freeze_test.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. """Tests for freeze and thaw."""
  2. from pyrsistent import v, m, s, freeze, thaw, PRecord, field, mutant
  3. ## Freeze
  4. def test_freeze_basic():
  5. assert freeze(1) == 1
  6. assert freeze('foo') == 'foo'
  7. def test_freeze_list():
  8. assert freeze([1, 2]) == v(1, 2)
  9. def test_freeze_dict():
  10. result = freeze({'a': 'b'})
  11. assert result == m(a='b')
  12. assert type(freeze({'a': 'b'})) is type(m())
  13. def test_freeze_set():
  14. result = freeze(set([1, 2, 3]))
  15. assert result == s(1, 2, 3)
  16. assert type(result) is type(s())
  17. def test_freeze_recurse_in_dictionary_values():
  18. result = freeze({'a': [1]})
  19. assert result == m(a=v(1))
  20. assert type(result['a']) is type(v())
  21. def test_freeze_recurse_in_lists():
  22. result = freeze(['a', {'b': 3}])
  23. assert result == v('a', m(b=3))
  24. assert type(result[1]) is type(m())
  25. def test_freeze_recurse_in_tuples():
  26. """Values in tuples are recursively frozen."""
  27. result = freeze(('a', {}))
  28. assert result == ('a', m())
  29. assert type(result[1]) is type(m())
  30. ## Thaw
  31. def test_thaw_basic():
  32. assert thaw(1) == 1
  33. assert thaw('foo') == 'foo'
  34. def test_thaw_list():
  35. result = thaw(v(1, 2))
  36. assert result == [1, 2]
  37. assert type(result) is list
  38. def test_thaw_dict():
  39. result = thaw(m(a='b'))
  40. assert result == {'a': 'b'}
  41. assert type(result) is dict
  42. def test_thaw_set():
  43. result = thaw(s(1, 2))
  44. assert result == set([1, 2])
  45. assert type(result) is set
  46. def test_thaw_recurse_in_mapping_values():
  47. result = thaw(m(a=v(1)))
  48. assert result == {'a': [1]}
  49. assert type(result['a']) is list
  50. def test_thaw_recurse_in_vectors():
  51. result = thaw(v('a', m(b=3)))
  52. assert result == ['a', {'b': 3}]
  53. assert type(result[1]) is dict
  54. def test_thaw_recurse_in_tuples():
  55. result = thaw(('a', m()))
  56. assert result == ('a', {})
  57. assert type(result[1]) is dict
  58. def test_thaw_can_handle_subclasses_of_persistent_base_types():
  59. class R(PRecord):
  60. x = field()
  61. result = thaw(R(x=1))
  62. assert result == {'x': 1}
  63. assert type(result) is dict
  64. def test_mutant_decorator():
  65. @mutant
  66. def fn(a_list, a_dict):
  67. assert a_list == v(1, 2, 3)
  68. assert isinstance(a_dict, type(m()))
  69. assert a_dict == {'a': 5}
  70. return [1, 2, 3], {'a': 3}
  71. pv, pm = fn([1, 2, 3], a_dict={'a': 5})
  72. assert pv == v(1, 2, 3)
  73. assert pm == m(a=3)
  74. assert isinstance(pm, type(m()))