示例#1
0
def test_debit_account_adds_credit_event_to_db(fake_app: FlaskClient, db,
                                               account_id, session: Session):
    fake_app.patch(f'/api/v1/account/{account_id}/balance',
                   data=json.dumps({
                       'action': 'debit',
                       'dollars': 12,
                       'cents': 95
                   }),
                   content_type='application/json')
    aggregate = session.query(AggregateModel).filter(
        AggregateModel.uuid == account_id.value).one()
    assert aggregate.events[-1].data['dollars'] == 12
    assert aggregate.events[-1].data['cents'] == 95
    assert aggregate.version == AGGREGATE_VERSION + 1
示例#2
0
def test_update_country_successful_response(app_test_client: FlaskClient,
                                            country_summary: Dict[str,
                                                                  Union[str,
                                                                        int]]):
    """
    Test updating one country with success.

    Args:
        app_test_client (FlaskClient): App's HTTP client.
        country_summary (Dict[str, Union[str, int]]): Summary message example.
    """
    clean_database()

    original_new_confirmed_number = country_summary["new_confirmed"]
    updated_new_confirmed_number = country_summary["new_confirmed"] + 100

    app_test_client.post("countries/", json=country_summary)

    pre_update_get_response = app_test_client.get(
        f"countries/{country_summary['country_code']}")
    assert (pre_update_get_response.json["new_confirmed"] ==
            original_new_confirmed_number)

    country_summary["new_confirmed"] = updated_new_confirmed_number
    response = app_test_client.patch(
        f"/countries/{country_summary['country_code']}", json=country_summary)
    assert response.status_code == 200

    post_update_get_response = app_test_client.get(
        f"countries/{country_summary['country_code']}")
    assert (post_update_get_response.json["new_confirmed"] ==
            updated_new_confirmed_number)
示例#3
0
def test_edit_should_change_user_info(sample_app, app_client: FlaskClient,
                                      test_token):
    with sample_app.test_request_context():

        expected_response = {
            "user": {
                "email": "*****@*****.**",
                "nickname": "LuanGameplays",
                "first_name:": "Ze",
                "last_name": "Neves",
                "biography": "Peace",
            }
        }

        response = app_client.patch(
            USERS_ROUTE,
            json={
                "nickname": "LuanGameplays",
                "first_name": "Ze",
                "biography": "Peace",
            },
            headers=test_token,
        )

    assert response.status_code == HTTPStatus.OK
    assert response.get_json() == expected_response
示例#4
0
def test_update_user_profile_not_logged_in(client: FlaskClient):
    user = users.add(
        User(email='*****@*****.**',
             password='******',
             first_name='Tibor',
             last_name='Mikita',
             phone='+421111222333',
             street='Kosicka',
             zip_code='06601',
             city='Humenne',
             country=Country.SK,
             date_of_birth=datetime.date(1994, 5, 25)))
    user.active = True

    r = client.patch(f'/api/users/{user.id}',
                     data=json.dumps({
                         'city': 'Medzilaborce',
                         'street': 'Bratislavska',
                         'zip_code': '99999',
                         'phone': '+420999999999'
                     }),
                     content_type='application/json')

    payload = r.json

    assert r.status_code == status.HTTP_403_FORBIDDEN
    assert payload[
        'message'] == 'You do not have permission to perform this action.'
示例#5
0
def test_update_user_profile_invalid_phone_format(client: FlaskClient):
    user = users.add(
        User(email='*****@*****.**',
             password='******',
             first_name='Tibor',
             last_name='Mikita',
             phone='+421111222333',
             street='Kosicka',
             zip_code='06601',
             city='Humenne',
             country=Country.SK,
             date_of_birth=datetime.date(1994, 5, 25)))
    user.active = True

    r = client.post('/api/auth/login',
                    data=json.dumps({
                        'email': '*****@*****.**',
                        'password': '******'
                    }),
                    content_type='application/json')

    payload = r.json

    access_token = payload['access_token']

    r = client.patch(f'/api/users/{user.id}',
                     data=json.dumps({'phone': '0999999999'}),
                     content_type='application/json',
                     headers={'Authorization': f'Bearer {access_token}'})

    payload = r.json

    assert r.status_code == status.HTTP_400_BAD_REQUEST
    assert 'Phone must have format' in payload['message']
示例#6
0
 def test_does_not_exist(self, client: FlaskClient, jwt_token: str) -> None:
     """
     A 404 is returned when editing a Todo item that does not exist
     """
     patch_result = client.patch(
         "/todo/1",
         json={"text": "test_text_edited"},
         headers={"Authorization": jwt_token},
     )
     assert patch_result.status_code == 404
示例#7
0
def test_disallowed(client: FlaskClient, pets):
    # delete disabled
    assert client.delete("/human/2").status_code == 405

    # human has get_enabled
    assert client.get("/human/2000").status_code == 404

    # pointless doesn't allow anything
    assert client.post("/pointless").status_code == 405
    assert client.patch("/pointless/2").status_code == 405
    assert client.get("/pointless/1").status_code == 405
示例#8
0
def test_acceptance_criteria_4(client: FlaskClient, session: Session):
    # create product
    product = create_basic_db_product()
    session.add(product)
    session.commit()

    assert product.featured is False

    # Make sure product doesn't become featured when rating is less then threshold
    response = client.patch(f'/products/{product.id}',
                            data=json.dumps({
                                "rating": FEATURED_THRESHOLD - 1,
                            }),
                            content_type='application/json')
    json_response = json.loads(response.data)

    assert response.status_code == 200
    assert json_response["featured"] is False

    # Check if featured is updated when rating is more then threshold
    response = client.patch(f'/products/{product.id}',
                            data=json.dumps({
                                "rating": FEATURED_THRESHOLD + 1,
                            }),
                            content_type='application/json')
    json_response = json.loads(response.data)

    assert response.status_code == 200
    assert json_response["featured"] is True

    # Make sure product do not stop being featured if rating becomes less then threshold
    response = client.patch(f'/products/{product.id}',
                            data=json.dumps({
                                "rating": FEATURED_THRESHOLD - 1,
                            }),
                            content_type='application/json')
    json_response = json.loads(response.data)

    assert response.status_code == 200
    assert json_response["featured"] is True
示例#9
0
def assert_crud_resource(api_gateway: FlaskClient,
                         auth_header,
                         path,
                         inputs,
                         loader_func,
                         valid=True,
                         delete=False):
    """
    Generic test routine, attempt to create a resource, assert that the relevant artifacts were (or not) created
    """

    for test_resource in inputs:
        resource_to_create = loader_func(test_resource["create"])
        p = api_gateway.post(f"{path}",
                             headers=auth_header,
                             data=json.dumps(resource_to_create))
        if valid:
            assert p.status_code == HTTPStatus.CREATED
            assert_json_subset(resource_to_create, p.get_json())
        else:
            assert p.status_code == HTTPStatus.BAD_REQUEST
            # ToDo: assert that the response is a problem - move problems to common

        resource_id = p.get_json().get("id_")
        g = api_gateway.get(f"{path}/{resource_id}", headers=auth_header)
        if valid:
            assert g.status_code == HTTPStatus.OK
            assert_json_subset(resource_to_create, g.get_json())
        else:
            assert g.status_code == HTTPStatus.NOT_FOUND
            # ToDo: assert that the response is a problem - move problems to common

        update = test_resource.get("update")
        if update:
            resource_to_update = loader_func(update)
            if update["type"] == "put":
                u = api_gateway.put(f"{path}/{resource_id}",
                                    headers=auth_header,
                                    data=json.dumps(resource_to_update))
                assert_json_subset(resource_to_update, u.get_json())
            elif update["type"] == "patch":
                u = api_gateway.patch(f"{path}/{resource_id}",
                                      headers=auth_header,
                                      data=json.dumps(resource_to_update))
                patch = jsonpatch.JsonPatch.from_string(resource_to_update)
                baseline = patch.apply(resource_to_create)
                assert_json_subset(baseline, u.get_json())

        if delete:
            d = api_gateway.delete(f"{path}/{resource_id}",
                                   headers=auth_header)
            assert d.status_code == HTTPStatus.NO_CONTENT
示例#10
0
 def test_todo_of_other_user(self, client: FlaskClient) -> None:
     """
     A 403 is returned when a user attempts to retrieve a Todo item that
     they do not own.
     """
     credentials = {
         "email": "*****@*****.**",
         "password": "******",
     }
     credentials_other = {
         "email": "*****@*****.**",
         "password": "******",
     }
     client.post("/auth/signup", json=credentials)
     client.post("/auth/signup", json=credentials_other)
     result_from_login = client.post("/auth/login", json=credentials)
     result_from_login_other = client.post("/auth/login",
                                           json=credentials_other)
     jwt_token = "Bearer " + result_from_login.get_json()["token"]
     jwt_token_other = ("Bearer " +
                        result_from_login_other.get_json()["token"])
     post_res = client.post(
         "/todo",
         json={"text": "test_text"},
         headers={"Authorization": jwt_token},
     )
     post_res_other = client.post(
         "/todo",
         json={"text": "test_text_other"},
         headers={"Authorization": jwt_token_other},
     )
     obj_id = post_res.get_json()["obj_id"]
     obj_id_other = post_res_other.get_json()["obj_id"]
     res = client.get("/todo/" + obj_id,
                      headers={"Authorization": jwt_token})
     res_other = client.get("/todo/" + obj_id_other,
                            headers={"Authorization": jwt_token_other})
     get_data = res.get_json()
     get_data_other = res_other.get_json()
     assert get_data == "test_text"
     assert get_data_other == "test_text_other"
     wrong_auth_token = client.get("/todo/" + obj_id_other,
                                   headers={"Authorization": jwt_token})
     assert wrong_auth_token.status_code == 403
     patch_result = client.patch(
         "/todo/" + obj_id,
         json={"text": "test_text_edited"},
         headers={"Authorization": jwt_token_other},
     )
     assert patch_result.status_code == 403
示例#11
0
def test_edit_membership_details(client: FlaskClient) -> None:
    user = User(uuid=example_uuid1)
    meeting = Meeting(uuid=example_uuid2, owner=user)
    membership = Membership(meeting=meeting, user=user)
    db.session.add(membership)
    db.session.commit()

    response = client.patch(f'/api/v1/memberships/{meeting.uuid}/{user.uuid}',
                            json={'stop_name': 'Chopina'})
    assert response.status_code == 204
    assert response.data == b''

    membership = Membership.query.get((meeting.uuid, user.uuid))
    assert membership.stop_name == 'Chopina'
示例#12
0
def test_assets_id(client: FlaskClient):
    """Test for /api/meta/assets/<id>"""
    url = '/api/meta/assets/1'
    res = client.get(url)
    assert res.json['code'] == http.HTTPStatus.OK

    res = client.post(url)
    assert res.json['code'] == http.HTTPStatus.METHOD_NOT_ALLOWED  # Method Not Allowed

    res = client.put(url)
    assert res.json['code'] == http.HTTPStatus.OK

    res = client.patch(url)
    assert res.json['code'] == http.HTTPStatus.OK
示例#13
0
def test_update_user_profile(client: FlaskClient):
    user = users.add(
        User(email='*****@*****.**',
             password='******',
             first_name='Tibor',
             last_name='Mikita',
             phone='+421111222333',
             street='Kosicka',
             zip_code='06601',
             city='Humenne',
             country=Country.SK,
             date_of_birth=datetime.date(1994, 5, 25)))
    user.active = True

    r = client.post('/api/auth/login',
                    data=json.dumps({
                        'email': '*****@*****.**',
                        'password': '******'
                    }),
                    content_type='application/json')

    payload = r.json

    access_token = payload['access_token']

    assert user.city == 'Humenne'
    assert user.street == 'Kosicka'
    assert user.zip_code == '06601'
    assert user.phone == '+421111222333'

    r = client.patch(f'/api/users/{user.id}',
                     data=json.dumps({
                         'city': 'Medzilaborce',
                         'street': 'Bratislavska',
                         'zip_code': '99999',
                         'phone': '+420999999999'
                     }),
                     content_type='application/json',
                     headers={'Authorization': f'Bearer {access_token}'})

    payload = r.json

    assert r.status_code == status.HTTP_200_OK
    assert payload['message'] == 'Profile successfully modified.'

    assert user.city == 'Medzilaborce'
    assert user.street == 'Bratislavska'
    assert user.zip_code == '99999'
    assert user.phone == '+420999999999'
示例#14
0
def test_acceptance_criteria_3(client: FlaskClient, session: Session):
    # create brand and category to add to new product
    brand = create_basic_db_brand()
    category = create_basic_db_category()

    session.add(brand)
    session.add(category)
    session.commit()

    now = datetime.utcnow()

    # Try to pass expiration date that is too early (creation)
    response = client.post('/products',
                           data=json.dumps({
                               "name":
                               "test",
                               "rating":
                               5,
                               "brand":
                               brand.id,
                               "categories": [category.id],
                               "expiration_date":
                               email_utils.format_datetime(now),
                               "items_in_stock":
                               1
                           }),
                           content_type='application/json')
    json_response = json.loads(response.data)

    assert response.status_code == 400
    assert len(json_response["errors"]) == 1
    assert json_response["errors"][0]["loc"][0] == 'expiration_date'

    # Try to pass expiration date that is too early (update)
    product = create_basic_db_product()
    session.add(product)
    session.commit()

    response = client.patch(f"/products/{product.id}",
                            data=json.dumps({
                                "expiration_date":
                                email_utils.format_datetime(now),
                            }),
                            content_type='application/json')
    json_response = json.loads(response.data)

    assert response.status_code == 400
    assert len(json_response["errors"]) == 1
    assert json_response["errors"][0]["loc"][0] == 'expiration_date'
示例#15
0
def test_edit_should_fail_when_user_not_exists(sample_app,
                                               app_client: FlaskClient,
                                               test_token_user_not_exists):
    with sample_app.test_request_context():

        expected_response = {"error": "User not found"}

        response = app_client.patch(
            USERS_ROUTE,
            json={},
            headers=test_token_user_not_exists,
        )

    assert response.status_code == HTTPStatus.NOT_FOUND
    assert response.get_json() == expected_response
示例#16
0
def test_edit_should_fail_when_email_already_exists(sample_app,
                                                    app_client: FlaskClient,
                                                    test_token):
    with sample_app.test_request_context():

        expected_response = {
            "error": "This email address is already being used"
        }

        response = app_client.patch(
            USERS_ROUTE,
            json={
                "email": "*****@*****.**",
            },
            headers=test_token,
        )

    assert response.status_code == HTTPStatus.CONFLICT
    assert response.get_json() == expected_response
示例#17
0
def test_update_other_user_profile_not_mine(client: FlaskClient):
    user1 = users.add(
        User(email='*****@*****.**',
             password='******',
             first_name='Tibor',
             last_name='Mikita',
             phone='+421111222333',
             street='Kosicka',
             zip_code='06601',
             city='Humenne',
             country=Country.SK,
             date_of_birth=datetime.date(1994, 5, 25)))
    user1.active = True

    user2 = users.add(User('*****@*****.**', 'dsaa'))
    user2.active = True

    r = client.post('/api/auth/login',
                    data=json.dumps({
                        'email': '*****@*****.**',
                        'password': '******'
                    }),
                    content_type='application/json')

    payload = r.json

    access_token = payload['access_token']

    r = client.patch(f'/api/users/{user1.id}',
                     data=json.dumps({
                         'city': 'Medzilaborce',
                         'street': 'Bratislavska',
                         'zip_code': '99999',
                         'phone': '+420999999999'
                     }),
                     content_type='application/json',
                     headers={'Authorization': f'Bearer {access_token}'})

    payload = r.json

    assert r.status_code == status.HTTP_400_BAD_REQUEST
    assert payload['message'] == 'You cannot edit profile of other person.'
示例#18
0
def test_edit_meeting(client: FlaskClient) -> None:
    owner = User(uuid=example_uuid1)
    meeting = Meeting(uuid=example_uuid2, owner=owner)
    db.session.add(meeting)
    db.session.commit()

    response = client.patch(f'/api/v1/meetings/{meeting.uuid}',
                            json={
                                'owner_uuid': owner.uuid,
                                'name': 'Lorem ipsum',
                                'description': 'Lorem ipsum sit dolor amet.',
                                'datetime': '2020-01-02T03:04:05',
                                'stop_name': 'Czarnowiejska',
                            })
    assert response.status_code == 204

    meeting = Meeting.query.get(meeting.uuid)
    assert meeting.name == 'Lorem ipsum'
    assert meeting.description == 'Lorem ipsum sit dolor amet.'
    assert meeting.datetime == datetime(2020, 1, 2, 3, 4, 5)
    assert meeting.stop_name == 'Czarnowiejska'
示例#19
0
 def test_exists(self, client: FlaskClient, jwt_token: str) -> None:
     """
     It is possible to edit the text of a Todo item
     """
     result_from_post = client.post(
         "/todo",
         json={"text": "test_text"},
         headers={"Authorization": jwt_token},
     )
     obj_id = result_from_post.get_json()["obj_id"]
     patch_result = client.patch(
         "/todo/" + obj_id,
         json={"text": "test_text_edited"},
         headers={"Authorization": jwt_token},
     )
     assert patch_result.status_code == 200
     res = client.get("/todo/" + obj_id,
                      headers={"Authorization": jwt_token})
     get_data = res.get_json()
     expected_data = "test_text_edited"
     assert get_data == expected_data
示例#20
0
def http_req(client: FlaskClient, url: str, method: str,
             payload: dict) -> dict:
    """
    发送测试请求
    :param client: flask客户端对象
    :param url: 路由
    :param method: 请求方法
    :param payload: 参数
    :return: 数据
    """
    if method.upper() == 'GET':
        return client.get(url, query_string=payload).json
    if method.upper() == 'POST':
        return client.post(url, json=payload, headers=headers).json
    if method.upper() == 'PUT':
        return client.put(url, json=payload, headers=headers).json
    if method.upper() == 'DELETE':
        return client.delete(url, json=payload, headers=headers).json
    if method.upper() == 'PATCH':
        return client.patch(url, json=payload, headers=headers).json
    else:
        raise RuntimeError('Http method error!')
示例#21
0
def verify_add_team_members(client: FlaskClient,
                            access_token: str,
                            team_slug: str,
                            users: List[Mapping]) -> Mapping:
    assert users
    payload = dict(users=[{
        'username': u['username'],
        'uniqueId': u['uniqueId'],
    } for u in users])
    response = client.patch(f'/teams/{team_slug}/members',
                            headers=auth_header(access_token),
                            json=payload,
                            follow_redirects=True)
    data = verify_api_response(response)

    assert data.get('slug') == team_slug
    members = data.get('members')
    assert members
    member_ids = [m['uniqueId'] for m in members]

    for uid in [u['uniqueId'] for u in users]:
        assert uid in member_ids
示例#22
0
def test_update_product(client: FlaskClient, session: Session):
    # create product
    product = create_basic_db_product()
    session.add(product)
    session.commit()

    # check before change
    product_pre_update = product.serialized

    # request update
    response = client.patch(f"/products/{product.id}",
                            data=json.dumps({"name": "test2"}),
                            content_type='application/json')

    # check status
    assert response.status_code == 200

    # check if product changed in database
    session.refresh(product)
    assert product.name == "test2"

    # make sure everything else is NOT changed
    product_post_update = product.serialized
    assert product_post_update["id"] == product_pre_update["id"]
    assert product_post_update["featured"] == product_pre_update["featured"]
    assert product_post_update["brand"] == product_pre_update["brand"]
    assert product_post_update["categories"] == product_pre_update[
        "categories"]
    assert product_post_update["items_in_stock"] == product_pre_update[
        "items_in_stock"]
    assert product_post_update["receipt_date"] == product_pre_update[
        "receipt_date"]
    assert product_post_update["expiration_date"] == product_pre_update[
        "expiration_date"]
    assert product_post_update["created_at"] == product_pre_update[
        "created_at"]
示例#23
0
def test_update(client: FlaskClient, pets):
    update = {"species": "Canis"}
    res = client.patch(f"/pet/{pets[0].id}", json=update)
    assert res.status_code == 200
    pet = res.json
    assert pet["species"] == "Canis"
示例#24
0
 def test_other_methods_not_allowed(self, client: FlaskClient):
     assert client.get('tasks/complete-task/1/').status_code == 405
     assert client.put('tasks/complete-task/1/').status_code == 405
     assert client.patch('tasks/complete-task/1/').status_code == 405
     assert client.delete('tasks/complete-task/1/').status_code == 405