Running tests on the output of Jupyter Notebook cells

Viewed 483

I am using Jupyter Notebook or Jupyter Lab for teaching the basics of Python.

Is it possible to run tests on previous cell's standard output without suppressing the output of a cell?

Magics %%capture with standard config redirects stdout. I'd like to be able to still see the output of the cell before running the tests.

e.g.

[cell 1] >> print('Hello, world!')
Hello, world!

Testing cell:

[cell 2] >>  if (cell1.stdout == 'Hello, world!'):
         ...    print('Success!')
         ... else:
         ...    print('Tests failed')
1 Answers

That is pretty simple, just wrap the %%capture magic with a custom function showing the captured output:

from IPython.core import magic

@magic.register_cell_magic
def non_suppressing_capture(variable, cell):
    get_ipython().magics_manager.magics['cell']['capture'](variable, cell)
    globals()[variable].show()

and (after execution of the above code) use it like this:

%%non_suppressing_capture cell1
print('Hello, world!')

Actually, your test will fail unless you add a new line character of the test string:

if cell1.stdout == 'Hello, world!\n':
    print('Success!')
else:
    print('Tests failed')

IPython magic is a powerful tool. You can find more advanced examples in documentation, see: defining custom magics chapter and API docs: core.magic, core.magic_arguments.

Related