1

I have some pytests that all access a fixture whose scope is module. I want to move the duplicated parts of the tests into a common place and access it from there.

Specifically, in the below sample code, in test/test_blah.py each of the test methods has the variable dsn, which is the device under test's serial number. I couldn't figure out how to extract this common code out. I tried accessing the dut in TestBase, but couldn't make it work.

# my_pytest/__init__.py

import pytest

@pytest.fixture(scope="module")
def device_fixture(request):
    config = getattr(request.module, 'config', {})
    device = get_device(config.get('dsn'))
    assert device is not None
    return device

...some other code...

# test/base.py

class TestBase:
    def common_method_1(self):
        pass

    def common_method_2(self):
        pass

# test/test_blah.py

from base import TestBase
import my_pytest
from my_pytest import device_fixture as dut  #'dut' stands for 'device under test'

class TestBlah(TestBase):
    def test_001(self, dut):
        dsn = dut.get_serialno()
        ...
        # how to extract the dsn = dut.get_serialno() into
        # something common so I can keep these tests more DRY?


    def test_002(self, dut):
        dsn = dut.get_serialno()
        ...

    def test_003(self, dut):
        dsn = dut.get_serialno()
        ...
user1002119
  • 3,692
  • 4
  • 27
  • 30
  • You say you "couldn't make it work" - what problems did you encounter, specifically? – jwd Jan 23 '17 at 21:50
  • See also: http://stackoverflow.com/questions/33508060/create-and-import-helper-functions-in-tests-without-creating-packages-in-test-di – jwd Jan 24 '17 at 19:37

1 Answers1

2

If I understand your question correctly: Put your fixtures in conftest.py and they will be available to use as arguments for your test functions. No need to import anything, you just define

@pytest.fixture(scope='module')
def dut():
    return 'something'
instant
  • 676
  • 6
  • 12