gpt4 book ai didi

python - 在多线程上下文中模拟以在 Python 中进行测试

转载 作者:太空宇宙 更新时间:2023-11-03 15:08:31 25 4
gpt4 key购买 nike

在 Django 项目中,我想为在多处理上下文 (Processing.create_all_files) 中使用的函数编写测试。如果我使用的是单线程,我会进行“模拟”以检查用于调用给定函数(在我的例子中是 FileCreator.create)的参数。

但是,一旦 FileCreator.create 函数被 multiprocessing.Pool 调用,mock 就不再适用了。

我应该如何测试 create_all_files?谢谢。

test_program.py:

def test_create_all_files(self):
file_paths = [ (...) ] # Initialize file_paths
processing = Processing()
with mock.patch('FileCreator.create', return_value=True) as create:
with mock.patch('os.path.isfile', return_value=False):
processing.create_all_files()
calls = create.call_args_list

for file_path in file_paths:
self.assertTrue(((file_path),) in calls)


program.py

def unwrap_self_create_one_file(arg):
return Processing.process_one_file(*arg)

class Processing:
(...)

def create_one_file(self, file_path):
if os.path.isfile(file_path):
FileCreator.create(file_path) # CREATE FILE

def create_all_files(file_paths):
(...) # define args_lst considering file_paths
ncpus = 4
pool = multiprocessing.Pool(ncpus)
pool.map(unwrap_create_one_file, args_lst, chunksize=1)

最佳答案

添加多线程后,您冒着“补丁”超出范围的风险,换句话说,当在不同的线程上执行 FileCreator.create 时,with patch()语句已经结束。

关于python - 在多线程上下文中模拟以在 Python 中进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29965968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com