Hello, I can recommend both Bruno's and Florian's approaches as being good practice :)
Cheers, Floris On Thu 07 Jan 2021 at 18:11 +0100, Florian Bruhin wrote: > Hey, > > On Wed, Jan 06, 2021 at 03:26:08PM -0300, Bruno Oliveira wrote: >> What I suggest you do in your case is to decouple your code from the >> fixture, so if you have something like this today: >> >> [setup / teardown in a fixture] >> >> You can write instead: >> >> @contextmanager >> def handle_work_reqs(): >> # [setup] >> try: >> yield x # some result >> finally: >> # [teardown] >> >> @pytest.fixture(scope="module") >> def my_work_reqs(): >> with handle_work_reqs() as x: >> yield x > > Perhaps it's just as obvious (at least in hindsight), but explicit is > better as implicit: > > Another thing I often do is return some kind of custom class from the > fixture, which tests can use - let's say we have: > > class JSTester: > > def __init__(self, qtbot): > self.qtbot = qtbot # a fixture needed in the class > > def run(self, source): > # ... > > # [some other methods tests can use] > > @pytest.fixture > def js_tester(qtbot): > return JSTester(qtbot) > > So that the tests can do things like: > > def test_simple_js(js_tester): > js_tester.run('1 + 1') > > If there was some teardown to do here, I'd just add a "cleanup" method > to that class, and call that in the fixture. > > If, for some reason, you have some more complex scenario and want to > test it inside pytest rather than isolated from it, another possibility > is the pytester fixture (called testdir in earlier releases): > > https://docs.pytest.org/en/latest/writing_plugins.html#testing-plugins > https://docs.pytest.org/en/latest/reference.html#std-fixture-pytester > > Florian _______________________________________________ pytest-dev mailing list pytest-dev@python.org https://mail.python.org/mailman/listinfo/pytest-dev