Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit fe26455

Browse files
committed
add-test-for-display-and-error
1 parent db746f2 commit fe26455

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

tests/test_magic.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from time import sleep
2020
from threading import Thread
2121
from unittest import TestCase, mock
22+
import nbformat
2223

2324
import pytest
2425

@@ -914,6 +915,53 @@ def test_notebook_export_json():
914915
_ip.run_line_magic("notebook", "%s" % outfile)
915916

916917

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+
917965
class TestEnv(TestCase):
918966

919967
def test_env(self):

0 commit comments

Comments
 (0)