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_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')
    def test_article_paging(self):
        headers = {'Authorization': self.token}
        print(len(self.article_id_list))
        response = test_app.get('/api/v1/article', headers=headers)
        self.test_paging(response, 1)

        headers = {'Authorization': self.token}
        response = test_app.get('/api/v1/article?page=2&page_size=20',
                                headers=headers)
        self.test_paging(response, 2)
Exemple #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}
Exemple #6
0
def test_added_hosts():
    """
    Check if added host is present.

    :var
    Username: ansible
    Password: default
    """
    log = logging.getLogger('added_hosts')
    username = '******'
    password = '******'

    rv = test_app.get('/eisen/api/v1.0/host/2', headers={
        'Authorization': 'Basic ' + base64.b64encode(username +
                                                     ":" + password)
    })
    check_content_type_json(rv.headers)
    resp = json.loads(rv.data)
    log.debug(rv.data)
    # make sure we get a response
    eq_(rv.status_code, 200)
    # make sure there are no users
    eq_(len(resp), 1)
    eq_(resp["host"]["host"], "127.0.0.1")
    eq_(resp["host"]["groups"], "vmware")
Exemple #7
0
def test_added_task():
    """
    Test execution of default task 1
    ping

    :var
    Username: ansible
    Password: default
    """
    log = logging.getLogger('task')
    username = '******'
    password = '******'

    rv = test_app.get('/eisen/api/v1.0/task/2/run',
                      headers={'Authorization': 'Basic ' +
                                                base64.b64encode(username +
                                                                 ":" + password)
                               })
    check_content_type_json(rv.headers)
    resp = json.loads(rv.data)
    log.debug(rv.data)
    # make sure we get a response
    eq_(rv.status_code, 200)
    # make sure there are no users
    eq_(len(resp), 1)
    eq_(resp["task"], "task started")
def test_query_cube():
    """
    Tests cube querying through API
    """
    # Create cube
    cube = Cube(4)
    cube.update(2, 2, 2, 4)
    cube_id = store(cube)

    response = test_app.get('/cubes/%s?x1=1&y1=1&x2=3&y2=3' % cube_id)

    _check_status_code(response)
    _check_content_type(response)

    data = _decode_response(response)['data']

    # Cube retrieved is the one we asked for
    eq_(data['_id'], cube_id)
    parameters = data['params']

    # Check parameters used to perform the summations match params passed as input and defaults
    eq_(parameters['x1'], 1)
    eq_(parameters['y1'], 1)
    eq_(parameters['z1'], 1)
    eq_(parameters['x2'], 3)
    eq_(parameters['y2'], 3)
    eq_(parameters['z2'], 4)
    eq_(data['result'], 4)
Exemple #9
0
def test_check_os():
    """
    Check for variable associated to added host

    :var
    Username: ansible
    Password: default
    """
    log = logging.getLogger('added_host_vars')
    username = '******'
    password = '******'

    rv = test_app.get('/eisen/api/v1.0/os_check',
                      headers={'Authorization': 'Basic ' +
                                                base64.b64encode(username +
                                                                 ":" + password)
                               })
    check_content_type_json(rv.headers)
    resp = json.loads(rv.data)
    # log.debug(rv.data)
    log2.debug(rv.data)
    # make sure we get a response
    #eq_(rv.status_code, 200)
    # make sure there are no users
    #eq_(len(resp), 1)
    def test_me(self):
        headers = {'Authorization': self.token}
        response = test_app.get('/api/v1/user/me', headers=headers)
        tools.assert_equals(response.status_code, 200)
        json_resp = json.loads(response.data)

        user_data = json_resp.get('data')
        user = User.get_by_id(self.id)
        tools.assert_equals(user_data, user.api_response())
        tools.assert_is_none(user_data.get('password'))

        headers = {'Authorization': self.token + 'aaaa'}
        response = test_app.get('/api/v1/user/me')
        tools.assert_equals(response.status_code, 401)

        response = test_app.get('/api/v1/user/me', headers=headers)
        tools.assert_equals(response.status_code, 401)
 def test_article_get(self):
     headers = {'Authorization': self.token}
     test_article = Article.get_by_id(self.article_id_list[1])
     url = f'/api/v1/article/{str(self.article_id_list[1])}'
     response = test_app.get(url, headers=headers)
     json_resp = json.loads(response.data)
     tools.assert_equals(response.status_code, 200)
     tools.assert_is_not_none(json_resp['data'])
     tools.assert_equals(json_resp['data'], test_article.api_response())
Exemple #12
0
def test_Authenticate():
    # test request Authenticating
    rv = test_app.get('/api/v1/user/x5050')
    check_content_type(rv.headers)
    resp = json.loads(rv.data)
    eq_(rv.status_code, 401)
    eq_(
        resp["error"],
        'Could not verify your access level for that URL. You have to login with proper credentials'
    )
Exemple #13
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_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'))
Exemple #15
0
def test_failed_auth():
    """
    failing Basic Auth

    sending no header
    """
    rv = test_app.get('/eisen/api/v1.0/agent')
    check_content_type_html(rv.headers)
    eq_(rv.data, 'Unauthorized Access')
    # make sure we get a response
    eq_(rv.status_code, 401)
Exemple #16
0
def test_login_endpoints():
    """
    Tests login 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"))

    # Login with invalid username
    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, 401)

    # Login with invalid password
    encoded_credentials = base64.b64encode("[email protected]:secret123!x")
    h = [("Authorization", "Basic %s" % encoded_credentials)]
    rv = test_app.get("%slogin/" % api_prefix, headers=h)
    eq_(rv.status_code, 401)

    # Login without credentials
    rv = test_app.get("%slogin/" % api_prefix)
    eq_(rv.status_code, 401)

    # 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)
    resp = json.loads(rv.data)["data"]
    ok_(isinstance(resp["loginJWT"], unicode))
def test_get_cube():
    """
    Tests cube retrieval through API
    """
    # Store cube
    cube_id = store(Cube(4))

    # Get it back
    response = test_app.get('/cubes/%s' % cube_id)
    _check_status_code(response)
    _check_content_type(response)

    data = _decode_response(response)['data']

    # Must be expected cube
    eq_(data['_id'], cube_id)
    assert 'params' not in data and 'result' not in data
Exemple #18
0
def test_packages():
    """
    Check for variable associated to added host

    :var
    Username: ansible
    Password: default
    """
    log = logging.getLogger('added_host_vars')
    username = '******'
    password = '******'

    rv = test_app.get('/eisen/api/v1.0/package_retrive',
                      headers={'Authorization': 'Basic ' +
                                                base64.b64encode(username +
                                                                 ":" + password)
                               })
    check_content_type_json(rv.headers)
    resp = json.loads(rv.data)
    # log.debug(rv.data)
    log2.debug(rv.data)
def test_list_all_cubes():
    """
    Tests cube indexing through API
    """
    # Insert a bunch of cubes

    cubes_ids = set()
    for i in range(10):
        cubes_ids.add(store(Cube(dimension=i + 1)))

    # Now list all cubes
    response = test_app.get('/cubes')

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

    # Extract list of cubes.
    data = _decode_response(response)['data']
    eq_(len(data), 10)  # We inserted 10. We expect 10.
    eq_(cubes_ids, set([c['_id'] for c in data]))  # Ids must match.
Exemple #20
0
def test_success_auth():
    """
    Succesful Basic Auth
    Request agent

    :var
    Username: ansible
    Password: default
    """
    username = '******'
    password = '******'

    rv = test_app.get('/eisen/api/v1.0/agent', headers={
        'Authorization': 'Basic ' + base64.b64encode(username +
                                                     ":" + password)
    })
    check_content_type_json(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), 1)
Exemple #21
0
def test_hosts():
    """
    get hosts information

    :var
    Username: ansible
    Password: default
    """
    log = logging.getLogger('hosts')
    username = '******'
    password = '******'

    rv = test_app.get('/eisen/api/v1.0/hosts', headers={
        'Authorization': 'Basic ' + base64.b64encode(username +
                                                     ":" + password)
    })
    check_content_type_json(rv.headers)
    resp = json.loads(rv.data)
    log.debug(rv.data)
    # make sure we get a response
    eq_(rv.status_code, 200)
    # make sure there are no users
    eq_(len(resp), 1)
Exemple #22
0
def test_name():
  result = test_app.get('/Yohannes')
  eq_(result.data, "Hello Yohannes!")
  eq_(result.status_code, 200)
Exemple #23
0
def test_home():
  result = test_app.get('/')
  eq_(result.data, "Hello World!")
  eq_(result.status_code, 200)
Exemple #24
0
def test_name():
    result = test_app.get('/Yohannes')
    eq_(result.data, "Hello Yohannes!")
    eq_(result.status_code, 200)
 def setUp(self):
     self.response = test_app.get('/seasonsummary')
Exemple #26
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)
Exemple #27
0
def test_added_task_result():
    """
    Test execution of default task 1
    ping

    :var
    Username: ansible
    Password: default
    """
    log = logging.getLogger('task')
    username = '******'
    password = '******'

    # task is not ready
    rv = test_app.get('/eisen/api/v1.0/task/2/result',
                      headers={'Authorization': 'Basic ' +
                                                base64.b64encode(username +
                                                                 ":" + password)
                               })
    check_content_type_json(rv.headers)
    resp = json.loads(rv.data)
    log.debug(rv.data)
    # make sure we get a response
    eq_(rv.status_code, 200)
    # make sure there are no users
    eq_(len(resp), 1)
    eq_(resp["task"], "not ready yet!")

    #check untill task is ready
    i = 10
    while resp["task"] == "not ready yet!":
            rv = test_app.get('/eisen/api/v1.0/task/2/result',
                      headers={'Authorization': 'Basic ' +
                                                base64.b64encode(username +
                                                                 ":" + password)
                               })
            check_content_type_json(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), 1)
            if i == 0:
                resp["task"] = "time out during test"
                log.debug(resp)
            i -= 1
            time.sleep(1)


    # task is ready
    rv = test_app.get('/eisen/api/v1.0/task/2/result',
                      headers={'Authorization': 'Basic ' +
                                                base64.b64encode(username +
                                                                 ":" + password)
                               })
    check_content_type_json(rv.headers)
    resp = json.loads(rv.data)
    log.debug(rv.data)
    # make sure we get a response
    eq_(rv.status_code, 200)
    # make sure there are no users
    eq_(len(resp), 1)
    eq_(resp["task"]['contacted']['localhost']["ping"], "pong")
Exemple #28
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)
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)
Exemple #30
0
def test_dashboard_server_is_up_and_running():
    # Go to the homepage
    response = test_app.get("/")
    # If the status code is 200 (success) then the test works.
    assert response.status_code == 200
Exemple #31
0
def test_dashboard_server_is_up_and_running():
    response = test_app.get("/")
    assert response.status_code == 200
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")
Exemple #33
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)
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)
Exemple #35
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)
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)
Exemple #37
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)
Exemple #38
0
def test_home():
    result = test_app.get('/')
    eq_(result.data, "Hello World!")
    eq_(result.status_code, 200)
Exemple #39
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)
    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)