How to make pytest ignore a class named TestSomething?

Viewed 596

I am working on a kind of test framework that happens to have classes named TestSomething of course. And I realized my tests are failing because pytest sees these classes as "something I need to instantiate and run!", as soon as imported. And this absolutely won't work.

import pytest
from package import TestSomethingClass

Is it possible to import such class from a pytest test file directly? Or should I indirectly use those via a fixture maybe?

The same problem applies to exceptions, as I would need to do something like

with pytest.raises(TestsSomethingError):
1 Answers

Explicitly Disable

You're able to allow pytest to ignore this specific class by virtue of it starting with the word Test, by setting the __test__ flag to False within your conflicting class

class TestSomethingClass(object):
    __test__ = False

    def test_class_something(self, object):
        pass

feature: https://github.com/pytest-dev/pytest/pull/1561


Configuration File

We could also change the convention completely in your pytest.ini file and ignore all class names which start the word Example. But I don't advice this, as we could potentially encounter unintended consequences down the road.

#pytest.ini file
[pytest]
python_classes = !Example

Pytest Conventions

  • test prefixed test functions or methods outside of class

  • test prefixed test functions or methods inside Test prefixed test classes (without an init method)

Source: https://docs.pytest.org/en/stable/customize.html

Related