Skip to content

Commit

Permalink
Improve schema difference test harness
Browse files Browse the repository at this point in the history
Use diff-match-patch to show differences only.
Create baseline yml if it does not exist.
  • Loading branch information
jayvdb committed Jul 20, 2020
1 parent b70fef2 commit a3c7b45
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
3 changes: 2 additions & 1 deletion requirements/testing.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
diff-match-patch
pytest>=5.3.5
pytest-django>=3.8.0
pytest-cov>=2.8.1
flake8>=3.7.9
mypy>=0.770
djangorestframework-stubs>=1.1.0
isort>=5.0.4
isort>=5.0.4
36 changes: 32 additions & 4 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,46 @@
import os
import sys

from diff_match_patch import diff_match_patch

from drf_spectacular.validation import validate_schema


def assert_schema(schema, reference_file):
def assert_schema(schema, reference_filename):
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={})

with open(reference_file.replace('.yml', '_out.yml'), 'wb') as fh:
if not os.path.exists(reference_filename):
generated_filename = reference_filename
else:
generated_filename = reference_filename.replace('.yml', '_out.yml')

with open(generated_filename, 'wb') as fh:
fh.write(schema_yml)

with open(reference_file) as fh:
assert schema_yml.decode() == fh.read()
if generated_filename == reference_filename:
raise RuntimeError(
f'{reference_filename} was not found. '
f'It has been created with the generated schema. '
f'Review carefully, as it is the baseline for subsequent checks.')

generated = schema_yml.decode()

with open(reference_filename) as fh:
expected = fh.read()

if expected != generated:
dmp = diff_match_patch()
diff = dmp.diff_main(expected, generated)
dmp.diff_cleanupSemantic(diff)
patch = dmp.patch_toText(dmp.patch_make(diff))
assert patch, f'Failed to generate patch from "{expected}" to "{generated}"'
msg = f"Patch from {reference_filename} to {generated_filename}: {patch}"
print(msg, file=sys.stderr)
assert expected == generated, msg

# this is more a less a sanity check as checked-in schemas should be valid anyhow
validate_schema(schema)
Expand Down

0 comments on commit a3c7b45

Please sign in to comment.