79113314

Date: 2024-10-22 09:28:23
Score: 1
Natty:
Report link

Similar to the third bullet-point mentioned by Anoop, but a bit more thorough and based on an answer from a different post: https://stackoverflow.com/a/45304063

You can do the following, using a pytest fixture:

@pytest.fixture()
def mod_fixture():
    import sys
    del sys.modules['mod']
    import mod
    return mod

Subsequently, use in your tests as such:

def test_set_x(mod_fixture):
    mod_fixture.global_setter()
    assert mod_fixture.x == 123
def test_get_x(mod_fixture):
    with pytest.raises(NameError):
        mod_fixture.global_getter()

This will ensure that you get a fresh mod module with a clean state each time the fixture is used. If you like, you can change the scope of the fixture such that it doesn't necessarily reset per function, but per module: https://docs.pytest.org/en/6.2.x/fixture.html#fixture-scopes

Reasons:
  • Blacklisted phrase (1): stackoverflow
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Archer