Debian Codegraph @

tests/test_thread_safety.py

raw
1 """
2 JinjaX
3 Copyright (c) Juan-Pablo Scaletti <[email protected]>
4 """
5 from threading import Barrier, Event, Thread
6
7 from markupsafe import Markup
8
9 import jinjax
10
11
12 class ThreadWithReturnValue(Thread):
13 def __init__(self, group=None, target=None, name=None, args=None, kwargs=None):
14 args = args or ()
15 kwargs = kwargs or {}
16 Thread.__init__(
17 self,
18 group=group,
19 target=target,
20 name=name,
21 args=args,
22 kwargs=kwargs,
23 )
24 self._target = target
25 self._args = args
26 self._kwargs = kwargs
27 self._return = None
28
29 def run(self):
30 if self._target is not None:
31 self._return = self._target(*self._args, **self._kwargs)
32
33 def join(self, *args, **kwargs):
34 Thread.join(self, *args, **kwargs)
35 return self._return
36
37
38 def test_thread_safety_of_render_assets(catalog, folder):
39 NUM_THREADS = 5
40
41 child_tmpl = """
42 {#css "c{i}.css" #}
43 {#js "c{i}.js" #}
44 <p>Child {i}</p>""".strip()
45
46 parent_tmpl = """
47 {{ catalog.render_assets() }}
48 {{ content }}""".strip()
49
50 comp_tmpl = """
51 {#css "a{i}.css", "b{i}.css" #}
52 {#js "a{i}.js", "b{i}.js" #}
53 <Parent{i}><Child{i} /></Parent{i}>""".strip()
54
55 expected_tmpl = """
56 <link rel="stylesheet" href="/static/components/a{i}.css">
57 <link rel="stylesheet" href="/static/components/b{i}.css">
58 <link rel="stylesheet" href="/static/components/c{i}.css">
59 <script type="module" src="/static/components/a{i}.js"></script>
60 <script type="module" src="/static/components/b{i}.js"></script>
61 <script type="module" src="/static/components/c{i}.js"></script>
62 <p>Child {i}</p>""".strip()
63
64 def render(i):
65 return catalog.render(f"Page{i}")
66
67 for i in range(NUM_THREADS):
68 si = str(i)
69 child_name = f"Child{i}.jinja"
70 child_src = child_tmpl.replace("{i}", si)
71
72 parent_name = f"Parent{i}.jinja"
73 parent_src = parent_tmpl.replace("{i}", si)
74
75 comp_name = f"Page{i}.jinja"
76 comp_src = comp_tmpl.replace("{i}", si)
77
78 (folder / child_name).write_text(child_src)
79 (folder / comp_name).write_text(comp_src)
80 (folder / parent_name).write_text(parent_src)
81
82 threads = []
83
84 for i in range(NUM_THREADS):
85 thread = ThreadWithReturnValue(target=render, args=(i,))
86 threads.append(thread)
87 thread.start()
88
89 results = [thread.join() for thread in threads]
90
91 for i, result in enumerate(results):
92 expected = expected_tmpl.replace("{i}", str(i))
93 print(f"---- EXPECTED {i}----")
94 print(expected)
95 print(f"---- RESULT {i}----")
96 print(result)
97 assert result == Markup(expected)
98
99
100 def test_same_thread_assets_independence(catalog, folder):
101 catalog2 = jinjax.Catalog()
102 catalog2.add_folder(folder)
103
104 print("Catalog1 key:", catalog._key)
105 print("Catalog2 key:", catalog2._key)
106
107 # Check if the context variables exist before the test
108 print("Before any rendering:")
109 print("Catalog1 in collected_css:", catalog._key in jinjax.catalog.collected_css)
110 print("Catalog2 in collected_css:", catalog2._key in jinjax.catalog.collected_css)
111 print("collected_css keys:", list(jinjax.catalog.collected_css.keys()))
112 print("collected_js keys:", list(jinjax.catalog.collected_js.keys()))
113
114 (folder / "Parent.jinja").write_text(
115 """
116 {{ catalog.render_assets() }}
117 {{ content }}""".strip()
118 )
119
120 (folder / "Comp1.jinja").write_text(
121 """
122 {#css "a.css" #}
123 {#js "a.js" #}
124 <Parent />""".strip()
125 )
126
127 (folder / "Comp2.jinja").write_text(
128 """
129 {#css "b.css" #}
130 {#js "b.js" #}
131 <Parent />""".strip()
132 )
133
134 expected_1 = """
135 <link rel="stylesheet" href="/static/components/a.css">
136 <script type="module" src="/static/components/a.js"></script>""".strip()
137
138 expected_2 = """
139 <link rel="stylesheet" href="/static/components/b.css">
140 <script type="module" src="/static/components/b.js"></script>""".strip()
141
142 # Render first component with first catalog
143 html1 = catalog.render("Comp1")
144
145 # Check context variables after first render
146 print("\nAfter first render:")
147 print("Catalog1 collected_css:", catalog.collected_css)
148 print("Catalog2 collected_css:", catalog2.collected_css)
149 print("Catalog1 in collected_css:", catalog._key in jinjax.catalog.collected_css)
150 print("Catalog2 in collected_css:", catalog2._key in jinjax.catalog.collected_css)
151 print("collected_css keys:", list(jinjax.catalog.collected_css.keys()))
152
153 # Render second component with second catalog
154 html2 = catalog2.render("Comp2")
155
156 # Check context variables after second render
157 print("\nAfter second render:")
158 print("Catalog1 collected_css:", catalog.collected_css)
159 print("Catalog2 collected_css:", catalog2.collected_css)
160 print("Catalog1 in collected_css:", catalog._key in jinjax.catalog.collected_css)
161 print("Catalog2 in collected_css:", catalog2._key in jinjax.catalog.collected_css)
162 print("collected_css keys:", list(jinjax.catalog.collected_css.keys()))
163
164 print("\nHTML outputs:")
165 print("HTML1:", html1)
166 print("HTML2:", html2)
167
168 assert html1 == Markup(expected_1)
169 assert html2 == Markup(expected_2)
170
171
172 def test_thread_safety_of_template_globals(catalog, folder):
173 """Every thread must render its own globals, even when they all hold the
174 same cached component at the same time.
175
176 The globals are set and the component looked up *before* the barrier, so
177 all the threads sit between the lookup and the render simultaneously. That
178 is the window in which a shared template would end up with the globals of
179 whichever thread happened to be the last one.
180 """
181 NUM_THREADS = 5
182 (folder / "Page.jinja").write_text("{{ globalvar }}")
183
184 # Warm the cache, so all the threads get the same compiled template
185 assert catalog.render("Page", _globals={"globalvar": "warmup"}) == Markup("warmup")
186
187 barrier = Barrier(NUM_THREADS, timeout=5)
188
189 def render(i):
190 catalog.tmpl_globals = {"globalvar": i}
191 component = catalog._get_component("Page")
192 barrier.wait()
193 return component.render()
194
195 threads = []
196
197 for i in range(NUM_THREADS):
198 thread = ThreadWithReturnValue(target=render, args=(i,))
199 threads.append(thread)
200 thread.start()
201
202 results = [thread.join() for thread in threads]
203
204 for i, result in enumerate(results):
205 assert result == Markup(str(i))
206
207
208 def test_cached_template_globals_are_not_shared_between_threads(catalog, folder):
209 """A render must not emit the globals of another request that used the
210 same cached component in the meantime."""
211 (folder / "Page.jinja").write_text("<p>{{ user }}</p>")
212
213 # Warm the cache, so both threads get the same compiled template
214 assert catalog.render("Page", _globals={"user": "warmup"}) == Markup("<p>warmup</p>")
215
216 got_component = Event()
217 other_finished = Event()
218 results = {}
219
220 def first():
221 catalog.tmpl_globals = {"user": "first"}
222 component = catalog._get_component("Page")
223 # Let another request render the same component before this one does
224 got_component.set()
225 other_finished.wait(timeout=5)
226 results["first"] = component.render()
227
228 def second():
229 got_component.wait(timeout=5)
230 results["second"] = catalog.render("Page", _globals={"user": "second"})
231 other_finished.set()
232
233 threads = [Thread(target=first), Thread(target=second)]
234 for thread in threads:
235 thread.start()
236 for thread in threads:
237 thread.join()
238
239 assert results["first"] == Markup("<p>first</p>")
240 assert results["second"] == Markup("<p>second</p>")
241
242
243 def test_render_globals_are_not_stored_in_the_shared_cache(catalog, folder):
244 (folder / "Page.jinja").write_text("<p>{{ user }}</p>")
245 assert catalog.render("Page", _globals={"user": "secret"}) == Markup("<p>secret</p>")
246
247 assert catalog._cache
248 for cache in catalog._cache.values():
249 assert "tmpl_globals" not in cache
250 assert "user" not in cache["tmpl"].globals