From 095c041cb03534a8d541ddca273d0e4ab9045235 Mon Sep 17 00:00:00 2001 From: fwkz Date: Sun, 30 Jun 2019 19:49:03 +0200 Subject: [PATCH] Refactor `Riposte.run()` in order to make it easier to test. Factor out from the main loop logic regarding line processing. --- riposte/riposte.py | 18 +++++++++++++----- tests/test_guides.py | 28 +++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/riposte/riposte.py b/riposte/riposte.py index 6b7303c..adad081 100644 --- a/riposte/riposte.py +++ b/riposte/riposte.py @@ -147,15 +147,23 @@ def wrapper(func: Callable): return wrapper + def _process(self) -> None: + """ Process input provided by the input generator. + + Get provided input, parse it, pick appropriate command handling + function and execute it. + """ + user_input = input(self.prompt) + if not user_input: + return + command_name, *args = self._parse_line(user_input) + self._get_command(command_name).execute(*args) + def run(self) -> None: self._printer_thread.start() while True: try: - user_input = input(self.prompt) - if not user_input: - continue - command_name, *args = self._parse_line(user_input) - self._get_command(command_name).execute(*args) + self._process() except RiposteException as err: self.error(err) except EOFError: diff --git a/tests/test_guides.py b/tests/test_guides.py index afb10b1..5a90b48 100644 --- a/tests/test_guides.py +++ b/tests/test_guides.py @@ -3,7 +3,7 @@ import pytest -from riposte import guides +from riposte import Riposte, guides from riposte.exceptions import GuideError @@ -68,3 +68,29 @@ def test_extract_guides(mocked_get_guides): mocked_get_guides.assert_called_once_with(type_hint) assert extracted_guides == {"foo": mocked_get_guides.return_value} + + +@pytest.mark.parametrize( + ("input", "guide", "expected"), + ( + ("foobar", str, "foobar"), + ("'foobar'", str, "foobar"), + ("'foo bar'", str, "foo bar"), + ("foobar", bytes, b"foobar"), + ("'foobar'", bytes, b"foobar"), + ("'foo bar'", bytes, b"foo bar"), + ("1", int, 1), + ("'1'", int, 1), + ("\"[1, 'foo']\"", list, [1, "foo"]), + ("\"{'foo': 'bar'}\"", dict, {"foo": "bar"}), + ), +) +@mock.patch("builtins.input") +def test_guides(mocked_input, input, guide, expected, repl: Riposte): + mocked_input.return_value = "foobar " + input + + @repl.command("foobar") + def handler_function(x: guide): + assert x == expected + + repl._process()