Files
ipython-demo/tests/test_app.py
T

90 lines
2.9 KiB
Python

import contextlib
import io
import re
import unittest
from unittest.mock import Mock, patch
from ipython_shell import utils
from ipython_shell.app import App
from ipython_shell.models import CallOptions, CallResponse
class AppTests(unittest.TestCase):
def test_generate_good_names_uses_readable_random_words(self):
generator = Mock()
assert isinstance(generator.word, Mock)
generator.word.side_effect = ["luminous", "otter"]
with patch.object(
utils,
"_WORD_GENERATOR",
generator,
create=True,
):
name = utils.generate_good_names()
self.assertRegex(name, re.compile(r"^[a-z]+-[a-z]+-[0-9a-f]{4}$"))
generator.word.assert_any_call(include_categories=["adjectives"])
generator.word.assert_any_call(include_categories=["nouns"])
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",
options=CallOptions(collapsed=True),
)
self.assertIsInstance(call, CallResponse)
self.assertEqual(call.code, "print('hello'); 2 + 2")
self.assertTrue(call.options.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)
def test_create_shell_and_get_last_shell_return_metadata(self):
app = App()
created = app.create_shell()
last = app.get_last_shell()
self.assertEqual(created.shell_id, last.shell_id)
self.assertEqual(created.name, last.name)
self.assertEqual(created.execution_count, 0)
if __name__ == "__main__":
unittest.main()