python - 在多线程上下文中模拟
问题描述
我想为一些在多线程上下文中启动的类编写一些集成测试。问题是其中一个类有一些我想模拟的外部库。
例子:
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()
当我运行此测试时,该函数不会被模拟并且它正在正常导入。有没有办法通过线程传递模拟版本?
解决方案
推荐阅读
- android - 在任务 transformDexArchiveWithExternalLibsDexMergerForDebug 期间会发生什么?什么时候重复类会导致dex失败?
- r - 将数据框中的字符串分类数据转换为数值数据
- node.js - 如何用mongodb树结构?
- ruby - 返回字符串中每组分隔符之间的字符
- r - 如何每隔五个元素分隔一个向量?
- node.js - 如何为 node.js 应用程序创建 ubuntu 的 Docker 映像
- c++ - c++ 中的 csv 文件管理(具体设置标题和每个标题将分别具有的值)
- r - Plotly R 与 ggplot2:在 geom_bar 中使用 coord_polar 使用 plotly
- android - 创建没有 gradle、ant 或 cmake 的仅 JNI/NDK apk 命令行
- python-3.x - Python脚本中的可执行文件无法写入文件