test_root_entity.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. from datetime import datetime
  2. from datetime import timezone
  3. from unittest import mock
  4. import pytest
  5. from clean_python import RootEntity
  6. from clean_python.base.domain.exceptions import BadRequest
  7. SOME_DATETIME = datetime(2023, 1, 1, tzinfo=timezone.utc)
  8. class User(RootEntity):
  9. name: str
  10. @pytest.fixture
  11. def user():
  12. return User(
  13. id=4,
  14. name="jan",
  15. created_at=datetime(2010, 1, 1, tzinfo=timezone.utc),
  16. updated_at=datetime(2020, 1, 1, tzinfo=timezone.utc),
  17. )
  18. @pytest.fixture
  19. def patched_now():
  20. with mock.patch(
  21. "clean_python.base.domain.root_entity.now", return_value=SOME_DATETIME
  22. ):
  23. yield
  24. def test_create(patched_now):
  25. obj = User.create(name="piet")
  26. assert obj.id is None
  27. assert obj.name == "piet"
  28. assert obj.created_at == SOME_DATETIME
  29. assert obj.updated_at == SOME_DATETIME
  30. def test_create_with_id():
  31. obj = User.create(id=42, name="piet")
  32. assert obj.id == 42
  33. def test_update(user, patched_now):
  34. actual = user.update(name="piet")
  35. assert actual is not user
  36. assert actual.name == "piet"
  37. assert actual.updated_at == SOME_DATETIME
  38. assert actual.created_at == datetime(2010, 1, 1, tzinfo=timezone.utc)
  39. def test_update_including_id(user):
  40. actual = user.update(id=4, name="piet")
  41. assert actual is not user
  42. assert actual.name == "piet"
  43. @pytest.mark.parametrize("new_id", [None, 42, "foo"])
  44. def test_update_with_wrong_id(user, new_id):
  45. with pytest.raises(BadRequest):
  46. user.update(id=new_id, name="piet")
  47. @pytest.mark.parametrize("new_id", [None, 42])
  48. def test_update_give_id(new_id):
  49. user_without_id = User.create(name="jan")
  50. actual = user_without_id.update(id=new_id, name="piet")
  51. assert actual.id == new_id