Skip to content
Advertisement

Tests being run from imported class

I have a base class with some tests similar to this:

class TestA:
    def test_something(self):
        data = self._generate_some_data()
        assert something_about_data

    def _generate_some_data(self)
        return some_data

And another class that reuses the testing logic within TestA but providing different data:

# This is the line that is giving me a problem
from somemodule import TestA

class TestB(TestA):
     def _generate_some_data(self)
        return some_other_data

Note that I am doing this and not simply creating another test in TestA because they each test a different class A and B (though the classes have the same interface)

The problem I am running into is, when importing TestA in the TestB module, the name is declared in the module’s namespace and therefore its found by pytest when searching for tests.

This results in TestA tests being run twice: one when its module is found and scanned, and another time when TestB module is scanned.

I have thought of two solutions:

  1. A simple work around: renaming TestA upon import so that it is not found by pytest scanning:
from somemodule import TestA as BaseTestA

class TestB(BaseTestA):
    ...
  1. I could extract the common logic to an abstract class whose name will not match pytest search, and that could be safely imported and inherited from by both test classes.

The first option, I do not like it, as it seems hacky. And regarding the second option, I would not really want to extract the logic to another class.

Is there another way to solve this problem that I am not seeing?

Advertisement

Answer

Just use:

import somemodule

class TestB(somemodule.TestA):
    ...
Advertisement