def __test_save_article(self):
        self.skr_article_data['title'] = compare_title
        self.skr_article_data['content'] = compare_content
        data = json.dumps(self.skr_article_data)
        response = test_app.post('/api/v1/article',
                                 data=data,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 200)

        json_resp = json.loads(response.data)
        tools.assert_equals(response.status_code, 200)
        tools.assert_is_not_none(json_resp.get('data'))
        tools.assert_is_not_none(json_resp.get('data').get('source'))

        self.tech_article_data['title'] = test_title
        self.tech_article_data['content'] = test_content
        data = json.dumps(self.tech_article_data)
        response = test_app.post('/api/v1/article',
                                 data=data,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 200)

        self.tesla_article_data['title'] = test_title
        self.tesla_article_data['content'] = test_content
        data = json.dumps(self.tesla_article_data)
        response = test_app.post('/api/v1/article',
                                 data=data,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 200)

        self.article_url_list.append(self.skr_article_data['url'])
        self.article_url_list.append(self.tech_article_data['url'])
        self.article_url_list.append(self.tesla_article_data['url'])
    def __test_save_article(self):
        self.skr_article_data['title'] = compare_title
        self.skr_article_data['content'] = compare_content
        data = json.dumps(self.skr_article_data)
        response = test_app.post('/api/v1/article',
                                 data=data,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 200)

        json_resp = json.loads(response.data)
        tools.assert_equals(response.status_code, 200)
        tools.assert_is_not_none(json_resp.get('data'))
        tools.assert_is_not_none(json_resp.get('data').get('source'))

        self.tech_article_data['title'] = test_title
        self.tech_article_data['content'] = test_content
        data = json.dumps(self.tech_article_data)
        response = test_app.post('/api/v1/article',
                                 data=data,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 200)

        self.tesla_article_data['title'] = test_title
        self.tesla_article_data['content'] = test_content
        data = json.dumps(self.tesla_article_data)
        response = test_app.post('/api/v1/article',
                                 data=data,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 200)

        self.article_url_list.append(self.skr_article_data['url'])
        self.article_url_list.append(self.tech_article_data['url'])
        self.article_url_list.append(self.tesla_article_data['url'])
    def test_post(self):
        headers = {'Authorization': self.token}
        t_data = deepcopy(self.test_data)
        t_data['username'] = '******'
        t_data['email'] = '*****@*****.**'
        data = json.dumps(t_data)
        
        user = User.get_by_id(self.id)
        user.level = 1
        user.save()

        response = test_app.post('/api/v1/user',
                                 data=data,
                                 headers=headers,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 500)
        tools.assert_equals(json.loads(response.data).get('data'),
                            {'msg': "user don't has authority"})

        user.level = 9
        user.save()

        response = test_app.post('/api/v1/user',
                                 data=data,
                                 headers=headers,
                                 content_type='application/json')
        json_resp = json.loads(response.data)
        tools.assert_equals(response.status_code, 200)
        tools.assert_is_not_none(json_resp.get('data'))
        tools.assert_is_not_none(json_resp.get('data').get('id'))
Example #4
0
def test_boulder_gradings():
    """
    Tests grading functionality of the boulderGrading endpoint.
    """
    login_jwts = ratings_fixture()
    gradings = ['VB', 'V5', '6A+', '6B', '6C+', 'V16', '2', '7A', '6A+', '8A+']

    # POST gradings
    for i in range(10):
        h = [('loginJWT', login_jwts[i])]
        d = dict(grade=gradings[i], boulder_id=4)
        rv = test_app.post('%sboulder-gradings/' % api_prefix, data=d, headers=h)
        check_content_type(rv.headers)
        eq_(rv.status_code, 201)

    # GET single
    rv = test_app.get('%s%s' % (endpoint, 4))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(resp['grading'], '6B+')

    # Try to grade a unconfirmed boulder
    h = [('loginJWT', login_jwts[i])]
    d = dict(grade=gradings[i], boulder_id=8)
    rv = test_app.post('%sboulder-gradings/' % api_prefix, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)
    check_error_code(rv.data, "074")

    # Try to grade a non existing boulder
    h = [('loginJWT', login_jwts[i])]
    d = dict(grade=gradings[i], boulder_id=42)
    rv = test_app.post('%sboulder-gradings/' % api_prefix, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "073")

    # Try to give an invalid grading score
    h = [('loginJWT', login_jwts[i])]
    d = dict(grade='9C+', boulder_id=4)
    rv = test_app.post('%sboulder-gradings/' % api_prefix, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)
    check_error_code(rv.data, "075")

    # Regrade boulders
    for i in range(10):
        h = [('loginJWT', login_jwts[i])]
        d = dict(grade="2", boulder_id=4)
        rv = test_app.post('%sboulder-gradings/' % api_prefix, data=d, headers=h)
        check_content_type(rv.headers)
        eq_(rv.status_code, 201)

    # GET single (should now be graded fb 2)
    rv = test_app.get('%s%s' % (endpoint, 4))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(resp['grading'], '2')
Example #5
0
def confirmation_fixture():
    """
    Creates three users (admin, author, user) for testing the confirmation functionalites of the system and loggs them
    into the system.

    :return: A dictionary with login JWTs for the created users.
    """
    # Create Admininstrator
    d = dict(nickname="Admin", email="*****@*****.**", password="******", installAdmin=True)
    rv = test_app.post('%susers/' % api_prefix, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)

    # Login Administrator
    encoded_credentials = base64.b64encode('[email protected]:secret123!')
    h = [('Authorization', 'Basic %s' % encoded_credentials)]
    rv = test_app.get('%slogin/' % api_prefix, headers=h)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    ok_(isinstance(resp['loginJWT'], unicode))
    login_jwt_admin = resp['loginJWT']

    # Create User
    d = dict(nickname="User", email="*****@*****.**", password="******")
    rv = test_app.post('%susers/' % api_prefix, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)

    # Login User
    encoded_credentials = base64.b64encode('[email protected]:secret123!')
    h = [('Authorization', 'Basic %s' % encoded_credentials)]
    rv = test_app.get('%slogin/' % api_prefix, headers=h)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    ok_(isinstance(resp['loginJWT'], unicode))
    login_jwt_user = resp['loginJWT']

    # Create author
    d = dict(nickname="Author", email="*****@*****.**", password="******")
    rv = test_app.post('%susers/' % api_prefix, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)

    # Login author
    encoded_credentials = base64.b64encode('[email protected]:secret123!')
    h = [('Authorization', 'Basic %s' % encoded_credentials)]
    rv = test_app.get('%slogin/' % api_prefix, headers=h)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    ok_(isinstance(resp['loginJWT'], unicode))
    login_jwt_author = resp['loginJWT']

    return {'login_jwt_admin': login_jwt_admin,
            'login_jwt_user': login_jwt_user,
            'login_jwt_author': login_jwt_author}
def test_entityphoto_endpoints():
    """
    Tests CRUD functionality of the entityphoto endpoints.
    """
    # Create test user and login JWT
    d = dict(nickname="Jule", email="*****@*****.**", password="******", installAdmin=True)
    rv = test_app.post('%susers/' % api_prefix, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['nickname'], "Jule")
    eq_(resp['email'], "*****@*****.**")
    ok_(datetime.now() >= datetime.strptime(resp['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))
    encoded_credentials = base64.b64encode('[email protected]:secret123!')
    h = [('Authorization', 'Basic %s' % encoded_credentials)]
    rv = test_app.get('%slogin/' % api_prefix, headers=h)
    eq_(rv.status_code, 200)
    login_jwt = json.loads(rv.data)['data']['loginJWT']
    h = [('loginJWT', login_jwt)]

    # Create test entity
    d = dict(name="Nahetal", confirmed=True)
    rv = test_app.post('%sareas/' % api_prefix, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['name'], "Nahetal")
    ok_(datetime.now() >= datetime.strptime(resp['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))
    entity_id = resp['id']

    # GET (empty) collection
    # rv = test_app.get(endpoint)
    # check_content_type(rv.headers)
    # resp = json.loads(rv.data)['data']
    # eq_(rv.status_code, 200)
    # eq_(len(resp), 0)

    # POST with missing parameter
    # d = dict()
    # rv = test_app.post(endpoint, data=d, headers=h)
    # check_content_type(rv.headers)
    # eq_(rv.status_code, 400)

    # POST
    d = dict(
            text='Schones Nahetal ist schon!',
            entity_id=entity_id,
            entityphoto=open(os.path.join(testfiles_path,'w3000h2000.jpg'), 'r+b'))
    rv = test_app.post(endpoint, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['text'], "Schones Nahetal ist schon!")
    ok_(datetime.now() >= datetime.strptime(resp['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))
Example #7
0
 def test_login(self):
     r = test_app.post('/api/users/register',
                       data={
                           'name': 'Tester',
                           'username': '******',
                           'password': '******'
                       })
     eq_(r.status_code, 200)
     r = test_app.post('/api/users/login',
                       data={
                           'username': '******',
                           'password': '******'
                       },
                       headers={'Authorization': self.token})
     eq_(r.status_code, 200)
Example #8
0
def test_add_new_task():
    """
    Testing Post
    Adding new host to /hosts

    :var
    Username: ansible
    Password: default
    Json data example
    """
    log = logging.getLogger('post_new_host')
    username = '******'
    password = '******'

    host = dict(hosts="localhost", module="ping")
    rv = test_app.post('/eisen/api/v1.0/tasks', data=json.dumps(host),
                       content_type='application/json',
                       headers={
                           'Authorization': 'Basic ' + base64.b64encode(username +
                                                                        ":" + password)
                       })
    check_content_type_json(rv.headers)
    log.debug(rv.headers)
    # make sure we get a response
    eq_(rv.status_code, 201)
Example #9
0
def test_add_vars_4():
    """
    Testing Post
    Adding new host to /hosts

    :var
    Username: ansible
    Password: default
    Json data example
    """
    log = logging.getLogger('post_new_host')
    username = '******'
    password = '******'

    var = dict(variable_key="ansible_port", variable_value="22", host="127.0.0.1")
    rv = test_app.post('/eisen/api/v1.0/host/2/vars', data=json.dumps(var),
                       content_type='application/json',
                       headers={
                           'Authorization': 'Basic ' + base64.b64encode(username +
                                                                        ":" + password)
                       })
    check_content_type_json(rv.headers)
    log.debug(rv.headers)
    # make sure we get a response
    eq_(rv.status_code, 201)
    def test_cluster_get(self):
        """
        测试cluster的get接口

        """

        service = ClusterService('2018/08/15')
        service.save_to_db()

        response = test_app.get('/api/v1/cluster?day=20180815')
        tools.assert_equals(response.status_code, 200)

        json_resp = json.loads(response.data)
        tools.assert_equals(response.status_code, 200)
        tools.assert_is_not_none(json_resp.get('data'))
        data = json_resp.get('data')
        tools.assert_equals(len(data), 2)
        news = data[0]['news']
        tools.assert_equals(data[0]['topic']['title'], news[0]['title'])
        tools.assert_equals(news[0]['title'], news[1]['title'])
        first_topic = data[0]['topic']['title']
        second_topic = data[1]['topic']['title']

        # test update cluster, topic unchanged
        self.skr_article_data['title'] = compare_title
        self.skr_article_data['content'] = compare_content
        self.skr_article_data['url'] = 'http://www.skr.net/yeah/'
        data = json.dumps(self.skr_article_data)
        response = test_app.post('/api/v1/article',
                                 data=data,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 200)

        service = ClusterService('2018/08/15')
        service.save_to_db()

        response = test_app.get('/api/v1/cluster?day=20180815')
        tools.assert_equals(response.status_code, 200)

        json_resp = json.loads(response.data)
        tools.assert_equals(response.status_code, 200)
        tools.assert_is_not_none(json_resp.get('data'))
        data = json_resp.get('data')
        tools.assert_equals(len(data), 2)

        tools.assert_equals(first_topic, data[0]['topic']['title'])
        tools.assert_equals(second_topic, data[1]['topic']['title'])

        news = data[0]['news']
        tools.assert_equals(data[0]['topic']['title'], news[0]['title'])
        tools.assert_equals(news[0]['title'], news[1]['title'])

        news = data[1]['news']
        tools.assert_equals(data[1]['topic']['title'], news[0]['title'])
        tools.assert_equals(news[0]['title'], news[1]['title'])

        # test length of cluster is correct
        news_count = data[0]['news_count']
        tools.assert_equals(news_count, 2)
        self.__test_send_mail()
    def test_cluster_get(self):
        """
        测试cluster的get接口

        """

        service = ClusterService('2018/08/15')
        service.save_to_db()

        response = test_app.get('/api/v1/cluster?day=20180815')
        tools.assert_equals(response.status_code, 200)

        json_resp = json.loads(response.data)
        tools.assert_equals(response.status_code, 200)
        tools.assert_is_not_none(json_resp.get('data'))
        data = json_resp.get('data')
        tools.assert_equals(len(data), 2)
        news = data[0]['news']
        tools.assert_equals(data[0]['topic']['title'], news[0]['title'])
        tools.assert_equals(news[0]['title'], news[1]['title'])
        first_topic = data[0]['topic']['title']
        second_topic = data[1]['topic']['title']

        # test update cluster, topic unchanged
        self.skr_article_data['title'] = compare_title
        self.skr_article_data['content'] = compare_content
        self.skr_article_data['url'] = 'http://www.skr.net/yeah/'
        data = json.dumps(self.skr_article_data)
        response = test_app.post('/api/v1/article',
                                 data=data,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 200)

        service = ClusterService('2018/08/15')
        service.save_to_db()

        response = test_app.get('/api/v1/cluster?day=20180815')
        tools.assert_equals(response.status_code, 200)

        json_resp = json.loads(response.data)
        tools.assert_equals(response.status_code, 200)
        tools.assert_is_not_none(json_resp.get('data'))
        data = json_resp.get('data')
        tools.assert_equals(len(data), 2)

        tools.assert_equals(first_topic, data[0]['topic']['title'])
        tools.assert_equals(second_topic, data[1]['topic']['title'])

        news = data[0]['news']
        tools.assert_equals(data[0]['topic']['title'], news[0]['title'])
        tools.assert_equals(news[0]['title'], news[1]['title'])

        news = data[1]['news']
        tools.assert_equals(data[1]['topic']['title'], news[0]['title'])
        tools.assert_equals(news[0]['title'], news[1]['title'])

        # test length of cluster is correct
        news_count = data[0]['news_count']
        tools.assert_equals(news_count, 2)
        self.__test_send_mail()
    def __test_save_early_article(self):
        """
        ClusterService 中 query 的时间段是 昨天21:00 ~ 当天21:00,
        设置原始数据时间为 2018-08-14 21:00:00,新增三篇 2018-08-14 20:59:59 文章,
        不应该影响 `test_cluster_get` 测试的结果
        """
        skr_article_data = deepcopy(self.skr_article_data)
        skr_article_data['title'] = compare_title
        skr_article_data['content'] = compare_content
        skr_article_data['url'] += '111'
        skr_article_data['date'] -= 1
        data = json.dumps(skr_article_data)
        response = test_app.post('/api/v1/article',
                                 data=data,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 200)

        json_resp = json.loads(response.data)
        tools.assert_equals(response.status_code, 200)
        tools.assert_is_not_none(json_resp.get('data'))
        tools.assert_is_not_none(json_resp.get('data').get('source'))

        tech_article_data = deepcopy(self.tech_article_data)
        tech_article_data['title'] = test_title
        tech_article_data['content'] = test_content
        tech_article_data['url'] += '222'
        tech_article_data['date'] -= 1
        data = json.dumps(tech_article_data)
        response = test_app.post('/api/v1/article',
                                 data=data,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 200)

        tesla_article_data = deepcopy(self.tesla_article_data)
        tesla_article_data['title'] = test_title
        tesla_article_data['content'] = test_content
        tesla_article_data['url'] += '333'
        tesla_article_data['date'] -= 1
        data = json.dumps(tesla_article_data)
        response = test_app.post('/api/v1/article',
                                 data=data,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 200)

        self.article_url_list.append(self.skr_article_data['url'])
        self.article_url_list.append(self.tech_article_data['url'])
        self.article_url_list.append(self.tesla_article_data['url'])
    def __test_save_early_article(self):
        """
        ClusterService 中 query 的时间段是 昨天21:00 ~ 当天21:00,
        设置原始数据时间为 2018-08-14 21:00:00,新增三篇 2018-08-14 20:59:59 文章,
        不应该影响 `test_cluster_get` 测试的结果
        """
        skr_article_data = deepcopy(self.skr_article_data)
        skr_article_data['title'] = compare_title
        skr_article_data['content'] = compare_content
        skr_article_data['url'] += '111'
        skr_article_data['date'] -= 1
        data = json.dumps(skr_article_data)
        response = test_app.post('/api/v1/article',
                                 data=data,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 200)

        json_resp = json.loads(response.data)
        tools.assert_equals(response.status_code, 200)
        tools.assert_is_not_none(json_resp.get('data'))
        tools.assert_is_not_none(json_resp.get('data').get('source'))

        tech_article_data = deepcopy(self.tech_article_data)
        tech_article_data['title'] = test_title
        tech_article_data['content'] = test_content
        tech_article_data['url'] += '222'
        tech_article_data['date'] -= 1
        data = json.dumps(tech_article_data)
        response = test_app.post('/api/v1/article',
                                 data=data,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 200)

        tesla_article_data = deepcopy(self.tesla_article_data)
        tesla_article_data['title'] = test_title
        tesla_article_data['content'] = test_content
        tesla_article_data['url'] += '333'
        tesla_article_data['date'] -= 1
        data = json.dumps(tesla_article_data)
        response = test_app.post('/api/v1/article',
                                 data=data,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 200)

        self.article_url_list.append(self.skr_article_data['url'])
        self.article_url_list.append(self.tech_article_data['url'])
        self.article_url_list.append(self.tesla_article_data['url'])
Example #14
0
    def test_registration(self):
        r = test_app.post('/api/users/register',
                          data={
                              'name': 'Tester',
                              'username': '******',
                              'password': '******'
                          })
        eq_(r.status_code, 200)
        assert 'token' in r.data
        self.token = json.loads(r.data)['token']

        # try again
        r = test_app.post('/api/users/register',
                          data={
                              'name': 'Tester',
                              'username': '******',
                              'password': '******'
                          })
        eq_(r.status_code, 403)
Example #15
0
def test_user_routes():
  rv = test_app.get('/users')
  check_content_type(rv.headers)
  resp = json.loads(rv.data)
  #make sure we get a response
  eq_(rv.status_code,200)
  #make sure there are no users
  eq_(len(resp), 0)

  #create a user
  d = dict(first_name="User1First", last_name="User1Last",email="*****@*****.**")
  rv = test_app.post('/users', data=d)
  check_content_type(rv.headers)
  eq_(rv.status_code,201)

  #Verify we sent the right data back
  resp = json.loads(rv.data)
  eq_(resp["email"],"*****@*****.**")
  eq_(resp["first_name"],"User1First")
  eq_(resp["last_name"],"User1Last")

  #Get users again...should have one
  rv = test_app.get('/users')
  check_content_type(rv.headers)
  resp = json.loads(rv.data)
  #make sure we get a response
  eq_(rv.status_code,200)
  eq_(len(resp), 1)

  #GET the user with specified ID
  rv = test_app.get('/users/%s' % resp[0]['id'])
  check_content_type(rv.headers)
  eq_(rv.status_code,200)
  resp = json.loads(rv.data)
  eq_(resp["email"],"*****@*****.**")
  eq_(resp["first_name"],"User1First")
  eq_(resp["last_name"],"User1Last")

  #Try and add Duplicate User Email
  rv = test_app.post('/users', data=d)
  check_content_type(rv.headers)
  eq_(rv.status_code,500)
    def test_article_post(self):
        """
        测试article的post接口

        """
        response = test_app.post('/api/v1/article')
        tools.assert_equals(response.status_code, 400)
        data = json.dumps(self.tech_article_data)

        response = test_app.post('/api/v1/article',
                                 data=data,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 200)

        self.article_url_list.append(self.tech_article_data['url'])

        json_resp = json.loads(response.data)
        tools.assert_equals(response.status_code, 200)
        tools.assert_is_not_none(json_resp.get('data'))
        tools.assert_is_not_none(json_resp.get('data').get('source'))
    def test_article_post(self):
        """
        测试edited_article的post接口
        1、测试登录认证
        2、测试权限问题,普通用户不能提交
        """
        headers = {'Authorization': self.token + 'aaaa'}
        response = test_app.post('/api/v1/article')
        tools.assert_equals(response.status_code, 401)
        response = test_app.post('/api/v1/article', headers=headers)
        tools.assert_equals(response.status_code, 401)

        headers = {'Authorization': self.token}
        t_data = deepcopy(self.test_data2)
        t_data.pop('added')
        data = json.dumps(t_data)

        user = User.get_by_id(self.user_id)
        user.level = 1
        user.save()

        response = test_app.post('/api/v1/article',
                                 data=data,
                                 headers=headers,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 500)
        tools.assert_equals(json.loads(response.data)['data'],
                            {'msg': "user don't has authority"})

        user.level = 9
        user.save()

        response = test_app.post('/api/v1/article',
                                 data=data,
                                 headers=headers,
                                 content_type='application/json')
        json_resp = json.loads(response.data)
        tools.assert_equals(response.status_code, 200)
        tools.assert_is_not_none(json_resp.get('data'))
        tools.assert_is_not_none(json_resp.get('data').get('id'))
    def __test_login(self):
        # self.__test_save()
        test_user = {'username': self.username,
                     'password': self.password}
        test_user['password'] = self.password + '222'
        data = json.dumps(test_user)
        response = test_app.post('/api/v1/login',
                                 data=data,
                                 content_type='application/json')
        tools.assert_equals(response.status_code, 401)

        test_user['password'] = self.password
        data = json.dumps(test_user)
        response = test_app.post('/api/v1/login',
                                 data=data,
                                 content_type='application/json')

        tools.assert_equals(response.status_code, 200)
        json_resp = json.loads(response.data)
        tools.assert_is_not_none(json_resp.get('data'))
        tools.assert_is_not_none(json_resp.get('data').get('access_token'))
        self.token = f'JWT {json_resp["data"]["access_token"]}'
 def __test_send_mail(self):
     """
     测试邮件功能
     """
     data = dict(command='daily',
                 date='20180815',
                 email=['*****@*****.**', '*****@*****.**'])
     data = json.dumps(data)
     response = test_app.post('/api/v1/helper/sendmail',
                              data=data,
                              content_type='application/json')
     tools.assert_equals(response.status_code, 200)
     json_resp = json.loads(response.data).get('data')
     tools.assert_is_not_none(json_resp)
     tools.assert_equals(len(json_resp), 2)
     for result in json_resp:
         tools.assert_equals(result['status'], True)
 def __test_send_mail(self):
     """
     测试邮件功能
     """
     data = dict(command='daily',
                 date='20180815',
                 email=['*****@*****.**', '*****@*****.**']
                 )
     data = json.dumps(data)
     response = test_app.post('/api/v1/helper/sendmail',
                              data=data,
                              content_type='application/json')
     tools.assert_equals(response.status_code, 200)
     json_resp = json.loads(response.data).get('data')
     tools.assert_is_not_none(json_resp)
     tools.assert_equals(len(json_resp), 2)
     for result in json_resp:
         tools.assert_equals(result['status'], True)
def test_create_cube():
    """
    Tests cube creation through API
    """
    request_body = {'dimension': 10}
    response = test_app.post('/cubes', data=json.dumps(request_body), content_type='application/json')

    # Check status code and content type
    _check_content_type(response)
    _check_status_code(response)

    # Check returned id
    payload = _decode_response(response)
    data = payload['data']
    assert '_id' in data and data['_id']

    # Check object was actually created
    cube = get(data['_id'])
    assert cube is not None
Example #22
0
def test_protected_action_permission_endpoints():
    """
    Tests protected action permission functionality.
    """
    # Create test user
    d = dict(nickname="Jule", email="*****@*****.**", password="******")
    rv = test_app.post(endpoint, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)["data"]
    eq_(resp["nickname"], "Jule")
    eq_(resp["email"], "*****@*****.**")
    ok_(datetime.now() >= datetime.strptime(resp["time_created"][:-6], "%a, %d %b %Y %H:%M:%S"))

    # Try to get invalid permission
    d = dict(action="reset")
    encoded_credentials = base64.b64encode("[email protected]:secret123!")
    h = [("Authorization", "Basic %s" % encoded_credentials)]
    rv = test_app.post("%sprotected-action-permission/" % api_prefix, headers=h, data=d)
    eq_(rv.status_code, 400)

    # Login with invalid username
    d = dict(action="put")
    encoded_credentials = base64.b64encode("[email protected]:secret123!")
    h = [("Authorization", "Basic %s" % encoded_credentials)]
    rv = test_app.post("%sprotected-action-permission/" % api_prefix, headers=h, data=d)
    eq_(rv.status_code, 401)

    # Login with invalid password
    encoded_credentials = base64.b64encode("[email protected]:secret123!x")
    h = [("Authorization", "Basic %s" % encoded_credentials)]
    rv = test_app.post("%sprotected-action-permission/" % api_prefix, headers=h, data=d)
    eq_(rv.status_code, 401)

    # Login without credentials
    rv = test_app.post("%sprotected-action-permission/" % api_prefix, data=d)
    eq_(rv.status_code, 401)

    # Login and get permission JWT
    encoded_credentials = base64.b64encode("[email protected]:secret123!")
    h = [("Authorization", "Basic %s" % encoded_credentials)]
    rv = test_app.post("%sprotected-action-permission/" % api_prefix, headers=h, data=d)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)["data"]
    ok_(isinstance(resp["paJWT"], unicode))
Example #23
0
import json
# import nose
# from nose.tools import *

from tests import test_app


def check_content_type(headers):
    eq_(headers['Content-Type'], 'application/json')


rv = test_app.post('/create_job', data='{"url": "http://www.boohoo.com/"}')
check_content_type(rv.headers)
eq_(rv.status_code, 200)
Example #24
0
def test_crag_confirmation():
    """
    Tests confirmation functionality and associated deletion permissions of the crag endpoint.
    """
    login_jwts = confirmation_fixture()

    # Create Area
    area_d = dict(name="Nahetal")
    area_rv = test_app.post('%sareas/' % api_prefix, data=area_d,
                            headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(area_rv.headers)
    eq_(area_rv.status_code, 201)
    area_resp = json.loads(area_rv.data)['data']

    # Try to POST confirmed not being admin or mod
    d = dict(name="Alter Steinbruch", area_id='%s' % area_resp['id'], confirmed=True)
    rv = test_app.post(endpoint, data=d, headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, "056")

    # POST
    d = dict(name="Alter Steinbruch", area_id='%s' % area_resp['id'])
    rv = test_app.post(endpoint, data=d, headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']

    # GET (empty) collection
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    eq_(len(json.loads(rv.data)['data']), 0)

    # GET (empty) single
    rv = test_app.get('%s%s' % (endpoint, resp['id']))
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "034")

    # Try to DELETE by user
    rv = test_app.delete('%s%s' % (endpoint, resp['id']), headers=[('loginJWT', login_jwts['login_jwt_user'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, '047')

    # DELETE by admin
    rv = test_app.delete('%s%s' % (endpoint, resp['id']), headers=[('loginJWT', login_jwts['login_jwt_admin'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 204)

    # POST again
    d = dict(name="Alter Steinbruch", area_id='%s' % area_resp['id'])
    rv = test_app.post(endpoint, data=d, headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']

    # Try to confirm by author
    d = dict(name="Alter Steinbruch", area_id='%s' % area_resp['id'], confirmed=True)
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, '048')

    # Confirm by admin
    d = dict(name="Alter Steinbruch", area_id='%s' % area_resp['id'], confirmed=True)
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=[('loginJWT', login_jwts['login_jwt_admin'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)

    # GET one element collection
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    eq_(len(json.loads(rv.data)['data']), 1)

    # GET single
    rv = test_app.get('%s%s' % (endpoint, resp['id']))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)

    # Try to DELETE by author
    rv = test_app.delete('%s%s' % (endpoint, resp['id']), headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, '046')

    # DELETE by admin
    rv = test_app.delete('%s%s' % (endpoint, resp['id']), headers=[('loginJWT', login_jwts['login_jwt_admin'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 204)
Example #25
0
def test_crag_endpoints():
    """
    Tests CRUD functionality of the crag endpoint.
    """
    # Create test user and login JWT
    d = dict(nickname="Jule", email="*****@*****.**", password="******", installAdmin=True)
    rv = test_app.post('%susers/' % api_prefix, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['nickname'], "Jule")
    eq_(resp['email'], "*****@*****.**")
    ok_(datetime.now() >= datetime.strptime(resp['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))
    encoded_credentials = base64.b64encode('[email protected]:secret123!')
    h = [('Authorization', 'Basic %s' % encoded_credentials)]
    rv = test_app.get('%slogin/' % api_prefix, headers=h)
    eq_(rv.status_code, 200)
    login_jwt = json.loads(rv.data)['data']['loginJWT']
    h = [('loginJWT', login_jwt)]

    # GET (empty) collection
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    resp = json.loads(rv.data)['data']
    eq_(rv.status_code, 200)
    eq_(len(resp), 0)

    # POST without existing area
    d = dict(name="Alter Steinbruch", confirmed=True)
    rv = test_app.post(endpoint, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)

    # Create Area
    area_d = dict(name="Nahetal", confirmed=True)
    area_rv = test_app.post('%sareas/' % api_prefix, data=area_d, headers=h)
    check_content_type(area_rv.headers)
    eq_(area_rv.status_code, 201)
    area_resp = json.loads(area_rv.data)['data']

    # POST
    d = dict(name="Alter Steinbruch", area_id='%s' % area_resp['id'], confirmed=True)
    rv = test_app.post(endpoint, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['name'], "Alter Steinbruch")
    eq_(resp['area']['name'], area_resp['name'])
    eq_(len(resp['blocks']), 0)
    ok_(datetime.now() >= datetime.strptime(resp['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))

    # GET (populated) collection
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    resp = json.loads(rv.data)['data']
    eq_(rv.status_code, 200)
    eq_(len(resp), 1)

    # GET non existing single
    rv = test_app.get('%s%s' % (endpoint, 42))
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "034")

    # GET single
    rv = test_app.get('%s%s' % (endpoint, resp[0]['id']))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(resp['name'], "Alter Steinbruch")
    ok_(datetime.now() >= datetime.strptime(resp['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))

    # PUT
    d = dict(name="Klein Bleau", area_id='%s' % area_resp['id'])
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['name'], "Klein Bleau")
    ok_(datetime.strptime(resp['time_updated'][:-6], '%a, %d %b %Y %H:%M:%S') >= datetime.strptime(
            resp['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))

    # GET (updated) single
    rv = test_app.get('%s%s' % (endpoint, resp['id']))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(resp['name'], "Klein Bleau")

    # PUT non existing
    d = dict(name="Klein Bleau", area_id='%s' % area_resp['id'])
    rv = test_app.put('%s%s' % (endpoint, 42), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "070")

    # POST duplicate
    rv = test_app.post(endpoint, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 500)

    # DELETE single
    rv = test_app.delete('%s%s' % (endpoint, resp['id']), headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 204)

    # DELETE non existing single
    rv = test_app.delete('%s%s' % (endpoint, 42), headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "035")

    # GET (empty) collection
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    resp = json.loads(rv.data)['data']
    eq_(rv.status_code, 200)
    eq_(len(resp), 0)
Example #26
0
def test_comments():
    """
    Tests CRUD functionality of the comment endpoint.
    """
    login_jwts = ratings_fixture()

    # POST comments
    for i in range(3):
        h = [('loginJWT', login_jwts[i])]
        d = dict(text="Lorem ipsum number %s" % i, entity_id=1)
        rv = test_app.post(endpoint, data=d, headers=h)
        check_content_type(rv.headers)
        eq_(rv.status_code, 201)

    # GET comment list
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(len(resp), 3)

    # GET single
    rv = test_app.get("%s%s" % (endpoint, 1))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(resp['text'], "Lorem ipsum number 0")

    # GET non existing single
    rv = test_app.get("%s%s" % (endpoint, 42))
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "065")

    # POST children
    h = [('loginJWT', login_jwts[i])]
    d = dict(text="This is a child comment", entity_id=1, parent_id=1)
    rv = test_app.post(endpoint, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    child_resp = json.loads(rv.data)['data']

    # POST grandchildren
    h = [('loginJWT', login_jwts[i])]
    d = dict(text="This is a child comment", entity_id=1, parent_id=child_resp['id'])
    rv = test_app.post(endpoint, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)
    check_error_code(rv.data, "064")

    # POST children for non exiting parent
    h = [('loginJWT', login_jwts[i])]
    d = dict(text="This is a child comment", entity_id=1, parent_id=42)
    rv = test_app.post(endpoint, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)
    check_error_code(rv.data, "063")

    # GET comment list
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(len(resp), 4)

    # GET comment list for entity
    rv = test_app.get('%sentity/1/comments/' % api_prefix)
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(len(resp), 3)

    # GET comment list for entity without comments
    rv = test_app.get('%sentity/42/comments/' % api_prefix)
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(len(resp), 0)

    # Try to comment on an unconfirmed entity
    h = [('loginJWT', login_jwts[i])]
    d = dict(text="Lorem ipsum", entity_id=5)
    rv = test_app.post(endpoint, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)
    check_error_code(rv.data, "062")

    # Try to comment on a non existing entity
    h = [('loginJWT', login_jwts[i])]
    d = dict(text="Lorem ipsum", entity_id=42)
    rv = test_app.post(endpoint, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "061")

    # UPDATE as author
    h = [('loginJWT', login_jwts[0])]
    d = dict(text="New text", entity_id=1)
    rv = test_app.put("%s%s" % (endpoint, 1), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['text'], "New text")

    # UPDATE as non author
    h = [('loginJWT', login_jwts[1])]
    d = dict(text="Newer text", entity_id=1)
    rv = test_app.put("%s%s" % (endpoint, 1), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, "069")

    # UPDATE non existing
    h = [('loginJWT', login_jwts[1])]
    d = dict(text="Newer text", entity_id=1)
    rv = test_app.put("%s%s" % (endpoint, 42), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "068")

    # DELETE single as author
    h = [('loginJWT', login_jwts[0])]
    rv = test_app.delete("%s%s" % (endpoint, 1), headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 204)

    # GET now non existing child comment
    rv = test_app.get("%s%s" % (endpoint, child_resp['id']))
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "065")

    # DELETE non existing single as author
    h = [('loginJWT', login_jwts[0])]
    rv = test_app.delete("%s%s" % (endpoint, 1), headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "066")

    # DELETE single as non-author
    h = [('loginJWT', login_jwts[2])]
    rv = test_app.delete("%s%s" % (endpoint, 2), headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, "067")
Example #27
0
def test_ratings():
    """
    Tests rating functionality of the rating endpoint.
    """
    login_jwts = ratings_fixture()
    ratings = [1, 3, 5, 5, 2, 5, 3, 5, 4, 3]

    # POST ratings
    for i in range(10):
        h = [('loginJWT', login_jwts[i])]
        d = dict(score=ratings[i], entity_id=1)
        rv = test_app.post(endpoint, data=d, headers=h)
        check_content_type(rv.headers)
        eq_(rv.status_code, 201)

    # GET single entity
    rv = test_app.get('%sareas/%s' % (api_prefix, 1))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(resp['rating'], 3.6)

    # Try to rate an unconfirmed entity
    h = [('loginJWT', login_jwts[i])]
    d = dict(score=ratings[i], entity_id=5)
    rv = test_app.post(endpoint, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)
    check_error_code(rv.data, "077")

    # Try to rate a non existing entity
    h = [('loginJWT', login_jwts[i])]
    d = dict(score=ratings[i], entity_id=42)
    rv = test_app.post(endpoint, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "078")

    # Try to give an invalid rating score
    h = [('loginJWT', login_jwts[i])]
    d = dict(score=0, entity_id=1)
    rv = test_app.post(endpoint, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)
    check_error_code(rv.data, "076")

    # rePOST ratings
    for i in range(10):
        h = [('loginJWT', login_jwts[i])]
        d = dict(score='5', entity_id=1)
        rv = test_app.post(endpoint, data=d, headers=h)
        check_content_type(rv.headers)
        eq_(rv.status_code, 201)

    # GET single entity (should now be rated at 5)
    rv = test_app.get('%sareas/%s' % (api_prefix, 1))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(resp['rating'], 5)

    # Simple tests for the other entity types
    for i in range(2,5):
        h = [('loginJWT', login_jwts[i])]
        d = dict(score='3', entity_id=i)
        rv = test_app.post(endpoint, data=d, headers=h)
        check_content_type(rv.headers)
        eq_(rv.status_code, 201)

    # GET single entitys
    rv = test_app.get('%scrags/%s' % (api_prefix, 2))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(resp['rating'], 3)

    rv = test_app.get('%sblocks/%s' % (api_prefix, 3))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(resp['rating'], 3)

    rv = test_app.get('%sboulders/%s' % (api_prefix, 4))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(resp['rating'], 3)
Example #28
0
def test_boulder_confirmation():
    """
    Tests confirmation functionality and associated deletion permissions of the boulder endpoint.
    """
    login_jwts = confirmation_fixture()

    # Create Area
    area_d = dict(name="Eifel")
    area_rv = test_app.post('%sareas/' % api_prefix, data=area_d,
                            headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(area_rv.headers)
    eq_(area_rv.status_code, 201)
    area_resp = json.loads(area_rv.data)['data']

    # Create Crag
    crag_d = dict(name="Glees", area_id='%s' % area_resp['id'])
    crag_rv = test_app.post('%scrags/' % api_prefix, data=crag_d,
                            headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(crag_rv.headers)
    eq_(crag_rv.status_code, 201)
    crag_resp = json.loads(crag_rv.data)['data']

    # Create Block
    block_d = dict(name="Bleausard", crag_id='%s' % crag_resp['id'])
    block_rv = test_app.post('%sblocks/' % api_prefix, data=block_d,
                             headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(block_rv.headers)
    eq_(block_rv.status_code, 201)
    block_resp = json.loads(block_rv.data)['data']

    # Try to POST confirmed not being admin or mod
    d = dict(name="Es", grade="7b+", block_id='%s' % block_resp['id'], confirmed=True)
    rv = test_app.post(endpoint, data=d, headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, "058")

    # POST
    d = dict(name="Es", grade="7b+", block_id='%s' % block_resp['id'])
    rv = test_app.post(endpoint, data=d, headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']

    # GET (empty) collection
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    eq_(len(json.loads(rv.data)['data']), 0)

    # GET (empty) single
    rv = test_app.get('%s%s' % (endpoint, resp['id']))
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "032")

    # Try to DELETE by user
    rv = test_app.delete('%s%s' % (endpoint, resp['id']), headers=[('loginJWT', login_jwts['login_jwt_user'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, '053')

    # DELETE by admin
    rv = test_app.delete('%s%s' % (endpoint, resp['id']), headers=[('loginJWT', login_jwts['login_jwt_admin'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 204)

    # POST again
    d = dict(name="Es", grade="7b+", block_id='%s' % block_resp['id'])
    rv = test_app.post(endpoint, data=d, headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']

    # Try to confirm by author
    d = dict(name="Es", grade="7b+", block_id='%s' % block_resp['id'], confirmed=True)
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, '054')

    # Confirm by admin
    d = dict(name="Es", grade="7b+", block_id='%s' % block_resp['id'], confirmed=True)
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=[('loginJWT', login_jwts['login_jwt_admin'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)

    # GET one element collection
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    eq_(len(json.loads(rv.data)['data']), 1)

    # GET single
    rv = test_app.get('%s%s' % (endpoint, resp['id']))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)

    # Try to DELETE by author
    rv = test_app.delete('%s%s' % (endpoint, resp['id']), headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, '052')

    # DELETE by admin
    rv = test_app.delete('%s%s' % (endpoint, resp['id']), headers=[('loginJWT', login_jwts['login_jwt_admin'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 204)
Example #29
0
def test_boulder_endpoints():
    """
    Tests CRUD functionality of the boulder endpoint.
    """
    # Create test user and login JWT
    d = dict(nickname="Jule", email="*****@*****.**", password="******", installAdmin=True)
    rv = test_app.post('%susers/' % api_prefix, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['nickname'], "Jule")
    eq_(resp['email'], "*****@*****.**")
    ok_(datetime.now() >= datetime.strptime(resp['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))
    encoded_credentials = base64.b64encode('[email protected]:secret123!')
    h = [('Authorization', 'Basic %s' % encoded_credentials)]
    rv = test_app.get('%slogin/' % api_prefix, headers=h)
    eq_(rv.status_code, 200)
    login_jwt = json.loads(rv.data)['data']['loginJWT']
    h = [('loginJWT', login_jwt)]

    # GET (empty) collection
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    resp = json.loads(rv.data)['data']
    eq_(rv.status_code, 200)
    eq_(len(resp), 0)

    # POST without existing block
    d = dict(name="Es", confirmed=True)
    rv = test_app.post(endpoint, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)

    # Create Area
    area_d = dict(name="Eifel", confirmed=True)
    area_rv = test_app.post('%sareas/' % api_prefix, data=area_d, headers=h)
    check_content_type(area_rv.headers)
    eq_(area_rv.status_code, 201)
    area_resp = json.loads(area_rv.data)['data']

    # Create Crag
    crag_d = dict(name="Glees", area_id='%s' % area_resp['id'], confirmed=True)
    crag_rv = test_app.post('%scrags/' % api_prefix, data=crag_d, headers=h)
    check_content_type(crag_rv.headers)
    eq_(crag_rv.status_code, 201)
    crag_resp = json.loads(crag_rv.data)['data']

    # Create Block
    block_d = dict(name="Bleausard", crag_id='%s' % crag_resp['id'], confirmed=True)
    block_rv = test_app.post('%sblocks/' % api_prefix, data=block_d, headers=h)
    check_content_type(block_rv.headers)
    eq_(block_rv.status_code, 201)
    block_resp = json.loads(block_rv.data)['data']

    # POST with invalid grade
    d = dict(name="Es", grade="42B+", block_id='%s' % block_resp['id'], confirmed=True)
    rv = test_app.post(endpoint, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)
    check_error_code(rv.data, "059")

    # POST
    d = dict(name="Es", grade="7b+", block_id='%s' % block_resp['id'], confirmed=True)
    rv = test_app.post(endpoint, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['name'], "Es")
    eq_(resp['grade'], "7B+")
    eq_(resp['block']['name'], block_resp['name'])
    ok_(datetime.now() >= datetime.strptime(resp['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))

    # GET (populated) collection
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    resp = json.loads(rv.data)['data']
    eq_(rv.status_code, 200)
    eq_(len(resp), 1)

    # GET non existing single
    rv = test_app.get('%s%s' % (endpoint, 42))
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "032")

    # GET single
    rv = test_app.get('%s%s' % (endpoint, resp[0]['id']))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(resp['name'], "Es")
    ok_(datetime.now() >= datetime.strptime(resp['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))

    # PUT with invalid grade
    d = dict(name="The bittersweet moment of losing", grade="42b", block_id='%s' % block_resp['id'],
             rock_type="Vulkangestein", rock_texture="rauh", height=4.5, beta="Direct", landing_area="Perfekt")
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)
    check_error_code(rv.data, "060")

    # PUT
    d = dict(name="The bittersweet moment of losing", grade="8b", block_id='%s' % block_resp['id'],
             rock_type="Vulkangestein", rock_texture="rauh", height=4.5, beta="Direct", landing_area="Perfekt")
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['name'], "The bittersweet moment of losing")
    eq_(resp['grade'], "8B")
    eq_(resp['rock_type'], "Vulkangestein")
    eq_(resp['rock_texture'], "rauh")
    eq_(resp['beta'], "Direct")
    eq_(resp['landing_area'], "Perfekt")
    eq_(resp['height'], 4.5)
    ok_(datetime.strptime(resp['time_updated'][:-6], '%a, %d %b %Y %H:%M:%S') >= datetime.strptime(
            resp['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))

    # GET (updated) single
    rv = test_app.get('%s%s' % (endpoint, resp['id']))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(resp['name'], "The bittersweet moment of losing")
    eq_(resp['grade'], "8B")
    eq_(resp['rock_type'], "Vulkangestein")
    eq_(resp['rock_texture'], "rauh")
    eq_(resp['beta'], "Direct")
    eq_(resp['landing_area'], "Perfekt")
    eq_(resp['height'], 4.5)

    # PUT non existing
    d = dict(name="The bittersweet moment of losing", grade="8b", block_id='%s' % block_resp['id'],
             rock_type="Vulkangestein", rock_texture="rauh", height=4.5, beta="Direct", landing_area="Perfekt")
    rv = test_app.put('%s%s' % (endpoint, 42), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "071")

    # POST duplicate
    rv = test_app.post(endpoint, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 500)

    # DELETE single
    rv = test_app.delete('%s%s' % (endpoint, resp['id']), headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 204)

    # DELETE non existing single
    rv = test_app.delete('%s%s' % (endpoint, 42), headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "033")

    # GET (empty) collection
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    resp = json.loads(rv.data)['data']
    eq_(rv.status_code, 200)
    eq_(len(resp), 0)
Example #30
0
def test_user_endpoints():
    """
    Tests CRUD functionality of the user endpoint.
    """
    # GET (empty) collection
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    resp = json.loads(rv.data)['data']
    eq_(rv.status_code, 200)
    eq_(len(resp), 0)

    # POST with missing parameter
    d = dict()
    rv = test_app.post(endpoint, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)

    # POST
    d = dict(nickname="Jule", email="*****@*****.**", password="******")
    rv = test_app.post(endpoint, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['nickname'], "Jule")
    eq_(resp['email'], "*****@*****.**")
    ok_(datetime.now() >= datetime.strptime(resp['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))

    # GET (populated) collection
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    resp = json.loads(rv.data)['data']
    eq_(rv.status_code, 200)
    eq_(len(resp), 1)

    # Get single
    rv = test_app.get('%s%s' % (endpoint, resp[0]['id']))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(resp['nickname'], "Jule")
    eq_(resp['email'], "*****@*****.**")
    ok_(datetime.now() >= datetime.strptime(resp['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))

    # Post duplicate
    rv = test_app.post(endpoint, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 500)

    # POST without nickname or first & lastname
    d = dict(email="*****@*****.**", passwort="secret")
    rv = test_app.post(endpoint, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)
    check_error_code(rv.data, "008")

    # POST with invalid email
    d = dict(nickname="Jimmy", email="jimmywebb.de", password="******")
    rv = test_app.post(endpoint, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)
    check_error_code(rv.data, "009")

    # POST with invalid sex
    d = dict(nickname="Jimmy", email="*****@*****.**", password="******", sex="humbug")
    rv = test_app.post(endpoint, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)
    check_error_code(rv.data, "026")

    # Get put permission jwt
    encoded_credentials = base64.b64encode('[email protected]:secret123!')
    h = [('Authorization', 'Basic %s' % encoded_credentials)]
    d = dict(action='put')
    rv = test_app.post('%sprotected-action-permission/' % api_prefix, headers=h, data=d)
    eq_(rv.status_code, 200)
    put_jwt = json.loads(rv.data)['data']['paJWT']

    # Login and get JWT
    encoded_credentials = base64.b64encode('[email protected]:secret123!')
    h = [('Authorization', 'Basic %s' % encoded_credentials)]
    rv = test_app.get('%slogin/' % api_prefix, headers=h)
    eq_(rv.status_code, 200)
    login_jwt = json.loads(rv.data)['data']['loginJWT']

    # PUT without login token
    d = dict(nickname="Der Jan", email="*****@*****.**")
    h = [('paJWT', put_jwt)]
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=h)
    check_content_type(rv.headers)
    check_error_code(rv.data, "013")

    # PUT without permission token
    d = dict(nickname="Der Jan", email="*****@*****.**")
    h = [('loginJWT', login_jwt)]
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=h)
    check_content_type(rv.headers)
    check_error_code(rv.data, "006")

    # PUT with invalid permission
    h = [('paJWT', 'iAmAnIvalidToken')]
    d = dict(nickname="Der Jan", email="*****@*****.**")
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, "023")

    # PUT without nickname or first & lastname
    d = dict(firstname="Jan", email="*****@*****.**")
    h = [('paJWT', put_jwt), ('loginJWT', login_jwt)]
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)
    check_error_code(rv.data, "003")

    # PUT with invalid email
    d = dict(nickname="Jan", email="jan@hojerde")
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)
    check_error_code(rv.data, "004")

    # PUT with invalid sex
    d = dict(nickname="Jan", email="*****@*****.**", sex="humbug")
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 400)
    check_error_code(rv.data, "027")

    # PUT unprotected fields
    d = dict(nickname="Der Jan", email="*****@*****.**", firstname="Jan", lastname="Hojer",
             birthday="1993-02-01", size=1.94, sex='male')
    h = [('loginJWT', login_jwt)]
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['nickname'], "Der Jan")
    eq_(resp['email'], "*****@*****.**")
    eq_(resp['firstname'], "Jan")
    eq_(resp['lastname'], "Hojer")
    eq_(resp['size'], 1.94)
    eq_(resp['sex'], "male")
    eq_(datetime.strptime(resp['birthday'][:-6], '%a, %d %b %Y %H:%M:%S'), datetime(1993, 02, 01, 0, 0, 0))
    ok_(datetime.now() >= datetime.strptime(resp['time_updated'][:-6], '%a, %d %b %Y %H:%M:%S'))
    ok_(datetime.strptime(resp['time_updated'][:-6], '%a, %d %b %Y %H:%M:%S') >= datetime.strptime(
            resp['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))
    try:
        resp['refreshedJWT']
        ok_(False)
    except KeyError:
        ok_(True)

    # PUT protected fields (only password)
    d = dict(nickname="Der Jan", email="*****@*****.**", password="******")
    h = [('paJWT', put_jwt), ('loginJWT', login_jwt)]
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['nickname'], "Der Jan")
    eq_(resp['email'], "*****@*****.**")
    ok_(datetime.now() >= datetime.strptime(resp['time_updated'][:-6], '%a, %d %b %Y %H:%M:%S'))
    ok_(datetime.strptime(resp['time_updated'][:-6], '%a, %d %b %Y %H:%M:%S') >= datetime.strptime(
            resp['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))
    try:
        resp['refreshedJWT']
        ok_(False)
    except KeyError:
        ok_(True)

    # PUT protected fields
    d = dict(nickname="Der Jan", email="*****@*****.**", password="******")
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)
    eq_(resp['data']['nickname'], "Der Jan")
    eq_(resp['data']['email'], "*****@*****.**")
    ok_(datetime.now() >= datetime.strptime(resp['data']['time_updated'][:-6], '%a, %d %b %Y %H:%M:%S'))
    ok_(datetime.strptime(resp['data']['time_updated'][:-6], '%a, %d %b %Y %H:%M:%S') >= datetime.strptime(
            resp['data']['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))
    ok_(isinstance(resp['refreshedJWT'], unicode))
    login_jwt = resp['refreshedJWT']

    # PUT non existing
    d = dict(nickname="Der Jan", email="*****@*****.**", firstname="Jan", lastname="Hojer",
             birthday="1993-02-01", size=1.94, sex='male')
    h = [('loginJWT', login_jwt)]
    rv = test_app.put('%s%s' % (endpoint, 42), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "080")

    # PUT duplicate
    d = dict(nickname="Adam", email="*****@*****.**", password="******")
    rv = test_app.post(endpoint, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)

    d = dict(nickname="Adam", email="*****@*****.**")
    h = [('loginJWT', login_jwt)]
    rv = test_app.put('%s%s' % (endpoint, resp['data']['id']), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 500)

    # Get new put permission jwt
    encoded_credentials = base64.b64encode('[email protected]:geheim')
    h = [('Authorization', 'Basic %s' % encoded_credentials)]
    d = dict(action='put')
    rv = test_app.post('%sprotected-action-permission/' % api_prefix, headers=h, data=d)
    eq_(rv.status_code, 200)
    put_jwt = json.loads(rv.data)['data']['paJWT']

    d = dict(nickname="Der Jan", email="*****@*****.**")
    h = [('loginJWT', login_jwt), ('paJWT', put_jwt)]
    rv = test_app.put('%s%s' % (endpoint, resp['data']['id']), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 500)

    # GET (updated) single
    rv = test_app.get('%s%s' % (endpoint, resp['data']['id']))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    eq_(resp['nickname'], "Der Jan")
    eq_(resp['email'], "*****@*****.**")

    # Get delete permission jwt
    encoded_credentials = base64.b64encode('[email protected]:geheim')
    h = [('Authorization', 'Basic %s' % encoded_credentials)]
    d = dict(action='delete')
    rv = test_app.post('%sprotected-action-permission/' % api_prefix, headers=h, data=d)
    eq_(rv.status_code, 200)
    delete_jwt = json.loads(rv.data)['data']['paJWT']

    # DELETE single without permission
    rv = test_app.delete('%s%s' % (endpoint, resp['id']))
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, "025")

    # DELETE single with invalid permission token
    h = [('paJWT', 'iAmAnInvalidToken')]
    rv = test_app.delete('%s%s' % (endpoint, resp['id']), headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, "023")

    # DELETE single
    h = [('paJWT', delete_jwt)]
    rv = test_app.delete('%s%s' % (endpoint, resp['id']), headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 204)

    # GET (1-length) collection
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    resp = json.loads(rv.data)['data']
    eq_(rv.status_code, 200)
    eq_(len(resp), 1)
    def test_items(self):
        # register
        r = test_app.post('/api/users/register',data={'name':'Test','username':'******','password':'******'})
        eq_(r.status_code,200)
        assert 'token' in r.data
        authorization = {'Authorization':json.loads(r.data)['token']}

        # login
        r = test_app.post('/api/users/login',data={'username':'******','password':'******'},headers=authorization)
        eq_(r.status_code,200)

        # get all items
        r = test_app.get('/api/items',headers=authorization)
        eq_(r.status_code,200)
        assert 'items' in r.data
        eq_(json.loads(r.data)['items'],[])

        # create an item
        #r = test_app.post('/api/items',data={'text':'todo item 1'},headers=authorization)
        h = {'Content-Type':'application/json','Authorization':authorization['Authorization']}
        r = test_app.post('/api/items',data=json.dumps({'item':{'title':'todo item 1'}}),headers=h)
        eq_(r.status_code,200)

        # create an item
        #r = test_app.post('/api/items',data={'text':'todo item 2'},headers=authorization)
        r = test_app.post('/api/items',data=json.dumps({'item':{'title':'todo item 2'}}),headers=h)
        eq_(r.status_code,200)

        # get all items
        r = test_app.get('/api/items',headers=authorization)
        eq_(r.status_code,200)
        assert 'items' in r.data
        eq_(json.loads(r.data)['items'],[{'title':'todo item 1','completed':False,'id':1,'uri':'/api/items/1'},{'title':'todo item 2','completed':False,'id':2,'uri':'/api/items/2'}])

        # get one item
        r = test_app.get('/api/items/1',headers=authorization)
        eq_(r.status_code,200)
        eq_(json.loads(r.data),{'id':1,'title':'todo item 1','completed':False,'uri':'/api/items/1'})

        # get an item that doesn't exist
        r = test_app.get('/api/items/10',headers=authorization)
        eq_(r.status_code,403)

        # put new info for item
        r = test_app.put('/api/items/1',data=json.dumps({'item':{'title':'todo item changed','completed':True}}),headers=h)
        eq_(r.status_code,200)
        eq_(json.loads(r.data),{'id':1,'title':'todo item changed','completed':True,'uri':'/api/items/1'})

        # delete an item
        r = test_app.delete('/api/items/2',headers=authorization)
        eq_(r.status_code,200)

        # register a second user
        r = test_app.post('/api/users/register',data={'name':'Test2','username':'******','password':'******'})
        eq_(r.status_code,200)
        assert 'token' in r.data
        authorization = {'Authorization':json.loads(r.data)['token']}

        # login
        r = test_app.post('/api/users/login',data={'username':'******','password':'******'},headers=authorization)
        eq_(r.status_code,200)

        # get an item that doesn't belong to second user
        r = test_app.get('/api/items/1',headers=authorization)
        eq_(r.status_code,403)
Example #32
0
def test_area_confirmation():
    """
    Tests confirmation functionality and associated deletion permissions of the area endpoint.
    """
    login_jwts = confirmation_fixture()

    # Try to POST confirmed not being admin or mod
    d = dict(name="Nahetal", confirmed=True)
    rv = test_app.post(endpoint, data=d, headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, "055")

    # POST
    d = dict(name="Nahetal")
    rv = test_app.post(endpoint, data=d, headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']

    # GET (empty) collection
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    eq_(len(json.loads(rv.data)['data']), 0)

    # GET (empty) single
    rv = test_app.get('%s%s' % (endpoint, resp['id']))
    check_content_type(rv.headers)
    eq_(rv.status_code, 404)
    check_error_code(rv.data, "028")

    # Try to DELETE by user
    rv = test_app.delete('%s%s' % (endpoint, resp['id']), headers=[('loginJWT', login_jwts['login_jwt_user'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, '044')

    # DELETE by admin
    rv = test_app.delete('%s%s' % (endpoint, resp['id']), headers=[('loginJWT', login_jwts['login_jwt_admin'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 204)

    # POST again
    d = dict(name="Nahetal")
    rv = test_app.post(endpoint, data=d, headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']

    # Try to confirm by author
    d = dict(name="Nahetal", confirmed=True)
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, '045')

    # Confirm by admin
    d = dict(name="Nahetal", confirmed=True)
    rv = test_app.put('%s%s' % (endpoint, resp['id']), data=d, headers=[('loginJWT', login_jwts['login_jwt_admin'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)

    # GET one element collection
    rv = test_app.get(endpoint)
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)
    eq_(len(json.loads(rv.data)['data']), 1)

    # GET single
    rv = test_app.get('%s%s' % (endpoint, resp['id']))
    check_content_type(rv.headers)
    eq_(rv.status_code, 200)

    # Try to DELETE by author
    rv = test_app.delete('%s%s' % (endpoint, resp['id']), headers=[('loginJWT', login_jwts['login_jwt_author'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, '043')

    # DELETE by admin
    rv = test_app.delete('%s%s' % (endpoint, resp['id']), headers=[('loginJWT', login_jwts['login_jwt_admin'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 204)
Example #33
0
def test_unconfirmed_endpoint():
    """
    Tests functionality of the unconfirmed endpoint.
    """
    login_jwts = confirmation_fixture()
    h = [('loginJWT', login_jwts['login_jwt_author'])]

    # Create Area
    area_d = dict(name="Eifel")
    area_rv = test_app.post('%sareas/' % api_prefix, data=area_d, headers=h)
    check_content_type(area_rv.headers)
    eq_(area_rv.status_code, 201)
    area_resp = json.loads(area_rv.data)['data']

    # Create Crag
    crag_d = dict(name="Glees", area_id='%s' % area_resp['id'])
    crag_rv = test_app.post('%scrags/' % api_prefix, data=crag_d, headers=h)
    check_content_type(crag_rv.headers)
    eq_(crag_rv.status_code, 201)
    crag_resp = json.loads(crag_rv.data)['data']

    # Create Block
    block_d = dict(name="Bleausard", crag_id='%s' % crag_resp['id'])
    block_rv = test_app.post('%sblocks/' % api_prefix, data=block_d, headers=h)
    check_content_type(block_rv.headers)
    eq_(block_rv.status_code, 201)
    block_resp = json.loads(block_rv.data)['data']

    # Create Boulder
    boulder_d = dict(name="Es", grade="7b+", block_id='%s' % block_resp['id'])
    boulder_rv = test_app.post('%sboulders/' % api_prefix, data=boulder_d, headers=h)
    check_content_type(boulder_rv.headers)
    eq_(boulder_rv.status_code, 201)

    # GET collection as author
    rv = test_app.get('%sunconfirmed/' % api_prefix, headers=h)
    check_content_type(rv.headers)
    resp = json.loads(rv.data)['data']
    eq_(rv.status_code, 200)
    eq_(len(resp), 4)

    # GET collection as admin
    rv = test_app.get('%sunconfirmed/' % api_prefix, headers=[('loginJWT', login_jwts['login_jwt_admin'])])
    check_content_type(rv.headers)
    resp = json.loads(rv.data)['data']
    eq_(rv.status_code, 200)
    eq_(len(resp), 4)

    # GET collection as normal user
    rv = test_app.get('%sunconfirmed/' % api_prefix, headers=[('loginJWT', login_jwts['login_jwt_user'])])
    check_content_type(rv.headers)
    resp = json.loads(rv.data)['data']
    eq_(rv.status_code, 200)
    eq_(len(resp), 0)

    # Create Area as user
    area_d = dict(name="Nahetal")
    area_rv = test_app.post('%sareas/' % api_prefix, data=area_d, headers=[('loginJWT', login_jwts['login_jwt_user'])])
    check_content_type(area_rv.headers)
    eq_(area_rv.status_code, 201)

    # Confirm area by admin
    d = dict(name="Eifel", confirmed=True)
    rv = test_app.put('%sareas/%s' % (api_prefix, area_resp['id']), data=d,
                      headers=[('loginJWT', login_jwts['login_jwt_admin'])])
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)

    # GET collection as author
    rv = test_app.get('%sunconfirmed/' % api_prefix, headers=h)
    check_content_type(rv.headers)
    resp = json.loads(rv.data)['data']
    eq_(rv.status_code, 200)
    eq_(len(resp), 3)

    # GET collection as admin
    rv = test_app.get('%sunconfirmed/' % api_prefix, headers=[('loginJWT', login_jwts['login_jwt_admin'])])
    check_content_type(rv.headers)
    resp = json.loads(rv.data)['data']
    eq_(rv.status_code, 200)
    eq_(len(resp), 4)

    # GET collection as normal user
    rv = test_app.get('%sunconfirmed/' % api_prefix, headers=[('loginJWT', login_jwts['login_jwt_user'])])
    check_content_type(rv.headers)
    resp = json.loads(rv.data)['data']
    eq_(rv.status_code, 200)
    eq_(len(resp), 1)
Example #34
0
def ratings_fixture():
    """
    Creates an admin, ten users, two areas, crags, blocks and boulders (the first (id = 1) confirmed, the
    second (id = 2) unconfirmed) and returns the users login JWTs. As the entities are subclassed, the ids are the
    following:
    confirmed area: 1
    confirmed crag: 2
    confirmed block: 3
    confirmed boulder: 4
    unconfirmed area: 5
    unconfirmed crag: 6
    unconfirmed block: 7
    unconfirmed boulder: 8
    :return: A list of login JWTs where the first jwt has admin rights.
    """
    # Create test users and login JWTs
    login_jwts = []
    d = dict(nickname="Jule%s" % 42, email="*****@*****.**" % 42, password="******", installAdmin=True)
    rv = test_app.post('%susers/' % api_prefix, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    encoded_credentials = base64.b64encode('juliane%[email protected]:secret123!' % 42)
    h = [('Authorization', 'Basic %s' % encoded_credentials)]
    rv = test_app.get('%slogin/' % api_prefix, headers=h)
    eq_(rv.status_code, 200)
    login_jwts.append(json.loads(rv.data)['data']['loginJWT'])
    for i in range(9):
        d = dict(nickname="Jule%s" % i, email="*****@*****.**" % i, password="******")
        rv = test_app.post('%susers/' % api_prefix, data=d)
        check_content_type(rv.headers)
        eq_(rv.status_code, 201)
        encoded_credentials = base64.b64encode('juliane%[email protected]:secret123!' % i)
        h = [('Authorization', 'Basic %s' % encoded_credentials)]
        rv = test_app.get('%slogin/' % api_prefix, headers=h)
        eq_(rv.status_code, 200)
        login_jwts.append(json.loads(rv.data)['data']['loginJWT'])

    h = [('loginJWT', login_jwts[0])]

    # CONFIRMED
    # Create Area
    area_d = dict(name="Eifel", confirmed=True)
    area_rv = test_app.post('%sareas/' % api_prefix, data=area_d, headers=h)
    check_content_type(area_rv.headers)
    eq_(area_rv.status_code, 201)
    area_resp = json.loads(area_rv.data)['data']

    # Create Crag
    crag_d = dict(name="Glees", area_id='%s' % area_resp['id'], confirmed=True)
    crag_rv = test_app.post('%scrags/' % api_prefix, data=crag_d, headers=h)
    check_content_type(crag_rv.headers)
    eq_(crag_rv.status_code, 201)
    crag_resp = json.loads(crag_rv.data)['data']

    # Create Block
    block_d = dict(name="Bleausard", crag_id='%s' % crag_resp['id'], confirmed=True)
    block_rv = test_app.post('%sblocks/' % api_prefix, data=block_d, headers=h)
    check_content_type(block_rv.headers)
    eq_(block_rv.status_code, 201)
    block_resp = json.loads(block_rv.data)['data']

    # Create Boulder
    d = dict(name="Es", grade="7b+", block_id='%s' % block_resp['id'], confirmed=True)
    rv = test_app.post('%sboulders/' % api_prefix, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)

    # UNCONFIRMED
    # Create Area
    area_d = dict(name="Eifel2")
    area_rv = test_app.post('%sareas/' % api_prefix, data=area_d, headers=h)
    check_content_type(area_rv.headers)
    eq_(area_rv.status_code, 201)
    area_resp = json.loads(area_rv.data)['data']

    # Create Crag
    crag_d = dict(name="Glee2s", area_id='%s' % area_resp['id'])
    crag_rv = test_app.post('%scrags/' % api_prefix, data=crag_d, headers=h)
    check_content_type(crag_rv.headers)
    eq_(crag_rv.status_code, 201)
    crag_resp = json.loads(crag_rv.data)['data']

    # Create Block
    block_d = dict(name="Bleausard2", crag_id='%s' % crag_resp['id'])
    block_rv = test_app.post('%sblocks/' % api_prefix, data=block_d, headers=h)
    check_content_type(block_rv.headers)
    eq_(block_rv.status_code, 201)
    block_resp = json.loads(block_rv.data)['data']

    # Create Boulder
    d = dict(name="Es2", grade="7b+", block_id='%s' % block_resp['id'])
    rv = test_app.post('%sboulders/' % api_prefix, data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)

    return login_jwts
Example #35
0
def test_admins_and_mods():
    """
    Tests CRUD functionality of the user endpoints administrator and moderator functionality.
    """
    # POST
    d = dict(nickname="Jule", email="*****@*****.**", password="******", installAdmin=True)
    rv = test_app.post(endpoint, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['nickname'], "Jule")
    eq_(resp['email'], "*****@*****.**")
    eq_(resp['administrator'], True)
    eq_(resp['moderator'], True)
    ok_(datetime.now() >= datetime.strptime(resp['time_created'][:-6], '%a, %d %b %Y %H:%M:%S'))

    # Try to create initial administrator a second time
    d = dict(nickname="Juleee", email="*****@*****.**", password="******", installAdmin=True)
    rv = test_app.post(endpoint, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, "036")

    # Create a second user
    d = dict(nickname="Danny", email="*****@*****.**", password="******")
    rv = test_app.post(endpoint, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    id_danny = resp['id']

    # Create a third user
    d = dict(nickname="Jimmy", email="*****@*****.**", password="******")
    rv = test_app.post(endpoint, data=d)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    id_jimmy = resp['id']

    # Login Jimmy
    encoded_credentials = base64.b64encode('[email protected]:secret123!')
    h = [('Authorization', 'Basic %s' % encoded_credentials)]
    rv = test_app.get('%slogin/' % api_prefix, headers=h)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    ok_(isinstance(resp['loginJWT'], unicode))
    login_jwt_jimmy = resp['loginJWT']

    # Login Jule
    encoded_credentials = base64.b64encode('[email protected]:secret123!')
    h = [('Authorization', 'Basic %s' % encoded_credentials)]
    rv = test_app.get('%slogin/' % api_prefix, headers=h)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    ok_(isinstance(resp['loginJWT'], unicode))
    login_jwt_jule = resp['loginJWT']

    # Test if Jimmy can promote administrators
    d = dict(promoteToAdmin=True)
    h = [('loginJWT', login_jwt_jimmy)]
    rv = test_app.put('%spromote/%s' % (api_prefix, id_danny), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, "038")

    # Test if Jimmy can promote moderators
    d = dict(promoteToMod=True)
    h = [('loginJWT', login_jwt_jimmy)]
    rv = test_app.put('%spromote/%s' % (api_prefix, id_danny), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, "039")

    # Promote Jimmy to moderator
    d = dict(promoteToMod=True)
    h = [('loginJWT', login_jwt_jule)]
    rv = test_app.put('%spromote/%s' % (api_prefix, id_jimmy), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['nickname'], "Jimmy")
    eq_(resp['administrator'], False)
    eq_(resp['moderator'], True)

    # Login Jimmy again to get higher privileged login jwt
    encoded_credentials = base64.b64encode('[email protected]:secret123!')
    h = [('Authorization', 'Basic %s' % encoded_credentials)]
    rv = test_app.get('%slogin/' % api_prefix, headers=h)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    ok_(isinstance(resp['loginJWT'], unicode))
    login_jwt_jimmy = resp['loginJWT']

    # Test if Jimmy can promote moderators
    d = dict(promoteToMod=True)
    h = [('loginJWT', login_jwt_jimmy)]
    rv = test_app.put('%spromote/%s' % (api_prefix, id_danny), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['nickname'], "Danny")
    eq_(resp['administrator'], False)
    eq_(resp['moderator'], True)

    # Test if Jimmy can promote administrators
    d = dict(promoteToAdmin=True)
    h = [('loginJWT', login_jwt_jimmy)]
    rv = test_app.put('%spromote/%s' % (api_prefix, id_danny), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 401)
    check_error_code(rv.data, "038")

    # Promote Jimmy to administrator
    d = dict(promoteToAdmin=True)
    h = [('loginJWT', login_jwt_jule)]
    rv = test_app.put('%spromote/%s' % (api_prefix, id_jimmy), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['nickname'], "Jimmy")
    eq_(resp['administrator'], True)
    eq_(resp['moderator'], True)

    # Login Jimmy again to get higher privileged login jwt
    encoded_credentials = base64.b64encode('[email protected]:secret123!')
    h = [('Authorization', 'Basic %s' % encoded_credentials)]
    rv = test_app.get('%slogin/' % api_prefix, headers=h)
    eq_(rv.status_code, 200)
    resp = json.loads(rv.data)['data']
    ok_(isinstance(resp['loginJWT'], unicode))
    login_jwt_jimmy = resp['loginJWT']

    # Test if Jimmy can promote administrators
    d = dict(promoteToAdmin=True)
    h = [('loginJWT', login_jwt_jimmy)]
    rv = test_app.put('%spromote/%s' % (api_prefix, id_danny), data=d, headers=h)
    check_content_type(rv.headers)
    eq_(rv.status_code, 201)
    resp = json.loads(rv.data)['data']
    eq_(resp['nickname'], "Danny")
    eq_(resp['administrator'], True)
    eq_(resp['moderator'], True)