Skip to content

Commit b34299e

Browse files
Like for like
1 parent 9477fd3 commit b34299e

2 files changed

Lines changed: 120 additions & 121 deletions

File tree

app/routers/sample_jsonb_sql.py

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import structlog
55
from asyncpg.exceptions import UniqueViolationError, ForeignKeyViolationError
66
from fastapi import APIRouter, Response, HTTPException
7-
from sqlalchemy.exc import IntegrityError
87

98
from app.dao.sample_jsonb_sql_dao import (
109
read_sample_documents,
@@ -58,25 +57,23 @@ async def create_sample_document_handler(
5857
try:
5958
created_id = await create_sample_document(database, input_document)
6059
return await read_sample_document_by_id(database, created_id)
61-
except IntegrityError as ie:
60+
except UniqueViolationError as uve:
6261
logger = structlog.get_logger()
63-
logger.error(f"IntegrityError!: {repr(ie)}")
64-
sqlstate: str = getattr(ie.orig, "sqlstate")
65-
if sqlstate == UniqueViolationError.sqlstate:
66-
raise HTTPException(
67-
status_code=409,
68-
detail={
69-
"key": "$.json_id.id",
70-
"value": str(input_document.json_data.id),
71-
},
72-
)
73-
elif sqlstate == ForeignKeyViolationError.sqlstate:
74-
raise HTTPException(
75-
status_code=422,
76-
detail={"key": "$.sample_id", "value": str(input_document.sample_id)},
77-
)
78-
else:
79-
raise ie
62+
logger.error(f"UniqueViolationError!: {repr(uve)}")
63+
raise HTTPException(
64+
status_code=409,
65+
detail={
66+
"key": "$.json_id.id",
67+
"value": str(input_document.json_data.id),
68+
},
69+
)
70+
except ForeignKeyViolationError as fkve:
71+
logger = structlog.get_logger()
72+
logger.error(f"ForeignKeyViolationError!: {repr(fkve)}")
73+
raise HTTPException(
74+
status_code=422,
75+
detail={"key": "$.sample_id", "value": str(input_document.sample_id)},
76+
)
8077

8178

8279
@router.delete("", status_code=204)

tests_integration/routers/test_sample_jsonb_sql.py

Lines changed: 104 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from datetime import datetime, timezone, timedelta
33
from decimal import Decimal
44
from pprint import pprint
5-
from typing import Generator
5+
from typing import Generator, MutableMapping, Any
66

77
import pytest
88
from assertpy import assert_that
@@ -45,107 +45,109 @@ def test_sample_jsonb_orm_create(delete_all_fixture: None, test_client: TestClie
4545
assert_created_response_entity(response_entity, request_entity)
4646

4747

48-
# @pytest.mark.parametrize(
49-
# "raise_server_exceptions, expected_status",
50-
# [(False, 409)],
51-
# indirect=["raise_server_exceptions"],
52-
# )
53-
# def test_sample_jsonb_orm_create_with_duplicate_json_id_returns_409(
54-
# raise_server_exceptions: bool,
55-
# delete_all_fixture: None,
56-
# test_client: TestClient,
57-
# expected_status: int,
58-
# captured_logs: list[MutableMapping[str, Any]],
59-
# ):
60-
# sample = create_random_sample(test_client)
61-
#
62-
# request_entity: SampleDocumentCreate = SampleDocumentCreate(
63-
# sample_id=sample.id,
64-
# json_data=DocumentMetadata(id=uuid.uuid4(), tags=tuple(["tag1", "tag2"])),
65-
# secondary_json_dict={"key": "value"},
66-
# )
67-
# http_response = test_client.put(
68-
# SAMPLE_JSONB_SQL_ENDPOINT, json=jsonable_encoder(request_entity)
69-
# )
70-
# assert_that(http_response.status_code).is_equal_to(200)
71-
# request_entity_with_duplicate_id: SampleDocumentCreate = SampleDocumentCreate(
72-
# sample_id=sample.id,
73-
# json_data=DocumentMetadata(
74-
# id=request_entity.json_data.id, tags=tuple(["tag1", "tag2"])
75-
# ),
76-
# secondary_json_dict={"key": "value"},
77-
# )
78-
# http_response_with_duplicate_id = test_client.put(
79-
# SAMPLE_JSONB_SQL_ENDPOINT,
80-
# json=jsonable_encoder(request_entity_with_duplicate_id),
81-
# )
82-
# assert_that(http_response_with_duplicate_id.status_code).is_equal_to(
83-
# expected_status
84-
# )
85-
# expected_body: dict[str, Any] = {
86-
# "detail": {"key": "$.json_id.id", "value": str(request_entity.json_data.id)}
87-
# }
88-
# assert_that(http_response_with_duplicate_id.json()).is_equal_to(expected_body)
89-
# assert_that(len(captured_logs)).is_greater_than(0)
90-
# assert_that(
91-
# list(
92-
# filter(
93-
# lambda entry: str(entry["event"]).startswith("IntegrityError!"),
94-
# captured_logs,
95-
# )
96-
# )
97-
# ).is_length(1)
98-
# assert_that(
99-
# list(
100-
# filter(
101-
# lambda entry: str(entry["event"]).startswith("An HTTP error!"),
102-
# captured_logs,
103-
# )
104-
# )
105-
# ).is_length(1)
106-
#
107-
#
108-
# @pytest.mark.parametrize(
109-
# "raise_server_exceptions",
110-
# [False],
111-
# indirect=True,
112-
# )
113-
# def test_sample_jsonb_orm_create_with_non_existent_parent_sample_returns_422(
114-
# raise_server_exceptions: bool,
115-
# delete_all_fixture: None,
116-
# test_client: TestClient,
117-
# captured_logs: list[MutableMapping[str, Any]],
118-
# ):
119-
# request_entity: SampleDocumentCreate = SampleDocumentCreate(
120-
# sample_id=uuid.uuid4(),
121-
# json_data=DocumentMetadata(id=uuid.uuid4(), tags=tuple(["tag1", "tag2"])),
122-
# secondary_json_dict={"key": "value"},
123-
# )
124-
# http_response = test_client.put(
125-
# SAMPLE_JSONB_SQL_ENDPOINT, json=jsonable_encoder(request_entity)
126-
# )
127-
# assert_that(http_response.status_code).is_equal_to(422)
128-
# expected_body: dict[str, Any] = {
129-
# "detail": {"key": "$.sample_id", "value": str(request_entity.sample_id)}
130-
# }
131-
# assert_that(http_response.json()).is_equal_to(expected_body)
132-
# assert_that(len(captured_logs)).is_greater_than(0)
133-
# assert_that(
134-
# list(
135-
# filter(
136-
# lambda entry: str(entry["event"]).startswith("IntegrityError!"),
137-
# captured_logs,
138-
# )
139-
# )
140-
# ).is_length(1)
141-
# assert_that(
142-
# list(
143-
# filter(
144-
# lambda entry: str(entry["event"]).startswith("An HTTP error!"),
145-
# captured_logs,
146-
# )
147-
# )
148-
# ).is_length(1)
48+
@pytest.mark.parametrize(
49+
"raise_server_exceptions, expected_status",
50+
[(False, 409)],
51+
indirect=["raise_server_exceptions"],
52+
)
53+
def test_sample_jsonb_orm_create_with_duplicate_json_id_returns_409(
54+
raise_server_exceptions: bool,
55+
delete_all_fixture: None,
56+
test_client: TestClient,
57+
expected_status: int,
58+
captured_logs: list[MutableMapping[str, Any]],
59+
):
60+
sample = create_random_sample(test_client)
61+
62+
request_entity: SampleDocumentCreate = SampleDocumentCreate(
63+
sample_id=sample.id,
64+
json_data=DocumentMetadata(id=uuid.uuid4(), tags=tuple(["tag1", "tag2"])),
65+
secondary_json_dict={"key": "value"},
66+
)
67+
http_response = test_client.put(
68+
SAMPLE_JSONB_SQL_ENDPOINT, json=jsonable_encoder(request_entity)
69+
)
70+
assert_that(http_response.status_code).is_equal_to(200)
71+
request_entity_with_duplicate_id: SampleDocumentCreate = SampleDocumentCreate(
72+
sample_id=sample.id,
73+
json_data=DocumentMetadata(
74+
id=request_entity.json_data.id, tags=tuple(["tag1", "tag2"])
75+
),
76+
secondary_json_dict={"key": "value"},
77+
)
78+
http_response_with_duplicate_id = test_client.put(
79+
SAMPLE_JSONB_SQL_ENDPOINT,
80+
json=jsonable_encoder(request_entity_with_duplicate_id),
81+
)
82+
assert_that(http_response_with_duplicate_id.status_code).is_equal_to(
83+
expected_status
84+
)
85+
expected_body: dict[str, Any] = {
86+
"detail": {"key": "$.json_id.id", "value": str(request_entity.json_data.id)}
87+
}
88+
assert_that(http_response_with_duplicate_id.json()).is_equal_to(expected_body)
89+
assert_that(len(captured_logs)).is_greater_than(0)
90+
assert_that(
91+
list(
92+
filter(
93+
lambda entry: str(entry["event"]).startswith("UniqueViolationError!"),
94+
captured_logs,
95+
)
96+
)
97+
).is_length(1)
98+
assert_that(
99+
list(
100+
filter(
101+
lambda entry: str(entry["event"]).startswith("An HTTP error!"),
102+
captured_logs,
103+
)
104+
)
105+
).is_length(1)
106+
107+
108+
@pytest.mark.parametrize(
109+
"raise_server_exceptions",
110+
[False],
111+
indirect=True,
112+
)
113+
def test_sample_jsonb_orm_create_with_non_existent_parent_sample_returns_422(
114+
raise_server_exceptions: bool,
115+
delete_all_fixture: None,
116+
test_client: TestClient,
117+
captured_logs: list[MutableMapping[str, Any]],
118+
):
119+
request_entity: SampleDocumentCreate = SampleDocumentCreate(
120+
sample_id=uuid.uuid4(),
121+
json_data=DocumentMetadata(id=uuid.uuid4(), tags=tuple(["tag1", "tag2"])),
122+
secondary_json_dict={"key": "value"},
123+
)
124+
http_response = test_client.put(
125+
SAMPLE_JSONB_SQL_ENDPOINT, json=jsonable_encoder(request_entity)
126+
)
127+
assert_that(http_response.status_code).is_equal_to(422)
128+
expected_body: dict[str, Any] = {
129+
"detail": {"key": "$.sample_id", "value": str(request_entity.sample_id)}
130+
}
131+
assert_that(http_response.json()).is_equal_to(expected_body)
132+
assert_that(len(captured_logs)).is_greater_than(0)
133+
assert_that(
134+
list(
135+
filter(
136+
lambda entry: str(entry["event"]).startswith(
137+
"ForeignKeyViolationError!"
138+
),
139+
captured_logs,
140+
)
141+
)
142+
).is_length(1)
143+
assert_that(
144+
list(
145+
filter(
146+
lambda entry: str(entry["event"]).startswith("An HTTP error!"),
147+
captured_logs,
148+
)
149+
)
150+
).is_length(1)
149151

150152

151153
def test_sample_jsonb_orm_read_all(delete_all_fixture: None, test_client: TestClient):

0 commit comments

Comments
 (0)