test_value_object.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import pytest
  2. from pydantic import field_validator
  3. from pydantic import ValidationError
  4. from clean_python import BadRequest
  5. from clean_python import ValueObject
  6. class Color(ValueObject):
  7. name: str
  8. @field_validator("name")
  9. def name_not_empty(cls, v, _):
  10. assert v != ""
  11. return v
  12. @pytest.fixture
  13. def color():
  14. return Color(name="green")
  15. def test_validator():
  16. with pytest.raises(ValidationError) as e:
  17. Color(name="")
  18. assert e.type is ValidationError # not BadRequest
  19. def test_create_err():
  20. with pytest.raises(BadRequest):
  21. Color.create(name="")
  22. def test_update(color):
  23. updated = color.update(name="red")
  24. assert color.name == "green"
  25. assert updated.name == "red"
  26. def test_update_validates(color):
  27. with pytest.raises(BadRequest):
  28. color.update(name="")
  29. def test_run_validation(color):
  30. assert color.run_validation() == color
  31. def test_run_validation_err():
  32. color = Color.model_construct(name="")
  33. with pytest.raises(BadRequest):
  34. color.run_validation()
  35. def test_hashable(color):
  36. assert len({color, color}) == 1
  37. def test_eq(color):
  38. assert color == color
  39. def test_neq(color):
  40. assert color != Color(name="red")