Tests if notebook export correctly captures outputs, errors, display outputs, and stream outputs.
()
| 1038 | |
| 1039 | |
| 1040 | def test_notebook_export_json_with_output(): |
| 1041 | """Tests if notebook export correctly captures outputs, errors, display outputs, and stream outputs.""" |
| 1042 | pytest.importorskip("nbformat") |
| 1043 | pytest.importorskip("nbclient") |
| 1044 | import nbformat |
| 1045 | from nbclient import NotebookClient |
| 1046 | |
| 1047 | _ip = get_ipython() |
| 1048 | _ip.history_manager.reset() |
| 1049 | _ip.colors = "neutral" |
| 1050 | _ip.execution_count = 1 |
| 1051 | |
| 1052 | try: |
| 1053 | commands = [ |
| 1054 | "1/0", |
| 1055 | "print('test')", |
| 1056 | "display('test')", |
| 1057 | "1+1", |
| 1058 | "display('a'), display('b')", |
| 1059 | "import sys\nprint('test', file=sys.stderr)", |
| 1060 | ] |
| 1061 | |
| 1062 | clean_nb = nbformat.v4.new_notebook( |
| 1063 | cells=[nbformat.v4.new_code_cell(source=cmd) for cmd in commands] |
| 1064 | ) |
| 1065 | |
| 1066 | with TemporaryDirectory() as td: |
| 1067 | outfile = os.path.join(td, "nb.ipynb") |
| 1068 | client = NotebookClient( |
| 1069 | clean_nb, |
| 1070 | timeout=600, |
| 1071 | kernel_name="python3", |
| 1072 | resources={"metadata": {"path": td}}, |
| 1073 | allow_errors=True, |
| 1074 | ) |
| 1075 | client.execute() |
| 1076 | nbformat.write(clean_nb, outfile) |
| 1077 | expected_nb = nbformat.read(outfile, as_version=4) |
| 1078 | |
| 1079 | for cmd in commands: |
| 1080 | _ip.run_cell(cmd, store_history=True, silent=False) |
| 1081 | print(f"\n{_ip.history_manager.outputs}\n") |
| 1082 | |
| 1083 | with TemporaryDirectory() as td: |
| 1084 | outfile = os.path.join(td, "nb.ipynb") |
| 1085 | _ip.run_cell(f"%notebook {outfile}", store_history=True) |
| 1086 | sleep(2) |
| 1087 | actual_nb = nbformat.read(outfile, as_version=4) |
| 1088 | |
| 1089 | assert len(actual_nb["cells"]) == len(commands) |
| 1090 | assert len(expected_nb["cells"]) == len(commands) |
| 1091 | |
| 1092 | for i, command in enumerate(commands): |
| 1093 | actual = actual_nb["cells"][i] |
| 1094 | expected = expected_nb["cells"][i] |
| 1095 | assert expected["source"] == command |
| 1096 | assert actual["source"] == expected["source"] |
| 1097 | _strip_ansi = re.compile(r"\x1b\[[0-9;]*m").sub |
nothing calls this directly
no test coverage detected
searching dependent graphs…