vendredi 27 mars 2020

python; monkeypatch in pytest setup_module

My question is similar to but is not a duplicate of: How to use monkeypatch in a "setup" method for unit tests using pytest?. That OP is not using pytest setup_module

So pytest provides setup_module and teardown_module (doc: https://docs.pytest.org/en/latest/xunit_setup.html#module-level-setup-teardown). However, they don't seem to take pytest fixtures.

I have to monkeypatch an object for multiple tests; it has to be patched, "started", then used in a bunch of tests, then stopped. It is not really a use case for fixtures since it's a multithreaded application and we are testing against the running application.

Right now, I am doing a series of tests that cannot be run in parallel because all are dependent on the first test, in effort to hackaround setup_module:

def test_1_must_come_first(monkeypatch, somefixture...):
    # patch my thing
    monkeypatch.setattr("mything.init_func", somefixture)
    mything.start()

def test_2()
    # use mything

def test_3()
    # use mything

...

def teardown_module():
    mything.stop()    

What I would like instead is to move the patching in the first step so that the tests themselves can be run in parallel and not dependent:

def setup_module(monkeypatch, somefixture):
    monkeypatch.setattr("mything.init_func", somefixture)
    mything.start()

def test_1():
    # use mything

def test_2()
    # use mything

# NO LONGER AN ORDERING DEPENDENCY AMONG TESTS
...

def teardown_module():
    mything.stop()

Is there a way to achieve this?

Aucun commentaire:

Enregistrer un commentaire