checked_set_test.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import pickle
  2. import pytest
  3. from pyrsistent import CheckedPSet, PSet, InvariantException, CheckedType, CheckedPVector, CheckedValueTypeError
  4. class Naturals(CheckedPSet):
  5. __type__ = int
  6. __invariant__ = lambda value: (value >= 0, 'Negative value')
  7. def test_instantiate():
  8. x = Naturals([1, 2, 3, 3])
  9. assert list(x) == [1, 2, 3]
  10. assert isinstance(x, Naturals)
  11. assert isinstance(x, PSet)
  12. assert isinstance(x, CheckedType)
  13. def test_add():
  14. x = Naturals()
  15. x2 = x.add(1)
  16. assert list(x2) == [1]
  17. assert isinstance(x2, Naturals)
  18. def test_invalid_type():
  19. with pytest.raises(CheckedValueTypeError):
  20. Naturals([1, 2.0])
  21. def test_breaking_invariant():
  22. try:
  23. Naturals([1, -1])
  24. assert False
  25. except InvariantException as e:
  26. assert e.invariant_errors == ('Negative value',)
  27. def test_repr():
  28. x = Naturals([1, 2])
  29. assert str(x) == 'Naturals([1, 2])'
  30. def test_default_serialization():
  31. x = Naturals([1, 2])
  32. assert x.serialize() == set([1, 2])
  33. class StringNaturals(Naturals):
  34. @staticmethod
  35. def __serializer__(format, value):
  36. return format.format(value)
  37. def test_custom_serialization():
  38. x = StringNaturals([1, 2])
  39. assert x.serialize("{0}") == set(["1", "2"])
  40. class NaturalsVector(CheckedPVector):
  41. __type__ = Naturals
  42. def test_multi_level_serialization():
  43. x = NaturalsVector.create([[1, 2], [3, 4]])
  44. assert str(x) == "NaturalsVector([Naturals([1, 2]), Naturals([3, 4])])"
  45. sx = x.serialize()
  46. assert sx == [set([1, 2]), set([3, 4])]
  47. assert isinstance(sx[0], set)
  48. def test_create():
  49. assert Naturals.create([1, 2]) == Naturals([1, 2])
  50. def test_evolver_returns_same_instance_when_no_updates():
  51. x = Naturals([1, 2])
  52. assert x.evolver().persistent() is x
  53. def test_pickling():
  54. x = Naturals([1, 2])
  55. y = pickle.loads(pickle.dumps(x, -1))
  56. assert x == y
  57. assert isinstance(y, Naturals)
  58. def test_supports_weakref():
  59. import weakref
  60. weakref.ref(Naturals([1, 2]))