Skip to content

Commit

Permalink
Add test for updating data
Browse files Browse the repository at this point in the history
  • Loading branch information
Reillyhewitson committed Nov 3, 2022
1 parent c434218 commit 5dc78c3
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 2 deletions.
22 changes: 20 additions & 2 deletions datagateway_api/src/datagateway_api/database/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@
from sqlalchemy.orm.collections import InstrumentedList

from datagateway_api.src.common.date_handler import DateHandler
from datagateway_api.src.common.exceptions import DatabaseError, FilterError
from datagateway_api.src.common.exceptions import (
BadRequestError,
DatabaseError,
FilterError,
)

Base = declarative_base()

Expand Down Expand Up @@ -178,7 +182,21 @@ def update_from_dict(self, dictionary):
:returns: The updated dict
"""
for key in dictionary:
setattr(self, key, dictionary[key])
try:
if hasattr(self.__table__.columns[key.upper()].type, "length"):
if (
len(dictionary[key])
> self.__table__.columns[key.upper()].type.length
):
raise AttributeError

setattr(self, key, dictionary[key])

except AttributeError:
raise BadRequestError(
f"Bad request made, cannot modify attribute '{key}'"
)

return self.to_dict()


Expand Down
50 changes: 50 additions & 0 deletions test/datagateway_api/db/endpoints/test_update_by_id_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from datagateway_api.src.common.config import Config


class TestUpdateByID:
def test_valid_update_with_id(
self,
flask_test_app_db,
valid_db_credentials_header,
single_investigation_test_data_db,
):
update_data_json = {
"doi": "DB Test Data Identifier",
"summary": "DB Test Summary",
"startDate": "2019-01-04 01:01:01+00:00",
}

single_investigation_test_data = single_investigation_test_data_db.to_dict()

single_investigation_test_data.update(update_data_json)
test_response = flask_test_app_db.patch(
f"{Config.config.datagateway_api.extension}/investigations"
f"/{single_investigation_test_data['id']}",
headers=valid_db_credentials_header,
json=update_data_json,
)
print(test_response.status_code)
assert test_response.json == single_investigation_test_data

def test_invalid_update_with_id(
self,
flask_test_app_db,
valid_db_credentials_header,
single_investigation_test_data_db,
):
"""This test will attempt to put the DB in an invalid state"""

invalid_update_json = {
"doi": "_" * 300,
}

single_investigation_test_data = single_investigation_test_data_db.to_dict()

test_response = flask_test_app_db.patch(
f"{Config.config.datagateway_api.extension}/investigations"
f"/{single_investigation_test_data['id']}",
headers=valid_db_credentials_header,
json=invalid_update_json,
)

assert test_response.status_code == 400

0 comments on commit 5dc78c3

Please sign in to comment.