Debian Codegraph @

tests/test_support_lazy_proxy.py

raw
1 import copy
2
3 import pytest
4
5 from babel import support
6
7
8 def test_proxy_caches_result_of_function_call():
9 counter = 0
10
11 def add_one():
12 nonlocal counter
13 counter += 1
14 return counter
15
16 proxy = support.LazyProxy(add_one)
17 assert proxy.value == 1
18 assert proxy.value == 1
19
20
21 def test_can_disable_proxy_cache():
22 counter = 0
23
24 def add_one():
25 nonlocal counter
26 counter += 1
27 return counter
28
29 proxy = support.LazyProxy(add_one, enable_cache=False)
30 assert proxy.value == 1
31 assert proxy.value == 2
32
33
34 @pytest.mark.parametrize(("copier", "expected_copy_value"), [
35 (copy.copy, 2),
36 (copy.deepcopy, 1),
37 ])
38 def test_can_copy_proxy(copier, expected_copy_value):
39 numbers = [1, 2]
40
41 def first(xs):
42 return xs[0]
43
44 proxy = support.LazyProxy(first, numbers)
45 proxy_copy = copier(proxy)
46
47 numbers.pop(0)
48 assert proxy.value == 2
49 assert proxy_copy.value == expected_copy_value
50
51
52 def test_handle_attribute_error():
53 def raise_attribute_error():
54 raise AttributeError('message')
55
56 proxy = support.LazyProxy(raise_attribute_error)
57 with pytest.raises(AttributeError, match='message'):
58 _ = proxy.value
59
60
61 def test_lazy_proxy():
62 def greeting(name='world'):
63 return f"Hello, {name}!"
64
65 lazy_greeting = support.LazyProxy(greeting, name='Joe')
66 assert str(lazy_greeting) == "Hello, Joe!"
67 assert ' ' + lazy_greeting == ' Hello, Joe!'
68 assert '(%s)' % lazy_greeting == '(Hello, Joe!)'
69 assert f"[{lazy_greeting}]" == "[Hello, Joe!]"
70
71 greetings = sorted([
72 support.LazyProxy(greeting, 'world'),
73 support.LazyProxy(greeting, 'Joe'),
74 support.LazyProxy(greeting, 'universe'),
75 ])
76 assert [str(g) for g in greetings] == [
77 "Hello, Joe!",
78 "Hello, universe!",
79 "Hello, world!",
80 ]