def test_put_mn_one_works_when_items_exist(empty_database, valid_people_orm,
                                           valid_team_orm):
    """Ideally we would be able to also assert on the error message that
    returns.

    # assert result == ({"error": "Resource with id '1' not found."},
    404)
    """
    resource_handler = ResourceHandler()

    person = valid_people_orm(name="tester")
    team1 = valid_team_orm(name="team")
    team2 = valid_team_orm(name="team2")
    person.team_collection.append(team1)

    db_session.add(person)
    db_session.add(team1)
    db_session.add(team2)
    db_session.commit()

    result = resource_handler.put_mn_one(
        id=1,
        body=[2],
        parent_orm=valid_people_orm,
        child_orm=valid_team_orm,
        patch=True,
    )

    assert result == ([1, 2], 200)
def test_put_errors_when_a_child_does_not_exist(empty_database,
                                                valid_people_orm,
                                                valid_team_orm):
    """Ideally we would be able to also assert on the error message that
    returns.

    # assert result == ({"error": "Resource with id '1' not found."},
    404)
    """
    resource_handler = ResourceHandler()

    person = valid_people_orm(id=1, name="tester")
    team = valid_team_orm(id=1, name="team")
    person.team_collection.append(team)

    db_session.add(person)
    db_session.add(team)
    db_session.commit()

    with pytest.raises(ApiError):
        _ = resource_handler.put_mn_one(
            id=1,
            body=[1, 2],
            parent_orm=valid_people_orm,
            child_orm=valid_team_orm,
            patch=True,
        )
    def put_mn_one(
        self,
        id: int,
        body: list,
        parent_orm: object,
        child_orm: object,
        patch: bool = False,
    ):
        """PUT m:n relationship data between a parent and child.

        Args:
            id (int): Given ID of type parent
            body: list,
            parent_orm: object,
            child_orm: object,
            patch: bool = False,
        """
        if id == 0:  # For testing
            return {}, 200

        primary_key = "id"
        parent = (
            db_session.query(parent_orm)
            .filter(getattr(parent_orm, primary_key) == id)
            .first()
        )

        if parent is None:
            db_session.rollback()
            raise ApiError(f"Resource with id '{id}' not found.", 404)

        if type(body) is not list:
            body = [body]

        mn_list = getattr(parent, f"{child_orm.__table__.name}_collection")

        if not patch:
            mn_list.clear()

        for child_id in body:
            child = (
                db_session.query(child_orm)
                .filter(getattr(child_orm, primary_key) == child_id)
                .first()
            )

            if child is None:
                db_session.rollback()
                raise ApiError(f"Child with id '{child_id}' does not exist.")

            mn_list.append(child)

        db_session.commit()

        response = [item.id for item in mn_list]

        return response, 200
Esempio n. 4
0
def test_get_one_works_when_item_exists(empty_database, valid_people_orm):
    # When one item in DB - GET returns that item
    resource_handler = ResourceHandler()

    new_object = valid_people_orm(name="tester")
    db_session.add(new_object)
    db_session.commit()

    result = resource_handler.get_one(
        resource_name="test", resource_orm=valid_people_orm, id=1
    )

    assert result == ({"id": 1, "name": "tester"}, 200)
def test_query_works_with_correct_data(valid_people_orm):
    resource_handler = ResourceHandler()

    class FakeFlaskRequest:
        json = {"name": "tester"}

    new_object = valid_people_orm(name="tester")
    db_session.add(new_object)
    db_session.commit()

    result = resource_handler.query_one(resource_orm=valid_people_orm,
                                        request=FakeFlaskRequest())

    assert result == ({"results": [{"id": 1, "name": "tester"}]}, 200)
def test_query_returns_none_when_given_incorrect_field_data(valid_people_orm):
    # When one item in DB - GET returns that item
    resource_handler = ResourceHandler()

    class FakeFlaskRequest:
        json = {"name": "wrongname"}

    new_object = valid_people_orm(name="tester")
    db_session.add(new_object)
    db_session.commit()

    result = resource_handler.query_one(resource_orm=valid_people_orm,
                                        request=FakeFlaskRequest())

    assert result == ({"message": "No matches found"}, 404)
    def update_one(self,
                   id=1,
                   resource_name=None,
                   resource_orm=None,
                   request=None,
                   mode="PUT"):
        """Update a single object from the data model based on it's primary
        key.

        Args:
            id (int): PK ID of resource,
            resource_name (str): =None,
            resource_orm (SQLAlchemy ORM):
            request (Flask request?): =None,
            mode (str): Tells the function if this is a PUT or PATCH

        Return:
            dict, int: The response object and the HTTP status code.
        """
        try:
            request_obj = request.json
        except Exception:
            raise ApiError("No request body found.", 400)

        primary_key = "id"
        data_obj = (db_session.query(resource_orm).filter(
            getattr(resource_orm, primary_key) == id).first())

        if mode == "PATCH" and data_obj is None:
            raise ApiError(f"Resource with id '{id}' not found.", 404)

        if data_obj is None:
            return ResourceCreate().insert_one(resource_orm=resource_orm,
                                               request=request)

        try:
            for key, value in request_obj.items():
                setattr(data_obj, key, value)
            db_session.commit()
        except (exc.SQLAlchemyError, AttributeError):
            raise ApiError("Failed to modify resource.")

        id_value = data_obj.id

        return {
            "message": "Successfully updated resource.",
            "id": id_value
        }, 200
def test_get_mn_one_works_when_item_exists(empty_database, valid_people_orm,
                                           valid_team_orm):
    resource_handler = ResourceHandler()

    person = valid_people_orm(name="tester")
    team = valid_team_orm(name="team")
    person.team_collection.append(team)

    db_session.add(person)
    db_session.add(team)
    db_session.commit()

    result = resource_handler.get_mn_one(id=1,
                                         parent_orm=valid_people_orm,
                                         child_orm=valid_team_orm)

    assert result == ([1], 200)
Esempio n. 9
0
def test_create_models_can_add_data_with_orm(valid_data_dictionary,
                                             empty_database):
    table_descriptors = valid_data_dictionary["data"]
    base = create_models(table_descriptors)

    people_orm = getattr(base.classes, "people")
    team_orm = getattr(base.classes, "team")

    person1 = people_orm(name="testperson")
    team1 = team_orm(name="testteam")

    person1.team_collection.append(team1)

    db_session.add(team1)
    db_session.add(person1)

    db_session.commit()
def test_query_errors_when_given_incorrect_field_data(valid_people_orm):
    """Ideally we would be able to also assert on the error message that
    returns.

    # assert result == ({"error": "Resource with id '1' not found."},
    404)
    """
    # When one item in DB - GET returns that item
    resource_handler = ResourceHandler()

    class FakeFlaskRequest:
        json = {"doesnotexist": "error"}

    new_object = valid_people_orm(name="tester")
    db_session.add(new_object)
    db_session.commit()

    with pytest.raises(ApiError):
        resource_handler.query_one(resource_orm=valid_people_orm,
                                   request=FakeFlaskRequest())
Esempio n. 11
0
def test_get_all(empty_database, valid_people_orm):
    # When nothing in DB - GET returns empty list
    resource_handler = ResourceHandler()

    result = resource_handler.get_all(
        resource_name="test", resource_orm=valid_people_orm, offset=0, limit=10
    )

    assert result == ({"test": [], "links": []}, 200)

    # When one item in DB - GET returns an item
    new_object = valid_people_orm(name="tester")
    db_session.add(new_object)
    db_session.commit()

    result = resource_handler.get_all(
        resource_name="test", resource_orm=valid_people_orm, offset=0, limit=10
    )

    assert result[0]["test"] == [{"id": 1, "name": "tester"}]
    assert result[1] == 200
def test_patch_works_when_item_exists(empty_database, valid_people_orm):
    # When something in DB - PATCH changes the item
    resource_handler = ResourceHandler()

    class FakeFlaskRequest:
        json = {"name": "tester"}

    new_object = valid_people_orm(name="tester")
    db_session.add(new_object)
    db_session.commit()

    result = resource_handler.update_one(
        id=1,
        resource_name="test",
        resource_orm=valid_people_orm,
        request=FakeFlaskRequest(),
        mode="PATCH",
    )

    assert result == ({
        "id": 1,
        "message": "Successfully updated resource."
    }, 200)
Esempio n. 13
0
    def insert_one(self, resource_orm: object = None, request: Request = None):
        """Insert a new object.

        Args:
            resource_orm (object): SQLAlchemy ORM model.
            request_obj (flask.Request): HTTP request object.

        Return:
            dict, int: The response object and associated HTTP status code.
        """
        try:
            request_obj = request.json
        except Exception:
            raise ApiError("No request body found.", 400)

        try:
            new_object = resource_orm()
            for key, value in request_obj.items():
                setattr(new_object, key, value)

            db_session.add(new_object)
            db_session.commit()
            # Can we get primary key(s) from sqlalchemy model?
            # https://stackoverflow.com/questions/6745189/how-do-i-get-the-name-of-an-sqlalchemy-objects-primary-key
            # id_value = getattr(new_object, table_schema["primaryKey"])
            id_value = new_object.id

            return {
                "message": "Successfully added new resource.",
                "id": id_value
            }, 201
        except Exception:
            # wrong type -- psycopg2.errors.InvalidTextRepresentation
            # IntegrityError('(psycopg2.errors.NotNullViolation) null value in column "required" violates not-null constraint\nDETAIL:  Failing row contains (1, null, 1).\n')
            db_session.rollback()
            raise ApiError("Failed to create new resource.", 400)