Пример #1
0
def test_main_jsonschema():
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        return_code: Exit = main([
            '--input',
            str(JSON_SCHEMA_DATA_PATH / 'person.json'),
            '--output',
            str(output_file),
            '--input-file-type',
            'jsonschema',
        ])
        assert return_code == Exit.OK
        assert (output_file.read_text() == '''# generated by datamodel-codegen:
#   filename:  person.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel, Field, conint


class Person(BaseModel):
    firstName: Optional[str] = Field(None, description="The person\'s first name.")
    lastName: Optional[str] = Field(None, description="The person\'s last name.")
    age: Optional[conint(ge=0.0)] = Field(
        None, description='Age in years which must be equal to or greater than zero.'
    )
''')
    with pytest.raises(SystemExit):
        main()
def test_main_root_id_jsonschema(mocker):
    root_id_response = mocker.Mock()
    root_id_response.text = 'dummy'
    person_response = mocker.Mock()
    person_response.text = (JSON_SCHEMA_DATA_PATH / 'person.json').read_text()
    httpx_get_mock = mocker.patch(
        'httpx.get', side_effect=[root_id_response, person_response]
    )
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        return_code: Exit = main(
            [
                '--input',
                str(JSON_SCHEMA_DATA_PATH / 'root_id.json'),
                '--output',
                str(output_file),
                '--input-file-type',
                'jsonschema',
            ]
        )
        assert return_code == Exit.OK
        assert (
            output_file.read_text()
            == (EXPECTED_MAIN_PATH / 'main_root_id' / 'output.py').read_text()
        )
        httpx_get_mock.assert_has_calls(
            [
                call('https://example.com/root_id.json'),
                call('https://example.com/person.json'),
            ]
        )
    with pytest.raises(SystemExit):
        main()
def test_main_yaml():
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        return_code: Exit = main([
            '--input',
            str(YAML_DATA_PATH / 'pet.yaml'),
            '--output',
            str(output_file),
            '--input-file-type',
            'yaml',
        ])
        assert return_code == Exit.OK
        assert (output_file.read_text() == '''# generated by datamodel-codegen:
#   filename:  pet.yaml
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from pydantic import BaseModel


class Pet(BaseModel):
    name: str
    age: int


class Model(BaseModel):
    Pet: Pet
''')
    with pytest.raises(SystemExit):
        main()
def test_main_jsonschema():
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        return_code: Exit = main([
            '--input',
            str(JSON_SCHEMA_DATA_PATH / 'person.json'),
            '--output',
            str(output_file),
            '--input-file-type',
            'jsonschema',
        ])
        assert return_code == Exit.OK
        assert (output_file.read_text() == '''# generated by datamodel-codegen:
#   filename:  person.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel, conint


class Person(BaseModel):
    firstName: Optional[str] = None
    lastName: Optional[str] = None
    age: Optional[conint(lt=0.0)] = None
''')

    with pytest.raises(SystemExit):
        main()
Пример #5
0
def test_main_jsonschema_nested_deep():
    with TemporaryDirectory() as output_dir:
        output_init_file: Path = Path(output_dir) / '__init__.py'
        output_nested_file: Path = Path(output_dir) / 'nested/deep.py'
        output_empty_parent_nested_file: Path = Path(
            output_dir) / 'empty_parent/nested/deep.py'

        return_code: Exit = main([
            '--input',
            str(JSON_SCHEMA_DATA_PATH / 'nested_person.json'),
            '--output',
            str(output_dir),
            '--input-file-type',
            'jsonschema',
        ])
        assert return_code == Exit.OK
        assert (output_init_file.read_text() == (
            EXPECTED_MAIN_PATH / 'main_jsonschema_nested_deep' /
            '__init__.py').read_text())

        assert (output_nested_file.read_text() == (
            EXPECTED_MAIN_PATH / 'main_jsonschema_nested_deep' / 'nested' /
            'deep.py').read_text())
        assert (output_empty_parent_nested_file.read_text() == (
            EXPECTED_MAIN_PATH / 'main_jsonschema_nested_deep' /
            'empty_parent' / 'nested' / 'deep.py').read_text())
    with pytest.raises(SystemExit):
        main()
Пример #6
0
def test_main_custom_template_dir(capsys: CaptureFixture) -> None:
    """Test main function with custom template directory."""

    input_filename = OPEN_API_DATA_PATH / 'api.yaml'
    custom_template_dir = DATA_PATH / 'templates'
    extra_template_data = OPEN_API_DATA_PATH / 'extra_data.json'

    with freeze_time(TIMESTAMP):
        main(
            [
                '--input',
                str(input_filename),
                '--custom-template-dir',
                str(custom_template_dir),
                '--extra-template-data',
                str(extra_template_data),
            ]
        )

    captured = capsys.readouterr()
    assert (
        captured.out
        == (EXPECTED_MAIN_PATH / 'main_custom_template_dir' / 'output.py').read_text()
    )
    assert not captured.err
Пример #7
0
def test_pyproject():
    with TemporaryDirectory() as output_dir:
        output_dir = Path(output_dir)
        with chdir(output_dir):
            output_file: Path = output_dir / 'output.py'
            pyproject_toml_path = Path(
                DATA_PATH) / "project" / "pyproject.toml"
            pyproject_toml = (pyproject_toml_path.read_text().replace(
                'INPUT_PATH', str(OPEN_API_DATA_PATH / 'api.yaml')).replace(
                    'OUTPUT_PATH', str(output_file)).replace(
                        'ALIASES_PATH',
                        str(OPEN_API_DATA_PATH /
                            'empty_aliases.json')).replace(
                                'EXTRA_TEMPLATE_DATA_PATH',
                                str(OPEN_API_DATA_PATH / 'empty_data.json'),
                            ).replace('CUSTOM_TEMPLATE_DIR_PATH',
                                      str(output_dir)))
            (output_dir / 'pyproject.toml').write_text(pyproject_toml)

            return_code: Exit = main([])
            assert return_code == Exit.OK
            assert (output_file.read_text() == (EXPECTED_MAIN_PATH /
                                                'pyproject' /
                                                'output.py').read_text())
    with pytest.raises(SystemExit):
        main()
def test_main_external_files_in_directory(tmpdir_factory: TempdirFactory) -> None:
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        return_code: Exit = main(
            [
                '--input',
                str(
                    JSON_SCHEMA_DATA_PATH
                    / 'external_files_in_directory'
                    / 'person.json'
                ),
                '--output',
                str(output_file),
                '--input-file-type',
                'jsonschema',
            ]
        )
        assert return_code == Exit.OK
        assert (
            output_file.read_text()
            == (
                EXPECTED_MAIN_PATH / 'main_external_files_in_directory' / 'output.py'
            ).read_text()
        )
    with pytest.raises(SystemExit):
        main()
def test_main_no_file(capsys: CaptureFixture, expected: str) -> None:
    """Test main function on non-modular file with no output name."""

    input_filename = OPEN_API_DATA_PATH / 'api.yaml'

    with freeze_time(TIMESTAMP):
        main(['--input', str(input_filename)])

    captured = capsys.readouterr()
    assert captured.out == expected
    assert not captured.err
Пример #10
0
def test_main_no_file(capsys: CaptureFixture) -> None:
    """Test main function on non-modular file with no output name."""

    input_filename = OPEN_API_DATA_PATH / 'api.yaml'

    with freeze_time(TIMESTAMP):
        main(['--input', str(input_filename)])

    captured = capsys.readouterr()
    assert (captured.out == (EXPECTED_MAIN_PATH / 'main_no_file' /
                             'output.py').read_text())
    assert not captured.err
Пример #11
0
def test_main_jsonschema_nested_deep():
    import os

    os.chdir(DATA_PATH / 'jsonschema')
    with TemporaryDirectory() as output_dir:
        output_init_file: Path = Path(output_dir) / '__init__.py'
        output_nested_file: Path = Path(output_dir) / 'nested/deep.py'
        return_code: Exit = main([
            '--input',
            str(JSON_SCHEMA_DATA_PATH / 'nested_person.json'),
            '--output',
            str(output_dir),
            '--input-file-type',
            'jsonschema',
        ])
        assert return_code == Exit.OK
        print(list(Path(output_dir).iterdir()))
        assert (output_init_file.read_text() ==
                '''# generated by datamodel-codegen:
#   filename:  nested_person.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel

import nested.deep


class NestedPerson(BaseModel):
    nested_deep_childJson: Optional[nested.deep.Json] = None
''')

        assert (output_nested_file.read_text() ==
                '''# generated by datamodel-codegen:
#   filename:  nested_person.json
#   timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel


class Json(BaseModel):
    firstName: Optional[str] = None
''')
    with pytest.raises(SystemExit):
        main()
Пример #12
0
def test_main_modular(tmpdir_factory: TempdirFactory) -> None:
    """Test main function on modular file."""

    output_directory = Path(tmpdir_factory.mktemp('output'))

    input_filename = OPEN_API_DATA_PATH / 'modular.yaml'
    output_path = output_directory / 'model'

    with freeze_time(TIMESTAMP):
        main(['--input', str(input_filename), '--output', str(output_path)])
    main_modular_dir = EXPECTED_MAIN_PATH / 'main_modular'
    for path in main_modular_dir.rglob('*.py'):
        result = output_path.joinpath(path.relative_to(main_modular_dir)).read_text()
        assert result == path.read_text()
Пример #13
0
def test_main_json_failed():
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        return_code: Exit = main([
            '--input',
            str(JSON_DATA_PATH / 'broken.json'),
            '--output',
            str(output_file),
            '--input-file-type',
            'json',
        ])
        assert return_code == Exit.ERROR
    with pytest.raises(SystemExit):
        main()
Пример #14
0
def test_main():
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        return_code: Exit = main([
            '--input',
            str(OPEN_API_DATA_PATH / 'api.yaml'),
            '--output',
            str(output_file),
        ])
        assert return_code == Exit.OK
        assert (output_file.read_text() == (EXPECTED_MAIN_PATH / 'main' /
                                            'output.py').read_text())

    with pytest.raises(SystemExit):
        main()
Пример #15
0
def test_main_modular(tmpdir_factory: TempdirFactory,
                      expected: Mapping[str, str]) -> None:
    """Test main function on modular file."""

    output_directory = Path(tmpdir_factory.mktemp('output'))

    input_filename = OPEN_API_DATA_PATH / 'modular.yaml'
    output_path = output_directory / 'model'

    with freeze_time(TIMESTAMP):
        main(['--input', str(input_filename), '--output', str(output_path)])

    for key, value in expected.items():
        result = output_path.joinpath(*key).read_text()
        assert result == value
Пример #16
0
def test_main_with_more_bad_aliases():
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        return_code: Exit = main([
            '--input',
            str(OPEN_API_DATA_PATH / 'api.yaml'),
            '--aliases',
            str(OPEN_API_DATA_PATH / 'list.json'),
            '--output',
            str(output_file),
        ])
        assert return_code == Exit.ERROR

    with pytest.raises(SystemExit):
        main()
Пример #17
0
def test_main_with_bad_extra_data():
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        return_code: Exit = main([
            '--input',
            str(OPEN_API_DATA_PATH / 'api.yaml'),
            '--extra-template-data',
            str(OPEN_API_DATA_PATH / 'not.json'),
            '--output',
            str(output_file),
        ])
        assert return_code == Exit.ERROR

    with pytest.raises(SystemExit):
        main()
def test_main_jsonschema_id_as_stdin(monkeypatch):
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        monkeypatch.setattr('sys.stdin', (JSON_SCHEMA_DATA_PATH / 'id.json').open())
        return_code: Exit = main(
            ['--output', str(output_file), '--input-file-type', 'jsonschema',]
        )
        assert return_code == Exit.OK
        assert (
            output_file.read_text()
            == (
                EXPECTED_MAIN_PATH / 'main_jsonschema_id_stdin' / 'output.py'
            ).read_text()
        )
    with pytest.raises(SystemExit):
        main()
Пример #19
0
def test_main_json():
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        return_code: Exit = main([
            '--input',
            str(JSON_DATA_PATH / 'pet.json'),
            '--output',
            str(output_file),
            '--input-file-type',
            'json',
        ])
        assert return_code == Exit.OK
        assert (output_file.read_text() == (EXPECTED_MAIN_PATH / 'main_json' /
                                            'output.py').read_text())
    with pytest.raises(SystemExit):
        main()
Пример #20
0
def test_space_and_special_characters_dict():
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        return_code: Exit = main([
            '--input',
            str(PYTHON_DATA_PATH / 'space_and_special_characters_dict.py'),
            '--output',
            str(output_file),
            '--input-file-type',
            'dict',
        ])
        assert return_code == Exit.OK
        assert (output_file.read_text() == (
            EXPECTED_MAIN_PATH / 'space_and_special_characters_dict' /
            'output.py').read_text())
    with pytest.raises(SystemExit):
        main()
Пример #21
0
def test_allow_population_by_field_name():
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        return_code: Exit = main([
            '--input',
            str(OPEN_API_DATA_PATH / 'api.yaml'),
            '--output',
            str(output_file),
            '--allow-population-by-field-name',
        ])
        assert return_code == Exit.OK
        assert (output_file.read_text() == (EXPECTED_MAIN_PATH /
                                            'allow_population_by_field_name' /
                                            'output.py').read_text())

    with pytest.raises(SystemExit):
        main()
Пример #22
0
def test_main_json_reuse_enum():
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        return_code: Exit = main([
            '--input',
            str(JSON_SCHEMA_DATA_PATH / 'duplicate_enum.json'),
            '--output',
            str(output_file),
            '--input-file-type',
            'jsonschema',
            '--reuse-model',
        ])
        assert return_code == Exit.OK
        assert (output_file.read_text() == (EXPECTED_MAIN_PATH /
                                            'main_json_reuse_enum' /
                                            'output.py').read_text())
    with pytest.raises(SystemExit):
        main()
def test_pyproject():
    with TemporaryDirectory() as output_dir:
        output_dir = Path(output_dir)
        pyproject_toml = Path(DATA_PATH) / "project" / "pyproject.toml"
        shutil.copy(pyproject_toml, output_dir)
        output_file: Path = output_dir / 'output.py'
        return_code: Exit = main([
            '--input',
            str(OPEN_API_DATA_PATH / 'api.yaml'),
            '--output',
            str(output_file),
        ])
        assert return_code == Exit.OK
        assert (output_file.read_text() == (EXPECTED_MAIN_PATH / 'pyproject' /
                                            'output.py').read_text())

    with pytest.raises(SystemExit):
        main()
Пример #24
0
def test_main_invalid_model_name():
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        return_code: Exit = main([
            '--input',
            str(JSON_SCHEMA_DATA_PATH / 'invalid_model_name.json'),
            '--output',
            str(output_file),
            '--input-file-type',
            'jsonschema',
            '--class-name',
            'ValidModelName',
        ])
        assert return_code == Exit.OK
        assert (output_file.read_text() == (EXPECTED_MAIN_PATH /
                                            'main_invalid_model_name' /
                                            'output.py').read_text())
    with pytest.raises(SystemExit):
        main()
Пример #25
0
def test_main_autodetect_failed():
    with TemporaryDirectory() as input_dir, TemporaryDirectory() as output_dir:
        input_file: Path = Path(input_dir) / 'input.yaml'
        output_file: Path = Path(output_dir) / 'output.py'

        input_file.write_text(':')

        return_code: Exit = main([
            '--input',
            str(input_file),
            '--output',
            str(output_file),
            '--input-file-type',
            'auto',
        ])
        assert return_code == Exit.ERROR

    with pytest.raises(SystemExit):
        main()
Пример #26
0
def test_main_use_standard_collections(tmpdir_factory: TempdirFactory) -> None:
    output_directory = Path(tmpdir_factory.mktemp('output'))

    input_filename = OPEN_API_DATA_PATH / 'modular.yaml'
    output_path = output_directory / 'model'

    with freeze_time(TIMESTAMP):
        main([
            '--input',
            str(input_filename),
            '--output',
            str(output_path),
            '--use-standard-collections',
        ])
    main_use_standard_collections_dir = (EXPECTED_MAIN_PATH /
                                         'main_use_standard_collections')
    for path in main_use_standard_collections_dir.rglob('*.py'):
        result = output_path.joinpath(
            path.relative_to(main_use_standard_collections_dir)).read_text()
        assert result == path.read_text()
Пример #27
0
def test_main_jsonschema_ids(tmpdir_factory: TempdirFactory) -> None:
    output_directory = Path(tmpdir_factory.mktemp('output'))

    input_filename = JSON_SCHEMA_DATA_PATH / 'ids' / 'Organization.schema.json'
    output_path = output_directory / 'model'

    with freeze_time(TIMESTAMP):
        main([
            '--input',
            str(input_filename),
            '--output',
            str(output_path),
            '--input-file-type',
            'jsonschema',
        ])
    main_jsonschema_ids_dir = EXPECTED_MAIN_PATH / 'main_jsonschema_ids'
    for path in main_jsonschema_ids_dir.rglob('*.py'):
        result = output_path.joinpath(
            path.relative_to(main_jsonschema_ids_dir)).read_text()
        assert result == path.read_text()
Пример #28
0
def test_main_base_class():
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        shutil.copy(DATA_PATH / 'pyproject.toml',
                    Path(output_dir) / 'pyproject.toml')
        return_code: Exit = main([
            '--input',
            str(OPEN_API_DATA_PATH / 'api.yaml'),
            '--output',
            str(output_file),
            '--base-class',
            'custom_module.Base',
        ])
        assert return_code == Exit.OK
        assert (output_file.read_text() == (EXPECTED_MAIN_PATH /
                                            'main_base_class' /
                                            'output.py').read_text())

    with pytest.raises(SystemExit):
        main()
Пример #29
0
def test_main_jsonschema_multiple_files():
    with TemporaryDirectory() as output_dir:
        output_path: Path = Path(output_dir)
        return_code: Exit = main([
            '--input',
            str(JSON_SCHEMA_DATA_PATH / 'multiple_files'),
            '--output',
            str(output_path),
            '--input-file-type',
            'jsonschema',
        ])
        assert return_code == Exit.OK
        main_modular_dir = EXPECTED_MAIN_PATH / 'multiple_files'
        for path in main_modular_dir.rglob('*.py'):
            result = output_path.joinpath(
                path.relative_to(main_modular_dir)).read_text()
            assert result == path.read_text()

    with pytest.raises(SystemExit):
        main()
Пример #30
0
def test_validation_failed():
    with TemporaryDirectory() as output_dir:
        output_file: Path = Path(output_dir) / 'output.py'
        assert (main([
            '--input',
            str(OPEN_API_DATA_PATH / 'invalid.yaml'),
            '--output',
            str(output_file),
            '--input-file-type',
            'openapi',
            '--validation',
        ]) == Exit.ERROR)