【发布时间】:2016-09-05 13:53:25
【问题描述】:
Mock.call_count 似乎无法与线程一起正常工作。例如:
import threading
import time
from mock import MagicMock
def f():
time.sleep(0.1)
def test_1():
mock = MagicMock(side_effect=f)
nb_threads = 100000
threads = []
for _ in range(nb_threads):
thread = threading.Thread(target=mock)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
assert mock.call_count == nb_threads, mock.call_count
test_1()
此代码产生以下输出:
Traceback (most recent call last):
File "test1.py", line 24, in <module>
test_1()
File "test1.py", line 21, in test_1
assert mock.call_count == nb_threads, mock.call_count
AssertionError: 99994
有没有办法可以在代码的多线程部分中使用call_count(或类似的)?我想避免自己重写 MagicMock...
【问题讨论】:
标签: python multithreading unit-testing mocking