Example #1
0
    def test_create_zone(
        self,
        client,
        common_data_mock,
        zone_data,
        admin_apikey,
        created_zone_data
    ):
        with patch('app.lib.helper.requests.request') as mock_post, \
             patch('app.blueprints.api.Domain') as mock_domain:
            mock_post.return_value.status_code = 201
            mock_post.return_value.content = json.dumps(created_zone_data)
            mock_post.return_value.headers = {}
            mock_domain.return_value.update.return_value = True

            res = client.post(
                "/api/v1/servers/localhost/zones",
                headers=admin_apikey,
                data=json.dumps(zone_data),
                content_type="application/json"
            )
            data = res.get_json(force=True)
            data['rrsets'] = []

            validate_zone(data)
            assert res.status_code == 201
    def test_get_multiple_zones(self, client, initial_data, zone_data,
                                basic_auth_admin_headers):
        res = client.post("/api/v1/pdnsadmin/zones",
                          headers=basic_auth_admin_headers,
                          data=json.dumps(zone_data),
                          content_type="application/json")
        data = res.get_json(force=True)
        data['rrsets'] = []

        validate_zone(data)
        assert res.status_code == 201

        res = client.get("/api/v1/pdnsadmin/zones",
                         headers=basic_auth_admin_headers)
        data = res.get_json(force=True)
        fake_domain = namedtuple("Domain", data[0].keys())(*data[0].values())
        domain_schema = DomainSchema(many=True)

        json.dumps(domain_schema.dump([fake_domain]))
        assert res.status_code == 200

        zone_url_format = "/api/v1/pdnsadmin/zones/{0}"
        zone_url = zone_url_format.format(zone_data['name'].rstrip("."))
        res = client.delete(zone_url, headers=basic_auth_admin_headers)

        assert res.status_code == 204
    def test_delete_zone(
        self,
        client,
        initial_apikey_data,
        zone_data,
        admin_apikey_integration
    ):
        res = client.post(
            "/api/v1/servers/localhost/zones",
            headers=admin_apikey_integration,
            data=json.dumps(zone_data),
            content_type="application/json"
        )
        data = res.get_json(force=True)
        data['rrsets'] = []

        validate_zone(data)
        assert res.status_code == 201

        zone_url_format = "/api/v1/servers/localhost/zones/{0}"
        zone_url = zone_url_format.format(zone_data['name'].rstrip("."))
        res = client.delete(
            zone_url,
            headers=admin_apikey_integration
        )

        assert res.status_code == 204
Example #4
0
def test_get_should_return_operator(client):
    client.post(
        "/operators",
        json=operator_not_written,
    )

    res = client.get("/operators/3")

    assert res.status_code == 200
    assert res.json["firstname"] == operator_not_written["firstname"]
    assert res.json["lastname"] == operator_not_written["lastname"]
    assert res.json["birthdate"] == operator_not_written["birthdate"].strftime(
        "%Y-%m-%d")
    assert res.json["fiscalcode"] == operator_not_written["fiscalcode"]
    assert res.json["email"] == operator_not_written["email"]
    assert res.json["phonenumber"] == operator_not_written["phonenumber"]
Example #5
0
def test_login_should_be_wrong_credentials(client):
    client.post(
        "/operators",
        json=operator_not_written,
    )

    res = client.post(
        "/operators/login",
        json={
            "email": operator_not_written["email"],
            "password": "******"
        },
    )

    assert res.status_code == 200
    assert res.json["message"] == "Wrong credentials"
Example #6
0
def test_patch_should_be_successful(client, db):
    client.post(
        "/users",
        json=user1,
    )

    res = client.patch("/users/1",
                       json={
                           "firstname": "Giovanni",
                           "lastname": "Verdi"
                       })
    q = db.session.query(User).filter_by(id=1).first()

    assert res.status_code == 204
    assert q.firstname == "Giovanni"
    assert q.lastname == "Verdi"
Example #7
0
def test_login_should_be_successful(client):
    client.post(
        "/operators",
        json=operator_not_written,
    )

    res = client.post(
        "/operators/login",
        json={
            "email": operator_not_written["email"],
            "password": operator_not_written["password"],
        },
    )

    assert res.status_code == 200
    assert res.json["message"] == "Success"
Example #8
0
 def test_unknown_session_id_response_body(self, client):
     response = client.post('/rulesets',
                            json={'session_id': str(ObjectId())})
     assert response.get_json() == {
         'status': 404,
         'field': 'session_id',
         'error': 'unknown'
     }
Example #9
0
    def test_get_multiple_apikey(self, client, initial_data, apikey_data,
                                 zone_data, basic_auth_admin_headers):
        res = client.post("/api/v1/pdnsadmin/zones",
                          headers=basic_auth_admin_headers,
                          data=json.dumps(zone_data),
                          content_type="application/json")
        data = res.get_json(force=True)

        assert res.status_code == 201

        res = client.post("/api/v1/pdnsadmin/apikeys",
                          headers=basic_auth_admin_headers,
                          data=json.dumps(apikey_data),
                          content_type="application/json")
        data = res.get_json(force=True)

        validate_apikey(data)
        assert res.status_code == 201

        res = client.get("/api/v1/pdnsadmin/apikeys",
                         headers=basic_auth_admin_headers)
        data = res.get_json(force=True)

        fake_role = namedtuple(
            "Role", data[0]['role'].keys())(*data[0]['role'].values())

        data[0]['domains'] = []
        data[0]['role'] = fake_role
        fake_apikey = namedtuple("ApiKey", data[0].keys())(*data[0].values())
        apikey_schema = ApiKeySchema(many=True)

        json.dumps(apikey_schema.dump([fake_apikey]))
        assert res.status_code == 200

        apikey_url_format = "/api/v1/pdnsadmin/apikeys/{0}"
        apikey_url = apikey_url_format.format(fake_apikey.id)
        res = client.delete(apikey_url, headers=basic_auth_admin_headers)

        assert res.status_code == 204

        zone_url_format = "/api/v1/pdnsadmin/zones/{0}"
        zone_url = zone_url_format.format(zone_data['name'].rstrip("."))
        res = client.delete(zone_url, headers=basic_auth_admin_headers)

        assert res.status_code == 204
Example #10
0
def test_login(client: client):
    # login with no credentials
    response = client.post("/api/auth/login", json={})
    assert_json_status(response, BadRequest.code)

    # login with incorrect credentials
    response = client.post("/api/auth/login", json=CREDENTIALS_BAD)
    assert_json_status(response, Unauthorized.code)

    # successful login
    response = client.post("/api/auth/login", json=CREDENTIALS_GOOD)
    assert_json_status(response, OK_STATUS)
    store_check_auth(response, credentials=CREDENTIALS_GOOD)

    # successful alt login
    response = client.post("/api/auth/login", json=CREDENTIALS_ALT)
    assert_json_status(response, OK_STATUS)
    store_check_auth(response, credentials=CREDENTIALS_ALT)
Example #11
0
def test_login_should_be_authority_not_found(client):
    res = client.post(
        "/authorities/login",
        json={
            "email": health_authority_not_written["email"],
            "password": health_authority_not_written["password"],
        },
    )

    assert res.status_code == 404
    assert res.json["message"] == "Authority not found"
Example #12
0
def test_should_mark_one_user_through_phonenumber(client, db):
    res = client.post(
        "/authorities/1/mark",
        json={"identifier": user1["phonenumber"], "duration": 15},
        follow_redirects=False,
    )

    q = User.query.filter_by(id=1).first()

    assert q.marked
    assert res.status_code == 204
Example #13
0
def test_login_should_be_operator_not_found(client):
    res = client.post(
        "/operators/login",
        json={
            "email": operator_not_written["email"],
            "password": operator_not_written["password"],
        },
    )

    assert res.status_code == 404
    assert res.json["message"] == "Operator not found"
Example #14
0
def test_login_should_be_user_not_found(client):
    res = client.post(
        "/users/login",
        json={
            "email": "thisdoesnotexist",
            "password": "******",
        },
    )

    assert res.status_code == 404
    assert res.json["message"] == "User not found"
Example #15
0
def test_create_character(client: client):
    # create a character with too much stats
    response = client.post("/api/game/create_character",
                           json={
                               "name": "good",
                               "description": "good",
                               "strength": 10,
                               "dexterity": 10,
                               "health": 10,
                               "special": "lightning"
                           },
                           headers=with_auth_headers())
    assert_json_status(response, BadRequest.code)

    # create a character for "GOOD"
    response = client.post(
        "/api/game/create_character",
        json={
            "name": "good",
            "description": "good",
            "strength": 5,
            "dexterity": 10,
            "health": 5,
            "special": "lightning"
        },
        headers=with_auth_headers(credentials=CREDENTIALS_GOOD))
    assert_json_status(response, OK_STATUS)

    # create a character for "ALT"
    response = client.post(
        "/api/game/create_character",
        json={
            "name": "alt",
            "description": "alt",
            "strength": 10,
            "dexterity": 1,
            "health": 9,
            "special": "wither"
        },
        headers=with_auth_headers(credentials=CREDENTIALS_ALT))
    assert_json_status(response, OK_STATUS)
def create_review(client, message=None, rating=5, redirect=True):
    if not message:
        message = "It was a delicious dinner, but initially the service was not so excellent in the speed of serving the meals."

    return client.post(
        "/restaurants/1",
        data=dict(
            rating=rating,
            message=message,
        ),
        follow_redirects=redirect,
    )
Example #17
0
def test_bad_access_token_user_login(client, app, mocker):  # noqa
    mocker.patch('requests.get',
                 MockResponse(401, {'error': {
                     'message': 'oops'
                 }}))

    data = {'timezone': 'US/Pacific', 'access_token': '123'}
    res = client.post(flask.url_for('auth.login'),
                      data=json.dumps(data),
                      headers={'Content-Type': 'application/json'})

    assert res.status_code == 401
Example #18
0
def test_decide_challenge(client: client):
    # accept the challenge as ALT
    response = client.post(
        "/api/game/challenge/decide",
        json={
            "id": VARS["challenge_id"],
            "accept": True,
            "character": "alt"
        },
        headers=with_auth_headers(credentials=CREDENTIALS_ALT))
    assert_json_status(response, OK_STATUS)
    VARS["game_id"] = response.json["game_id"]
Example #19
0
def test_create_challenge(client: client):
    # send a challenge from GOOD to ALT
    response = client.post("/api/game/challenge",
                           json={
                               "defender": CREDENTIALS_ALT["username"],
                               "challenge_config": {
                                   "max_turns": 5,
                                   "character": "good"
                               }
                           },
                           headers=with_auth_headers())
    assert_json_status(response, OK_STATUS)
    VARS["challenge_id"] = response.json["challenge_id"]
Example #20
0
def test_post_should_be_successful(client, db):
    res = client.post("/users", json=user_not_written)

    q = db.session.query(User).filter_by(id=7).first()

    assert res.status_code == 201
    assert q.firstname == user_not_written["firstname"]
    assert q.lastname == user_not_written["lastname"]
    assert q.birthdate.strftime(
        "%Y-%m-%d") == user_not_written["birthdate"].strftime("%Y-%m-%d")
    assert q.fiscalcode == user_not_written["fiscalcode"]
    assert q.email == user_not_written["email"]
    assert q.phonenumber == user_not_written["phonenumber"]
def test_user_should_not_create_review_when_message_is_less_than_30_character(
        client, db):
    helpers.create_user(client)
    helpers.login_user(client)
    helpers.insert_complete_restaurant(db)

    res = client.post(
        "/restaurants/1",
        data=dict(rating=4, message="It was a"),
        follow_redirects=True,
    )

    assert res.status_code == 200
    assert b"The review should be at least of 30 characters." in res.data
Example #22
0
def test_create(client):
    data = {'firstname': 'Binom', 'lastname': 'Missieu'}

    response = client.post('/players',
                           data=json.dumps(data),
                           content_type='application/json')
    player_id = client.database.execute('SELECT (id) FROM players;')[0]['id']

    assert response.status_code == 201
    assert json.loads(response.data) == {
        "id": player_id,
        "firstname": "Binom",
        "lastname": "Missieu"
    }
Example #23
0
def test_delete_should_be_successful(client, db):
    res = client.post(
        "/users",
        json=user1,
    )

    res = client.delete("/users/1")

    q = db.session.query(User).filter_by(id=1).first()

    assert res.status_code == 204
    assert q.firstname == ""
    assert q.lastname == ""
    assert q.fiscalcode == ""
    assert q.phonenumber == ""
    assert not q.birthdate
    assert q.email == "deleted"
Example #24
0
def test_post_should_be_successful(client, db):
    res = client.post(
        "/authorities",
        json=health_authority_not_written,
    )

    q = db.session.query(HealthAuthority).filter_by(id=3).first()

    assert res.status_code == 201
    assert q.name == health_authority_not_written["name"]
    assert q.email == health_authority_not_written["email"]
    assert q.phonenumber == health_authority_not_written["phonenumber"]
    assert q.country == health_authority_not_written["country"]
    assert q.city == health_authority_not_written["city"]
    assert q.state == health_authority_not_written["state"]
    assert q.lat == health_authority_not_written["lat"]
    assert q.lon == health_authority_not_written["lon"]
    def test_delete_zone(self, client, initial_data, zone_data,
                         basic_auth_admin_headers):
        res = client.post("/api/v1/pdnsadmin/zones",
                          headers=basic_auth_admin_headers,
                          data=json.dumps(zone_data),
                          content_type="application/json")
        data = res.get_json(force=True)
        data['rrsets'] = []

        validate_zone(data)
        assert res.status_code == 201

        zone_url_format = "/api/v1/pdnsadmin/zones/{0}"
        zone_url = zone_url_format.format(zone_data['name'].rstrip("."))
        res = client.delete(zone_url, headers=basic_auth_admin_headers)

        assert res.status_code == 204
    def test_create_zone(self, client, common_data_mock, zone_data,
                         basic_auth_admin_headers, created_zone_data):
        with patch('powerdnsadmin.lib.helper.requests.request') as mock_post, \
             patch('powerdnsadmin.routes.api.Domain') as mock_domain:
            mock_post.return_value.status_code = 201
            mock_post.return_value.content = json.dumps(created_zone_data)
            mock_post.return_value.headers = {}
            mock_domain.return_value.update.return_value = True

            res = client.post("/api/v1/pdnsadmin/zones",
                              headers=basic_auth_admin_headers,
                              data=json.dumps(zone_data),
                              content_type="application/json")
            data = res.get_json(force=True)
            data['rrsets'] = []

            validate_zone(data)
            assert res.status_code == 201
Example #27
0
def test_new_user_login(client, mocker, session):  # noqa
    mocker.patch('rr.queries.user_by_fb_id', side_effect=no_existing_user)
    requests_get_mock = mocker.patch('requests.get',
                                     side_effect=MockResponse(
                                         200, graph_me_with_friends))

    data = {'timezone': 'US/Pacific', 'access_token': '123'}
    res = client.post(flask.url_for('auth.login'),
                      data=json.dumps(data),
                      headers={'Content-Type': 'application/json'})

    url = ('https://graph.facebook.com/me?fields=id,name,picture,'
           'friends&access_token={}').format(data['access_token'])
    requests_get_mock.assert_called_with(url)

    u = session.query(User).one()

    # login # FIXME
    #  assert flask.session.get('user_id') == str(u.id)

    # request succeeded
    assert res.status_code == 200
Example #28
0
def test_existing_user_login(client, session, mocker):  # noqa
    existing, friend_one, friend_two = seed_existing_users()

    session.add_all([existing, friend_one, friend_two])
    session.commit()

    assert existing.all_friends == []

    mocker.patch('requests.get', MockResponse(200, graph_me_with_friends))
    mocker.patch('rr.queries.user_by_fb_id', no_existing_user)
    data = {'timezone': 'US/Pacific', 'access_token': '123'}
    res = client.post(flask.url_for('auth.login'),
                      data=json.dumps(data),
                      headers={'Content-Type': 'application/json'})

    # no new users created
    assert session.query(User).count() == 3

    # fb access token updated
    assert existing.fb_access_token == '123'

    # friends updated
    assert set(existing.friends) == set([friend_one, friend_two])
Example #29
0
def post_game(client, session_id, data={}, expected_response=200):
    response = client.post('/session/{}/game/'.format(session_id),
                           data=json.dumps(data),
                           content_type='application/json')
    assert response.status_code == expected_response
    return response
Example #30
0
    def test_account_users(
            self,
            client,
            initial_data,  # noqa: F811
            account_data,
            user1_data,  # noqa: F811
            basic_auth_admin_headers,
            basic_auth_user_headers):  # noqa: F811
        self.client = client
        self.basic_auth_admin_headers = basic_auth_admin_headers

        # Create account
        res = client.post(
            "/api/v1/pdnsadmin/accounts",
            headers=basic_auth_admin_headers,
            data=json.dumps(account_data),
            content_type="application/json",
        )
        data = res.get_json(force=True)
        assert res.status_code == 201

        # Check account
        data = self.check_account(account_data)
        account_id = data["id"]

        # Create user1
        res = client.post(
            "/api/v1/pdnsadmin/users",
            headers=basic_auth_admin_headers,
            data=json.dumps(user1_data),
            content_type="application/json",
        )
        data = res.get_json(force=True)
        assert res.status_code == 201
        assert len(data) == 1

        # Check user
        user1 = self.check_user(user1_data, data[0])
        user1_id = user1["id"]

        # Assert test account has no users
        res = client.get(
            "/api/v1/pdnsadmin/accounts/users/{}".format(account_id),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        data = res.get_json(force=True)
        assert res.status_code == 200
        assert data == []

        # Link user to account (as user, should fail)
        res = client.put(
            "/api/v1/pdnsadmin/accounts/users/{}/{}".format(
                account_id, user1_id),
            headers=basic_auth_user_headers,
            content_type="application/json",
        )
        assert res.status_code == 401

        # Link user to account (as admin)
        res = client.put(
            "/api/v1/pdnsadmin/accounts/users/{}/{}".format(
                account_id, user1_id),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 204

        # Unlink user from account (as user, should fail)
        res = client.delete(
            "/api/v1/pdnsadmin/accounts/users/{}/{}".format(
                account_id, user1_id),
            headers=basic_auth_user_headers,
            content_type="application/json",
        )
        assert res.status_code == 401

        # Unlink user from account (as admin)
        res = client.delete(
            "/api/v1/pdnsadmin/accounts/users/{}/{}".format(
                account_id, user1_id),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 204

        # Cleanup (delete user)
        res = client.delete(
            "/api/v1/pdnsadmin/users/{}".format(user1_id),
            data=json.dumps(user1_data),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 204

        # Cleanup (delete account)
        res = client.delete(
            "/api/v1/pdnsadmin/accounts/{}".format(account_id),
            data=json.dumps(account_data),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 204