test_misc.py
1 import re 2 import string 3 import sys 4 import textwrap 5 6 import pytest 7 from IPython.lib.pretty import pretty 8 9 from galgebra.ga import lazy_dict, OrderedBiMap, GradedTuple 10 from galgebra._utils import cached_property 11 12 13 class TestOrderedBiMap: 14 15 def test_inverse(self): 16 d = OrderedBiMap([('one', 1), ('two', 2)]) 17 assert d.inverse == OrderedBiMap([(1, 'one'), (2, 'two')]) 18 assert d.inverse.inverse is d 19 20 def test_annotation(self): 21 # check that we can use this like a generic type 22 def foo() -> OrderedBiMap[str, int]: 23 pass 24 25 26 class TestCachedProperty: 27 28 def test_cache(self): 29 30 class X: 31 _val = 0 32 @cached_property 33 def val(self): 34 try: 35 return self._val 36 finally: 37 self._val += 1 38 39 # property is computed only when the cache is clear 40 x = X() 41 assert x.val == 0 42 assert x.val == 0 43 del x.val 44 assert x.val == 1 45 assert x.val == 1 46 del x.val 47 assert x.val == 2 48 assert x.val == 2 49 50 @pytest.mark.skipif( 51 sys.version_info < (3, 6), 52 reason='__set_name__ was not added until Python 3.6' 53 ) 54 def test_annotation(self): 55 class X: 56 @cached_property 57 def val(self) -> 'int': 58 pass 59 60 assert X.__annotations__['val'] == 'int' 61 62 63 class TestLazyDict: 64 65 def test_caching(self): 66 seen = [] 67 def f_value(k): 68 seen.append(k) 69 return len(seen) 70 71 l = lazy_dict({'a': 0}, f_value) 72 assert l['a'] == 0 73 assert len(seen) == 0 74 75 # should not call the function twice 76 assert l['b'] == 1 77 assert l['b'] == 1 78 79 assert l['c'] == 2 80 81 def test_repr(self): 82 l = lazy_dict({'1': 1}, int) 83 assert repr(l) == "lazy_dict({'1': 1}, f_value=<class 'int'>)" 84 85 # needs to be long enough to wrap 86 l = lazy_dict({string.ascii_lowercase: string.ascii_lowercase }, int) 87 assert pretty(l) == textwrap.dedent("""\ 88 lazy_dict({'abcdefghijklmnopqrstuvwxyz': 'abcdefghijklmnopqrstuvwxyz'}, 89 f_value=<class 'int'>)""") 90 91 92 class TestGradedTuple: 93 94 def test_basic(self): 95 t = GradedTuple(( 96 ([0],), 97 ([1], [1]), 98 ([2],), 99 )) 100 assert isinstance(t, tuple) 101 102 assert t.flat == ([0], [1], [1], [2]) 103 with pytest.raises(AttributeError): 104 t.flat = ()