chmp / ipytest

Pytest in IPython notebooks.
MIT License
314 stars 17 forks source link

How to run doctest with cell magic command? #24

Closed tamuhey closed 4 years ago

tamuhey commented 5 years ago

Hi, thanks for this great project!

I want to run doctest with cell magic, as follows:

%%run_pytest --doctest-modules
def foo(x):
    """
    >>> foo(2)
    4
    """
    return x*2

However, the output says no tests found:

============================= test session starts ==============================
platform darwin -- Python 3.6.9, pytest-5.0.1, py-1.8.0, pluggy-0.12.0
rootdir: /Users/yohei_tamura/work/men
collected 0 items

========================= no tests ran in 0.02 seconds =========================
chmp commented 5 years ago

Thanks for the feedback and brining this issue up. First, you're right atm I can't think of way to run doctests with pytest and ipytest. I had a quick look into how that part of the code is implemented and fixing it does not seem to be easy.

Maybe as a short-time solution, the non-pytest way to execute doc tests should work:

import doctest
doctest.testmod()
chmp commented 4 years ago

Documenting the "solution" for myself, while pondering, whether this hack is a good idea:

def _run_impl(*args, module, filename, plugins, return_exit_code):
    ...

    with _valid_filename(filename, module) as valid_filename:
        import sys, pathlib
        p = pathlib.Path(valid_filename)
        sys.modules[p.stem] = module
        module.__file__ = str(p.with_suffix(".py"))

        ...

The reason this works:

Remarks:

chmp commented 4 years ago

I added a new config option register_module if set to True doctests will work as expected:

import ipytest
ipytest.autoconfig(register_module=True)

%%run_pytest --doctest-modules
def foo(x):
    """
    >>> foo(2)
    4
    """
    return x*2

This functionality will be released with the 0.9.0.