Skip to content

Commit

Permalink
add test_fields API response test #501
Browse files Browse the repository at this point in the history
  • Loading branch information
tfranzel committed Sep 9, 2021
1 parent 5743e4a commit 7f4831a
Show file tree
Hide file tree
Showing 3 changed files with 111 additions and 16 deletions.
28 changes: 17 additions & 11 deletions tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,21 @@
from drf_spectacular.validation import validate_schema


def build_absolute_file_path(relative_path):
return os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
relative_path
)


def assert_schema(schema, reference_filename, transforms=None):
from drf_spectacular.renderers import OpenApiJsonRenderer, OpenApiYamlRenderer

schema_yml = OpenApiYamlRenderer().render(schema, renderer_context={})
# render also a json and provoke serialization issues
OpenApiJsonRenderer().render(schema, renderer_context={})

reference_filename = os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))), reference_filename
)
reference_filename = build_absolute_file_path(reference_filename)

with open(reference_filename.replace('.yml', '_out.yml'), 'wb') as fh:
fh.write(schema_yml)
Expand All @@ -36,21 +41,22 @@ def assert_schema(schema, reference_filename, transforms=None):
for t in transforms or []:
generated = t(generated)

assert_equal(expected, generated)
assert_equal(generated, expected)
# this is more a less a sanity check as checked-in schemas should be valid anyhow
validate_schema(schema)


def assert_equal(a, b):
if not isinstance(a, str) or not isinstance(b, str):
a = json.dumps(a, indent=4)
b = json.dumps(b, indent=4)
def assert_equal(actual, expected):
if not isinstance(actual, str):
actual = json.dumps(actual, indent=4)
if not isinstance(expected, str):
expected = json.dumps(expected, indent=4)
diff = difflib.unified_diff(
a.splitlines(True),
b.splitlines(True),
expected.splitlines(True),
actual.splitlines(True),
)
diff = ''.join(diff)
assert a == b and not diff, diff
assert actual == expected and not diff, diff


def generate_schema(route, viewset=None, view=None, view_function=None, patterns=None):
Expand Down
21 changes: 16 additions & 5 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import functools
import json
import tempfile
import uuid
from datetime import date, datetime, timedelta
from datetime import timedelta
from decimal import Decimal
from typing import Optional

Expand All @@ -17,7 +18,7 @@
from rest_framework.test import APIClient

from drf_spectacular.generators import SchemaGenerator
from tests import assert_schema
from tests import assert_equal, assert_schema, build_absolute_file_path

try:
functools_cached_property = functools.cached_property # type: ignore
Expand Down Expand Up @@ -289,7 +290,7 @@ def test_fields(no_warnings):
@pytest.mark.urls(__name__)
@pytest.mark.django_db
def test_model_setup_is_valid():
aux = Aux()
aux = Aux(id='0ac6930d-87f4-40e8-8242-10a3ed31a335')
aux.save()

m = AllFields(
Expand All @@ -308,8 +309,8 @@ def test_model_setup_is_valid():
field_decimal=Decimal('666.333'),
field_file=None,
field_img=None, # TODO fill with data below
field_date=date.today(),
field_datetime=datetime.now(),
field_date='2021-09-09',
field_datetime='2021-09-09T10:15:26.049862',
field_bigint=11111111111111,
field_smallint=111111,
field_posint=123,
Expand All @@ -332,3 +333,13 @@ def test_model_setup_is_valid():

response = APIClient().get(reverse('allfields-detail', args=(m.pk,)))
assert response.status_code == 200

with open(build_absolute_file_path('tests/test_fields_response.json')) as fh:
expected = json.load(fh)

if DJANGO_VERSION < '3':
expected['field_file'] = f'http://testserver/allfields/1/{m.field_file.name}'
else:
expected['field_file'] = f'http://testserver/{m.field_file.name}'

assert_equal(json.loads(response.content), expected)
78 changes: 78 additions & 0 deletions tests/test_fields_response.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
{
"id": 1,
"field_decimal_uncoerced": 666.333,
"field_method_float": 1.3456,
"field_method_object": {
"key": "value"
},
"field_regex": "12345asdfg-a",
"field_list": [
1.1,
2.2,
3.3
],
"field_list_serializer": [
{
"id": "0ac6930d-87f4-40e8-8242-10a3ed31a335",
"field_foreign": null
}
],
"field_related_slug": "0ac6930d-87f4-40e8-8242-10a3ed31a335",
"field_related_string": "Aux object (0ac6930d-87f4-40e8-8242-10a3ed31a335)",
"field_related_hyperlink": "http://testserver/aux/0ac6930d-87f4-40e8-8242-10a3ed31a335/",
"field_identity_hyperlink": "http://testserver/allfields/1/",
"field_read_only_nav_uuid": "0ac6930d-87f4-40e8-8242-10a3ed31a335",
"field_read_only_nav_uuid_3steps": null,
"field_read_only_model_function_basic": true,
"field_read_only_model_function_model": "0ac6930d-87f4-40e8-8242-10a3ed31a335",
"field_bool_override": true,
"field_model_property_float": 1.337,
"field_model_cached_property_float": 1.337,
"field_model_py_cached_property_float": 1.337,
"field_dict_int": {
"A": 1,
"B": 2
},
"field_json": {
"A": 1,
"B": 2
},
"field_sub_object_calculated": 1,
"field_sub_object_nested_calculated": 1,
"field_sub_object_model_int": 1,
"field_sub_object_cached_calculated": 1,
"field_sub_object_cached_nested_calculated": 1,
"field_sub_object_cached_model_int": 1,
"field_sub_object_py_cached_calculated": 1,
"field_sub_object_py_cached_nested_calculated": 1,
"field_sub_object_py_cached_model_int": 1,
"field_optional_sub_object_calculated": 1,
"field_sub_object_optional_int": 1,
"field_int": 1,
"field_float": 1.25,
"field_bool": true,
"field_char": "char",
"field_text": "text",
"field_slug": "all_fields",
"field_email": "[email protected]",
"field_uuid": "00000000-0000-0000-0000-000000000000",
"field_url": "https://github.com/tfranzel/drf-spectacular",
"field_ip_generic": "2001:db8::8a2e:370:7334",
"field_decimal": "666.333",
"field_file": "http://testserver/hello_p8Eotwr.txt",
"field_img": null,
"field_date": "2021-09-09",
"field_datetime": "2021-09-09T10:15:26.049862",
"field_bigint": 11111111111111,
"field_smallint": 111111,
"field_posint": 123,
"field_possmallint": 1,
"field_nullbool": null,
"field_time": "00:05:23.283000",
"field_duration": "00:00:10",
"field_foreign": "0ac6930d-87f4-40e8-8242-10a3ed31a335",
"field_o2o": "0ac6930d-87f4-40e8-8242-10a3ed31a335",
"field_m2m": [
"0ac6930d-87f4-40e8-8242-10a3ed31a335"
]
}

0 comments on commit 7f4831a

Please sign in to comment.