首页 > 解决方案 > 在多线程上下文中模拟

问题描述

我想为一些在多线程上下文中启动的类编写一些集成测试。问题是其中一个类有一些我想模拟的外部库。

例子:

foo.py

import threading

from external_lib import function_i_want_to_mock


class Foo(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        print(self.run_function())

    def run_function(self):
        return function_i_want_to_mock()

巴.py

import threading

from foo import Foo


class Bar(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        foo = Foo()
        foo.start()

test_mock_thread.py

from unittest.mock import patch

from bar import Bar


def test_run():
    with patch("foo.function_i_want_to_mock"):
        bar = Bar()
        bar.start()
        bar.join()


if __name__ == '__main__':
    test_run()

当我运行此测试时,该函数不会被模拟并且它正在正常导入。有没有办法通过线程传递模拟版本?

标签: pythonpython-3.xmultithreadingmocking

解决方案


推荐阅读