Multi-thread testing in Pyramid

If you want to do multi-thread testing in Pyramid, it probably won’t work the first time because request and registry are thread local, and things like get_renderer will call get_current_registry. When it happens in a thread, it won’t get the same value as it would have in the main thread.

So, here is a hack to address this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import pyramid.threadlocal
from threading import Thread, Lock

candidates = [
(self._test1, ()),
(self._test2, ()),
(self._test3, ()),
]

def random_func(pyramid_thread_locals):
pyramid.threadlocal.manager.push(pyramid_thread_locals)
time.sleep(random.random()) # 0 ~ 1 sec
func, args = random.choice(candidates)
func(*args)

pyramid_thread_locals = pyramid.threadlocal.manager.get()
threads = [Thread(target=random_func, args=(pyramid_thread_locals, ),)
for i in range(100)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()

There is no guarantee that pyramid.threadlocal.manager will always be there. Even if it’s there, there’s no guarantee it can be used this way. So, this should only be considered as a temporary workaround.