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

标签 python django multithreading unit-testing

在 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/

相关文章:

python - 在条件列表理解中使用 or 语句来过滤数据框中的列

python - 在 QStandardItem 中重载了 "<"运算符,但它没有被调用

python - 如何在 Python 中识别 ARIMA 模型的 p(滞后阶数)

python - telegram-python-bot ImportError No module named 'cryptography' Alpine Docker

django - 如何在 django 模板中重复 "block"

django - 获取 <django.db.models.query_utils.DeferredAttribute object at 0x1069ce0d0> 而不是值

ios - 混淆线程和队列之间的技术术语

c++ - 线程构建 block 生成嵌套任务

sql - 从 Django 数据库中检索最近 10 个项目的更好方法

android - 等待信号量循环时的 SystemClock.sleep() 与 Thread.sleep()