from typing import Optional, Any
import pytest
from pydantic import ValidationError
# Packages imports
from pydantic import BaseModel, field_validator, ValidationInfo, ConfigDict


class A(BaseModel):
    model_config = ConfigDict(validate_default=True)
    var1: int
    var2: Optional[str] = None

    @field_validator('var2', mode='after')
    @classmethod
    def check_var2(cls, value: Any, info: ValidationInfo) -> Any:

        if info.data['var1'] == 2:

            if not value:
                raise ValueError('field required when var1==2')

        return value


def test_pydantic_validators_optional_none():
    data = {
        "var1": 1,
        # 'var2': None,
        # "var2": {'var3': 'hello', 'var4': 'world'}
    }
    # a = A.model_validate(data)
    a = A(**data)
    assert a
    assert a.var1 == 1
    assert a.var2 is None


def test_pydantic_validators_optional_2():
    data = {
        "var1": 2,
        # "var2": {'var3': 'hello', 'var4': 'world'}
    }
    with pytest.raises(ValidationError):
        a = A.model_validate(data)

    data = {
        "var1": 2,
        "var2": 'hello'
    }
    a = A.model_validate(data)
    assert a
    assert a.var2 == 'hello'
