[pytest-dev] Test discovery by subclassing

Bruno Oliveira nicoddemus at gmail.com
Tue Apr 19 07:22:31 EDT 2016


Hi Dave,

Using plain pytest that is currently not possible, and I’m not aware of any
plugin which allows this.

You can implement your own collection rules by implementing the
pytest_pycollect_makeitem
<http://pytest.org/latest/writing_plugins.html#_pytest.hookspec.pytest_pycollect_makeitem>
hook. I suggest taking a look at how pytest itself does it
<https://github.com/pytest-dev/pytest/blob/master/_pytest/python.py#L306>
to get some guidance, but I think this would be enough for your case:

# conftest.pyimport inspect
class X: pass
def pytest_pycollect_makeitem(collector, name, obj):
    if inspect.isclass(obj) and issubclass(obj, X):
        Class = collector._getcustomclass("Class")
        return Class(name, parent=collector)
# test_foo.pyfrom conftest import X
class Foo(X):
    def test_foo(self):
        pass

test_foo.py::Foo::test_foo PASSED

========================== 1 passed in 0.13 seconds ===========================

Cheers,
Bruno.
​

On Tue, Apr 19, 2016 at 7:46 AM Dave <dave.hirschfeld at gmail.com> wrote:

> Hi,
> Instead of discovering tests by name matching is there any way to specify
> that all subclasses of X be collected?
>
> I realise this can be done by subclassing unittest.TestCase but that is a)
> pretty heavyweight and b) seems to break parameterised fixtures for me.
>
>
> Thanks,
> Dave
>
>
> _______________________________________________
> pytest-dev mailing list
> pytest-dev at python.org
> https://mail.python.org/mailman/listinfo/pytest-dev
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/pytest-dev/attachments/20160419/19c4d8b7/attachment.html>


More information about the pytest-dev mailing list