|
| 1 | +import imp |
| 2 | +import json |
| 3 | +import sys |
| 4 | +from inspect import isclass |
| 5 | + |
| 6 | +import pydantic |
| 7 | +import pytest |
| 8 | + |
| 9 | +from json_to_models.generator import MetadataGenerator |
| 10 | +from json_to_models.models.base import generate_code |
| 11 | +from json_to_models.models.pydantic import PydanticModelCodeGenerator |
| 12 | +from json_to_models.models.structure import compose_models_flat |
| 13 | +from json_to_models.registry import ModelRegistry |
| 14 | +from .test_script import test_data_path |
| 15 | + |
| 16 | +test_self_validate_pydantic_data = [ |
| 17 | + pytest.param(test_data_path / "gists.json", list, id="gists.json"), |
| 18 | + pytest.param(test_data_path / "users.json", list, id="users.json"), |
| 19 | + pytest.param(test_data_path / "unicode.json", dict, id="unicode.json"), |
| 20 | + pytest.param(test_data_path / "photos.json", dict, id="photos.json"), |
| 21 | +] |
| 22 | + |
| 23 | + |
| 24 | +@pytest.mark.parametrize("data,data_type", test_self_validate_pydantic_data) |
| 25 | +def test_self_validate_pydantic(data, data_type): |
| 26 | + with data.open() as f: |
| 27 | + data = json.load(f) |
| 28 | + |
| 29 | + gen = MetadataGenerator( |
| 30 | + dict_keys_fields=['files'] |
| 31 | + ) |
| 32 | + reg = ModelRegistry() |
| 33 | + if data_type is not list: |
| 34 | + data = [data] |
| 35 | + fields = gen.generate(*data) |
| 36 | + reg.process_meta_data(fields, model_name="TestModel") |
| 37 | + reg.merge_models(generator=gen) |
| 38 | + reg.generate_names() |
| 39 | + |
| 40 | + structure = compose_models_flat(reg.models_map) |
| 41 | + code = generate_code(structure, PydanticModelCodeGenerator) |
| 42 | + module = imp.new_module("test_models") |
| 43 | + sys.modules["test_models"] = module |
| 44 | + try: |
| 45 | + exec(compile(code, "test_models.py", "exec"), module.__dict__) |
| 46 | + except Exception as e: |
| 47 | + assert not e, code |
| 48 | + |
| 49 | + import test_models |
| 50 | + for name in dir(test_models): |
| 51 | + cls = getattr(test_models, name) |
| 52 | + if isclass(cls) and issubclass(cls, pydantic.BaseModel): |
| 53 | + cls.update_forward_refs() |
| 54 | + for item in data: |
| 55 | + obj = test_models.TestModel.parse_obj(item) |
| 56 | + assert obj |
0 commit comments