猴子补丁没有通过类导入 [英] monkeypatching not carrying through class import

查看:57
本文介绍了猴子补丁没有通过类导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 pytest 测试一些代码,并且需要更改某个模块中的函数.我的一个导入也导入了该函数,但是当我使用 monkeypatch 更改方法时,这会失败.这是我所拥有的:

I'm trying to test some code using pytest and need to change a function from some module. One of my imports also imports that function, but this is failing when I change the method using monkeypatch. Here is what I have:

util.py

def foo():
    raise ConnectionError  # simulate an error
    return 'bar'

something.py

from proj import util

need_this = util.foo()
print(need_this)

test_this.py

import pytest

@pytest.fixture(autouse=True)
def fix_foo(monkeypatch):
    monkeypatch.setattr('proj.something.util.foo', lambda: 'bar')

import proj.something

这会引发ConnectionError.如果我改变

test_this.py

import pytest

@pytest.fixture(autouse=True)
def fix_foo(monkeypatch):
    monkeypatch.setattr('proj.something.util.foo', lambda: 'bar')

def test_test():
    import proj.something

然后它以 monkeypatch 的方式导入,按预期工作.我已经阅读了 this 并尝试从中模拟我的测试,但这不起作用除非我在测试中导入.如果monkeypatch只是在测试文件中正常导入,为什么它什么都不做?

Then it imports with the monkeypatch working as expected. I've read though this and tried to model my testing from it, but that isn't working unless I import inside of a test. Why does the monkeypatch not do anything if it is just a normal import in the testing file?

推荐答案

那是因为夹具应用于测试函数而不是整个代码.autouse=True 属性只是说它应该在每个测试中使用

That is because the fixture is applied to the test function not the entire code. autouse=True attribute just says that it should be used in every test

这篇关于猴子补丁没有通过类导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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