Coverage for tests/test_encoders.py: 70.73%

33 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-15 16:47 +0200

1"""Tests for the `encoders` module.""" 

2 

3from __future__ import annotations 

4 

5import json 

6 

7import pytest 

8from jsonschema import ValidationError, validate 

9 

10from griffe import Function, GriffeLoader, Module, Object 

11 

12 

13def test_minimal_data_is_enough() -> None: 

14 """Test serialization and de-serialization. 

15 

16 This is an end-to-end test that asserts 

17 we can load back a serialized tree and 

18 infer as much data as within the original tree. 

19 """ 

20 loader = GriffeLoader() 

21 module = loader.load("griffe") 

22 minimal = module.as_json(full=False) 

23 full = module.as_json(full=True) 

24 reloaded = Module.from_json(minimal) 

25 assert reloaded.as_json(full=False) == minimal 

26 assert reloaded.as_json(full=True) == full 

27 

28 # Also works (but will result in a different type hint). 

29 assert Object.from_json(minimal) 

30 

31 # Won't work if the JSON doesn't represent the type requested. 

32 with pytest.raises(TypeError, match="provided JSON object is not of type"): 

33 Function.from_json(minimal) 

34 

35 

36# use this function in test_json_schema to ease schema debugging 

37def _validate(obj: dict, schema: dict) -> None: 

38 if "members" in obj: 

39 for member in obj["members"]: 

40 _validate(member, schema) 

41 

42 try: 

43 validate(obj, schema) 

44 except ValidationError: 

45 print(obj["path"]) # noqa: T201 

46 raise 

47 

48 

49def test_json_schema() -> None: 

50 """Assert that our serialized data matches our JSON schema.""" 

51 loader = GriffeLoader() 

52 module = loader.load("griffe") 

53 loader.resolve_aliases() 

54 data = json.loads(module.as_json(full=True)) 

55 with open("docs/schema.json") as f: 

56 schema = json.load(f) 

57 validate(data, schema)