BadAtTesting123
BadAtTesting123

Reputation: 11

monkeypatching not carrying through class import

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

And this raises ConnectionError. If I change

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

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?

Upvotes: 1

Views: 657

Answers (1)

Pitirus
Pitirus

Reputation: 137

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

Upvotes: 1

Related Questions