假设我有一些python模块(application.py),它包含一些复杂的业务逻辑,并启用了多线程或多进程。例如,
application.py
from multiprocessing.pool import ThreadPool
class application:
def __init__(service):
self.service = service
def execute():
pool = ThreadPool(processes=2)
task1 = pool.apply_async(service.get, "1")
task2 = pool.apply_async(service.get, "2")
if task1.successful() and task2.successful():
return True
test_application.py(我在单元测试中使用mockito库)
class test_application(Unittest.TestCase):
def test_execute():
service = mock()
when(service).get(ANY()).thenReturn(200)
fakeApplication = application(service=service)
status = fakeApplication.execute()
self.assertEquals(True, stautus)
如果task1.successful()和task2.successful():
,我发现测试用例在行中失败了Failure
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py", line 59, in testPartExecutor
yield
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py", line 605, in run
testMethod()
File "/ENV/lib/python3.6/site-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
File "TransactionTest.py", line 69, in test_create_transaction_TT
actual = application.execute()
File "/Transaction.py", line 45, in start_transaction
if task1.successful() and task2.successful():
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 631, in successful
assert self.ready()
AssertionError
我认为单元测试调用的execute()方法实际上并没有创建ThreadPool功能。
一些问题: - unittest不使用python的线程池库吗? - 如何在不重写代码的情况下对application.py进行单元测试? - 用于多线程测试的任何现有python模块?