test_referencing_suite.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from pathlib import Path
  2. import json
  3. import os
  4. import pytest
  5. from referencing import Registry
  6. from referencing.exceptions import Unresolvable
  7. import referencing.jsonschema
  8. class SuiteNotFound(Exception):
  9. def __str__(self): # pragma: no cover
  10. return (
  11. "Cannot find the referencing suite. "
  12. "Set the REFERENCING_SUITE environment variable to the path to "
  13. "the suite, or run the test suite from alongside a full checkout "
  14. "of the git repository."
  15. )
  16. if "REFERENCING_SUITE" in os.environ: # pragma: no cover
  17. SUITE = Path(os.environ["REFERENCING_SUITE"]) / "tests"
  18. else:
  19. SUITE = Path(__file__).parent.parent.parent / "suite/tests"
  20. if not SUITE.is_dir(): # pragma: no cover
  21. raise SuiteNotFound()
  22. DIALECT_IDS = json.loads(SUITE.joinpath("specifications.json").read_text())
  23. @pytest.mark.parametrize(
  24. "test_path",
  25. [
  26. pytest.param(each, id=f"{each.parent.name}-{each.stem}")
  27. for each in SUITE.glob("*/**/*.json")
  28. ],
  29. )
  30. def test_referencing_suite(test_path, subtests):
  31. dialect_id = DIALECT_IDS[test_path.relative_to(SUITE).parts[0]]
  32. specification = referencing.jsonschema.specification_with(dialect_id)
  33. loaded = json.loads(test_path.read_text())
  34. registry = loaded["registry"]
  35. registry = Registry().with_resources(
  36. (uri, specification.create_resource(contents))
  37. for uri, contents in loaded["registry"].items()
  38. )
  39. for test in loaded["tests"]:
  40. with subtests.test(test=test):
  41. if "normalization" in test_path.stem:
  42. pytest.xfail("APIs need to change for proper URL support.")
  43. resolver = registry.resolver(base_uri=test.get("base_uri", ""))
  44. if test.get("error"):
  45. with pytest.raises(Unresolvable):
  46. resolver.lookup(test["ref"])
  47. else:
  48. resolved = resolver.lookup(test["ref"])
  49. assert resolved.contents == test["target"]
  50. then = test.get("then")
  51. while then: # pragma: no cover
  52. with subtests.test(test=test, then=then):
  53. resolved = resolved.resolver.lookup(then["ref"])
  54. assert resolved.contents == then["target"]
  55. then = then.get("then")