gpt4 book ai didi

Python 测试 - 重置所有模拟?

转载 作者:太空狗 更新时间:2023-10-30 01:07:09 27 4
gpt4 key购买 nike

当使用 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/

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