From 0511b578447a694172a43d4e98edf57191ab2fac Mon Sep 17 00:00:00 2001 From: Bahram Farahmand Date: Thu, 3 Apr 2025 13:41:23 +0300 Subject: [PATCH] Add note on using mixin classes for abstract test classes in documentation --- changelog/8612.doc.rst | 5 +++++ doc/en/example/pythoncollection.rst | 27 +++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 changelog/8612.doc.rst diff --git a/changelog/8612.doc.rst b/changelog/8612.doc.rst new file mode 100644 index 00000000000..6ab4102ace4 --- /dev/null +++ b/changelog/8612.doc.rst @@ -0,0 +1,5 @@ +Add a recipe for handling abstract test classes in the documentation. + +A new example has been added to the documentation to demonstrate how to use a mixin class to handle abstract +test classes without manually setting the ``__test__`` attribute for subclasses. +This ensures that subclasses of abstract test classes are automatically collected by pytest. diff --git a/doc/en/example/pythoncollection.rst b/doc/en/example/pythoncollection.rst index 89d7ee42614..6a3b143d580 100644 --- a/doc/en/example/pythoncollection.rst +++ b/doc/en/example/pythoncollection.rst @@ -325,3 +325,30 @@ with ``Test`` by setting a boolean ``__test__`` attribute to ``False``. # Will not be discovered as a test class TestClass: __test__ = False + +.. note:: + + If you are working with abstract test classes and want to avoid manually setting + the ``__test__`` attribute for subclasses, you can use a mixin class to handle + this automatically. For example: + + .. code-block:: python + + # Mixin to handle abstract test classes + class NotATest: + def __init_subclass__(cls): + cls.__test__ = NotATest not in cls.__bases__ + + + # Abstract test class + class AbstractTest(NotATest): + pass + + + # Subclass that will be collected as a test + class RealTest(AbstractTest): + def test_example(self): + assert 1 + 1 == 2 + + This approach ensures that subclasses of abstract test classes are automatically + collected without needing to explicitly set the ``__test__`` attribute.