Pydantic validation fails when importing module from a package when running pytest

47 Views Asked by At

I am trying to understand why pydantic validation fails here. I was running into this in larger codebase and was able to condense it into small example.

there is misc_build.py where pydantic model is defined

metadata_manager/misc_build.py

from pydantic import BaseModel
from md_enums import MiscBuildType


class VersionInfo(BaseModel):
    build_type: MiscBuildType

then there is md_enums.py where the Enum is defined

metadata_manager/md_enums.py

class MiscBuildType(enum.Enum):
    PROD = "PROD"
    DEV = "DEV"

finally there is test file metadata_manager/tests/test_build.py

from misc_build import VersionInfo

import md_enums
import metadata_manager.md_enums

from md_enums import MiscBuildType as BuildType1
from metadata_manager.md_enums import MiscBuildType as BuildType2


def test_build():
    assert md_enums.__file__ == metadata_manager.md_enums.__file__
    print(
        f"imported from the same file: {md_enums.__file__ == metadata_manager.md_enums.__file__}"
    )

    version_info = VersionInfo(build_type=BuildType1.DEV)  # this works
    print(f"version info 1: {version_info}")

    version_info = VersionInfo(build_type=BuildType2.DEV)  # this fails
    print(f"version info 2: {version_info}")


The first instance of VersionInfo is created successfully but the second one fails with this message when running pytest.

E       pydantic_core._pydantic_core.ValidationError: 1 validation error for VersionInfo
E       build_type
E         Input should be 'PROD' or 'DEV' [type=enum, input_value=<MiscBuildType.DEV: 'DEV'>, input_type=MiscBuildType]

It seems that pydantic sees those as two different enums even though they are imported from the same file.

So my question is - why is this happening when the module is imported as metadata_manager.md_enums?

btw there are conftest.py files in metadata_manager directory as well as in the parent folder which the metadata_manager is part of but there is nothing there that seems likely to cause this.

0

There are 0 best solutions below