Files
ipython-demo/tests/test_app.py
T

93 lines
3.0 KiB
Python

import contextlib
import importlib
import io
import json
import re
import subprocess
import sys
import unittest
from unittest.mock import Mock, patch
from ipython_demo.app import App
from ipython_demo.models import CallResponse
class AppTests(unittest.TestCase):
def test_generate_good_names_uses_readable_random_words(self):
app_module = importlib.import_module("ipython_demo.app")
generator = Mock()
generator.word.side_effect = ["luminous", "otter"]
with patch.object(
app_module,
"_WORD_GENERATOR",
generator,
create=True,
):
name = app_module.generate_good_names()
self.assertRegex(name, re.compile(r"^[a-z]+-[a-z]+-[0-9a-f]{4}$"))
generator.word.assert_any_call(include_parts_of_speech=["adjectives"])
generator.word.assert_any_call(include_parts_of_speech=["nouns"])
def test_main_emits_one_json_payload(self):
completed = subprocess.run(
[sys.executable, "-c", "from ipython_demo.app import main; main()"],
capture_output=True,
text=True,
check=True,
)
payload = json.loads(completed.stdout)
self.assertEqual(len(payload), 2)
self.assertEqual(payload[0]["events"][0]["kind"], "stdout")
self.assertTrue(payload[1]["collapsed"])
def test_run_code_returns_frontend_facing_call_response(self):
app = App()
with contextlib.redirect_stdout(io.StringIO()):
call = app.run_code(
"print('hello'); 2 + 2",
shell_name="new",
collapsed=True,
)
self.assertIsInstance(call, CallResponse)
self.assertEqual(call.code, "print('hello'); 2 + 2")
self.assertTrue(call.collapsed)
self.assertEqual(call.result.result, 4)
self.assertEqual([event.kind for event in call.events], [
"stdout",
"execute_result",
])
def test_last_reuses_shell_but_each_call_has_new_id(self):
app = App()
with contextlib.redirect_stdout(io.StringIO()):
first = app.run_code("x = 41", shell_name="new")
second = app.run_code("x + 1", shell_name="last")
self.assertEqual(first.shell_name, second.shell_name)
self.assertNotEqual(first.call_id, second.call_id)
self.assertEqual(second.result.result, 42)
def test_response_and_shell_list_expose_shell_info(self):
app = App()
with contextlib.redirect_stdout(io.StringIO()):
call = app.run_code("1 + 1", shell_name="new")
shells = app.list_shells()
self.assertEqual(len(shells), 1)
self.assertEqual(call.shell.shell_id, shells[0].shell_id)
self.assertEqual(call.shell.name, call.shell_name)
self.assertEqual(call.shell.execution_count, call.result.execution_count)
self.assertIn("execute_result", call.shell.capabilities)
if __name__ == "__main__":
unittest.main()