pytest_notebook.ipy_magic module#

Module to provide an IPython magic for running pytest.

Load via: %load_ext pytest_notebook.ipy_magic, then %pytest and %%pytest can be accessed.

pytest_notebook.ipy_magic.eval_literals(literals: List[str], local_ns: dict | None) List[Tuple[str, str]][source]#

Evaluate and yield literal items.

pytest_notebook.ipy_magic.load_ipython_extension(ipython)[source]#

Load the ipython magic, when the module is called via %load_ext.

pytest_notebook.ipy_magic.parse_cell_content(cell: str | None) Tuple[List[str], List[str], List[str]][source]#

Parse the cell contents.

Returns:

(test_content, config_content, literals_content)

pytest_notebook.ipy_magic.pytest(line: str = '', cell: str | None = None, local_ns: dict | None = None)[source]#

Run pytest.

%pytest arg1 arg2 ... will run pytest in a temporary directory.

%%pytest arg1 arg2 ... will additionally write the cell contents to a test module in the temporary directory.

The cell content can optionally contain a fenced sections:

  • ---: lines extracted and written as pytest.ini

  • ***: each line should be able to be evaluated as a tuple of two strings, (file_content, file_name), that will be written to the temporary directory. Any variables in the notebook scope can be used in these expressions.

Example:

%%pytest -v

---
[pytest]
adopts = --disable-warning
---

***
(content_string, "test_other.py")
***

def test_something():
    assert True

Note: to change output width, se the ‘COLUMNS’ environmental variable:

import os
os.environ["COLUMNS"] = "80"
pytest_notebook.ipy_magic.run_pytest(args: List[str], cwd: str | Path | None = None)[source]#

Run pytest, with live output.

Adapted from https://stackoverflow.com/a/18422264/5033292

Note: originally this used pytest.main to run pytest, however, there was issues with multiple calls to it (see: https://docs.pytest.org/en/latest/usage.html#calling-pytest-from-python-code).

pytest_notebook.ipy_magic.write_file(content: List[str], file_name: str, temp_dir: str | Path)[source]#

Write file to the temp_dir.