Python 测试 - 重置所有模拟?

标签 python unit-testing testing mocking pytest

当使用 Python/PyTest 进行单元测试时,如果你没有补丁装饰器或 with patch block 贯穿你的代码,有没有办法在每个文件的末尾重置所有模拟/模块以避免文件间测试污染?

似乎在一个 Python 测试文件中被模拟的东西在另一个具有相同返回值的文件中仍然被模拟,这意味着我的模拟在测试和文件之间持续存在(当补丁装饰器或 with patch block 未使用)。

除了打补丁还有什么办法吗?不会碰巧有 mock.reset_all_mocks() 或类似的东西吧?

最佳答案

我最后做的是使用 pytest-mock图书馆。根据自述文件:

This plugin installs a mocker fixture which is a thin-wrapper around the patching API provided by the excellent mock package, but with the benefit of not having to worry about undoing patches at the end of a test. (Emphasis added.)

所以现在我可以这样做:mocker.patch.object(module, 'method', return_value='hi'),补丁将在测试结束时被移除。 无需再使用 with,这样如果您在一个测试中有很多 mock 或者如果您想在测试期间更改 mock,则此解决方案可以很好地扩展。

关于Python 测试 - 重置所有模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33051263/

相关文章:

python - OneToOne 关系和 django-autocomplete-light

python - 在golang中访问C数组

unit-testing - phpunit单元测试错误zf2教义

design-patterns - 使白盒测试更容易的编程设计模式?

django - 如何运行 Django 项目级测试?

python - Pytorch:为什么 `tensor`变量占用的内存这么小?

python - 将 pandas 中的正则表达式值转换为 0 或 1

angular - 如何在@ngrx/data 中对 EntityCollectionServiceBase 进行单元测试?

unit-testing - 去单元测试找不到所需的文件

javascript - 如何使用 Protractor 从网格中获取列数据?