|
19 | 19 | from time import sleep |
20 | 20 | from threading import Thread |
21 | 21 | from unittest import TestCase, mock |
| 22 | +import nbformat |
22 | 23 |
|
23 | 24 | import pytest |
24 | 25 |
|
@@ -914,6 +915,53 @@ def test_notebook_export_json(): |
914 | 915 | _ip.run_line_magic("notebook", "%s" % outfile) |
915 | 916 |
|
916 | 917 |
|
| 918 | +def test_notebook_export_json_with_display_and_error(): |
| 919 | + pytest.importorskip("nbformat") |
| 920 | + _ip = get_ipython() |
| 921 | + _ip.history_manager.reset() |
| 922 | + _ip.history_manager.exceptions.clear() |
| 923 | + _ip.history_manager.output_mime_bundles.clear() |
| 924 | + |
| 925 | + cmds = ["1/0", "display('test')"] |
| 926 | + for i, cmd in enumerate(cmds, start=1): |
| 927 | + _ip.history_manager.store_inputs(i, cmd) |
| 928 | + try: |
| 929 | + exec(cmd) |
| 930 | + except Exception as exc: |
| 931 | + formatted_exc = _ip._format_exception_for_storage(exc) |
| 932 | + _ip.history_manager.exceptions[i] = formatted_exc |
| 933 | + if cmd.startswith("display("): |
| 934 | + _ip.history_manager.output_mime_bundles[i] = {"text/plain": "test"} |
| 935 | + |
| 936 | + with TemporaryDirectory() as td: |
| 937 | + outfile = os.path.join(td, "nb.ipynb") |
| 938 | + _ip.run_line_magic("notebook", outfile) |
| 939 | + with open(outfile, "r", encoding="utf-8") as f: |
| 940 | + nb = nbformat.read(f, as_version=4) |
| 941 | + |
| 942 | + error_found = False |
| 943 | + for cell in nb.get("cells", []): |
| 944 | + if cell.get("cell_type") == "code": |
| 945 | + for output in cell.get("outputs", []): |
| 946 | + if output.get("output_type") == "error": |
| 947 | + error_found = True |
| 948 | + expected_ename = _ip.history_manager.exceptions[1]["ename"] |
| 949 | + assert expected_ename in output.get("ename", "") |
| 950 | + assert error_found, "Notebook export did not include the expected error output." |
| 951 | + |
| 952 | + # Verify that the display cell output is 'test' |
| 953 | + for cell in nb.get("cells", []): |
| 954 | + if cell.get("source", "").strip() == "display('test')": |
| 955 | + for output in cell.get("outputs", []): |
| 956 | + if output.get("output_type") in ("display_data", "execute_result"): |
| 957 | + data = output.get("data", {}) |
| 958 | + text = data.get("text/plain", "").strip() |
| 959 | + assert text == "test", f"Expected 'test', got: {text}" |
| 960 | + elif output.get("output_type") == "stream": |
| 961 | + text = output.get("text", "").strip() |
| 962 | + assert text == "test", f"Expected 'test', got: {text}" |
| 963 | + |
| 964 | + |
917 | 965 | class TestEnv(TestCase): |
918 | 966 |
|
919 | 967 | def test_env(self): |
|
0 commit comments