【问题标题】:Correctly Patching a method in pytest when Module is already patched已修补模块时正确修补 pytest 中的方法
【发布时间】:2020-10-28 20:31:03
【问题描述】:

我们有一个测试夹具,可以修补两个类,如下所示。

@pytest.fixture
def license_fixture(mocker):
    
    mocker.patch('api.license_api.UserLicense')
    mocker.patch('api.license_api.UserLicense.userrole', return_value = 'admin') # doesn't work.
    l_mock = mocker.patch('api.license_api.LicenseContent')
    yield l_mock

LicenseContent 为许可内容的 api 调用提供服务并使用 UserLicense。

UserLicense 是第三方导入的许可证用户(使用加密)检查并服务于三个目的。

  1. 检查许可证验证的所有加密方法。
  2. 如果用户通过方法 isvalid() 获得有效许可
  3. 通过方法userrole()设置用户的正确授权

通过修补 UserLicense 我可以测试 isvalid,但是当我尝试修补方法以获取用户角色时,它不会将方法的返回值设置为管理员并且测试失败。

修补方法的正确方法是什么?

【问题讨论】:

  • 这是什么目的:mocker.patch('api.license_api.UserLicense')?除了导致错误之外,它什么都不做。
  • 它实际上是在模拟整个班级。

标签: pytest pytest-mock


【解决方案1】:

您可以修补模拟对象的return_value

@pytest.fixture
def license_fixture(mocker):
    
    user_license = mocker.patch('api.license_api.UserLicense')
    user_license.return_value.userrole.return_value = 'admin'
    l_mock = mocker.patch('api.license_api.LicenseContent')
    yield l_mock

userrole 是一个实例方法,所以它是在UserLicense 的实例上调用的,而不是类本身。实例是调用类的返回值。因此,您需要在修补时牢记这一点。

取自answer

类似问题:

【讨论】:

    猜你喜欢
    • 2021-09-03
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    相关资源
    最近更新 更多