如何用python编写多线程代码的单元测试

2024-06-02 08:51:37 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个python模块(应用程序.py)支持多线程或多进程的一些复杂业务逻辑。例如

在应用程序.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

试验_应用程序.py(我在unittest中使用mockito库)

^{pr2}$

我发现,如果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()方法实际上并没有创建线程池功能。在

一些问题: -unittest没有使用python的线程池库吗? -我应该如何对应用程序.py不重写代码? -有没有用于多线程测试的现有python模块?在


Tags: inpy应用程序executelibservicelinelibrary