Python 测试 - 重置所有模拟? [英] Python Testing - Reset all mocks?

查看:81
本文介绍了Python 测试 - 重置所有模拟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When doing unit-testing with Python / PyTest, if you do you not have patch decorators or with patch blocks throughout your code, is there a way to reset all mocks at the end of every file / module to avoid inter-file test pollution?

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

It seems like something that is mocked in one Python test file remains mocked in other file with the same return value, which means my mocks are persisting between tests and files (when a patch decorator or with patch block is NOT used).

除了打补丁之外还有什么办法可以解决这个问题吗?不会碰巧有 mock.reset_all_mocks() 或类似的东西,是吗?

Is there any way around this other than patching? There wouldn't happen to be a mock.reset_all_mocks() or something like that, would there?

推荐答案

我最终做的是使用 pytest-mock 库.根据自述文件:

What I ended up doing was using the pytest-mock library. According to the Readme:

这个插件安装了一个模拟装置,它是一个薄包装由优秀的模拟包提供的补丁 API,但带有不必担心在结束时撤消补丁的好处测试.(强调.)

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 使用,因此如果您在一个测试中有多个模拟,或者您想在测试期间更改模拟,则此解决方案可以很好地扩展.

So now I can do: mocker.patch.object(module, 'method', return_value='hi'), and the patch will be removed at the end of the test. There is no need to use with any more so that this solution scales nicely if you have many mocks in one test or if you want to change mocks during the test.

这篇关于Python 测试 - 重置所有模拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆