immutable_object_test.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import pytest
  2. from pyrsistent import immutable
  3. class Empty(immutable(verbose=True)):
  4. pass
  5. class Single(immutable('x')):
  6. pass
  7. class FrozenMember(immutable('x, y_')):
  8. pass
  9. class DerivedWithNew(immutable(['x', 'y'])):
  10. def __new__(cls, x, y):
  11. return super(DerivedWithNew, cls).__new__(cls, x, y)
  12. def test_instantiate_object_with_no_members():
  13. t = Empty()
  14. t2 = t.set()
  15. assert t is t2
  16. def test_assign_non_existing_attribute():
  17. t = Empty()
  18. with pytest.raises(AttributeError):
  19. t.set(a=1)
  20. def test_basic_instantiation():
  21. t = Single(17)
  22. assert t.x == 17
  23. assert str(t) == 'Single(x=17)'
  24. def test_cannot_modify_member():
  25. t = Single(17)
  26. with pytest.raises(AttributeError):
  27. t.x = 18
  28. def test_basic_replace():
  29. t = Single(17)
  30. t2 = t.set(x=18)
  31. assert t.x == 17
  32. assert t2.x == 18
  33. def test_cannot_replace_frozen_member():
  34. t = FrozenMember(17, 18)
  35. with pytest.raises(AttributeError):
  36. t.set(y_=18)
  37. def test_derived_class_with_new():
  38. d = DerivedWithNew(1, 2)
  39. d2 = d.set(x=3)
  40. assert d2.x == 3