5

In pytest we can define a session-scoped fixture, so the following

@pytest.fixture(scope="session", autouse=True)
def some_fixt():
   ... some setup procedure ...
   yield
   ... some cleanup procedure ...

will automagically set things up before testing session begins, and clean things up afterwards.

Is there something similar in unittest? The best I can find is setUpModule+tearDownModule, but that's just per-module, necessitating copy-paste among different testing modules.


EDIT: This is my current workaround:

For each and every Test Module:

from contextlib import ExitStack
...


ModuleResources = ExitStack()

def setUpModule():
    # For funcs/objects that can act as a context_manager
    ModuleResources.enter_context(
        ... something that can act as a context_manager ...
    )
    # For funcs/objects that cannot act as a context manager,
    # but has a "cleanup" method such as "stop" or "close"
    ... invoke setup ...
    ModuleResources.callback(thing.cleanup)


def tearDownModule():
    ModuleResources.close()

The problem is, of course, I have to paste all those code for each and every test module. So I'm looking for something simpler here.

pepoluan
  • 6,132
  • 4
  • 46
  • 76
  • I am not familiar with `python-unittest`, however, you likely can just define your own context manager to accomplish this. I googled, "python-unittest context manager" and found this: https://stackoverflow.com/questions/8416208/in-python-is-there-a-good-idiom-for-using-context-managers-in-setup-teardown – Tim Dec 01 '20 at 07:17
  • @Tim the example does setup & teardown per each test case, though. Something I don't want to do. As to the context manager, it's quite easy since I use `contextlib.ExitStack`. – pepoluan Dec 01 '20 at 08:41
  • @Tim I've edited my question to show my current, unsatisfactory implementation. – pepoluan Dec 01 '20 at 08:48
  • I see. Well, if you don't want a per module fixture, then you could do the context manager in whatever calls the main set of tests? Like, make a wrapper for your tests suite? – Tim Dec 01 '20 at 08:48

0 Answers0