Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions pybars/_compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -776,12 +776,12 @@ class Compiler:
"""

_handlebars = OMeta.makeGrammar(handlebars_grammar, {}, 'handlebars')
_builder = CodeBuilder()
_compiler = OMeta.makeGrammar(compile_grammar, {'builder': _builder})

def __init__(self):
self._helpers = {}
self.template_counter = 1
self._builder = CodeBuilder()
self._compiler = OMeta.makeGrammar(compile_grammar, {'builder': self._builder})

def _extract_word(self, source, position):
"""
Expand Down
32 changes: 32 additions & 0 deletions tests/test__compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
str_class = str

import sys
import threading

from unittest import TestCase

Expand Down Expand Up @@ -134,3 +135,34 @@ def test_compile_with_path(self):
# recompile and check that a new path is used
self.assertEqual(result, compiler.compile(template, path=path)(context))
self.assertTrue(sys.modules.get('pybars._templates._project_widgets_templates_1') is not None)

def test_distinct_compilers_are_thread_safe(self):
templates = [
(u"Hello {{name}}!", {'name': 'world'}, u"Hello world!"),
(u"{{#each items}}{{this}},{{/each}}",
{'items': [1, 2, 3]}, u"1,2,3,"),
(u"{{#if flag}}yes{{else}}no{{/if}}",
{'flag': True}, u"yes"),
(u"{{a.b.c}}", {'a': {'b': {'c': 'deep'}}}, u"deep"),
]

errors = []
barrier = threading.Barrier(8)

def worker():
try:
barrier.wait()
for _ in range(10):
for src, ctx, expected in templates:
fn = Compiler().compile(src)
self.assertEqual(expected, str_class(fn(ctx)))
except Exception as e:
errors.append(e)

threads = [threading.Thread(target=worker) for _ in range(8)]
for t in threads:
t.start()
for t in threads:
t.join()

self.assertEqual([], errors)