【Python】inputを使った処理をpytestでunittestしたい(monkeypatchでmockする)

Code

はじまり

リサちゃん
リサちゃん

う〜ん、この処理、中にinputが入ってるんだよな・・・。どうやって、テストしようか・・・。

135ml
135ml

あー、その場合、mockしてしまおうか。

リサちゃん
リサちゃん

なるほどねえ、でも、inputってビルトイン関数だよね?

その場合、どうするの?

135ml
135ml

今回紹介する方法で、ビルトイン関数もmockできるから試してみてくれ。

今回、テストしたいコード

今回は、このコードをpytestしたいと思います。中には、inputを使ったインタラクティブ処理が混ざっています。

input_controller.py

def repeat_input_with_multi_choices(first_message : str, choice_list : list = []) -> str:
    '''
    first_message    : String message for the first input.
    choice_list      : List of String choice.
    is_input_correct : Boolean input is correct or not.
    is_first_input   : Boolean this input is the first time or not.
    input_message    : String message for input.
    input_chr        : String input character.
    '''
    if type(first_message) != str:
        raise TypeError("first_message must be str type.")
    if type(choice_list) != list:
        raise TypeError("choice_list must be list type.")
    is_input_correct = False
    is_first_input   = True
    input_message   = ''
    input_chr       = ''
    while is_input_correct == False:
        if is_first_input == True:
            # Create message for the first input.
            input_message = first_message
        else:
            # Create message.
            input_message = 'Retry.'
            if choice_list == []:
                pass
            else:
                input_message += ' [ "'
                for i in range(0, len(choice_list)):
                    if i == 0:
                        input_message += '{choice}"'.format(choice=choice_list[i])
                    else:
                        input_message += ' or "{choice}"'.format(choice=choice_list[i])
                input_message += ' ]: '
        input_chr = input(input_message)
        # Check by message.
        if input_chr == '':
            pass
        else:
            if type(choice_list[0]) is int:
                if int(input_chr) >= 0 and int(input_chr) <= 100:
                    is_input_correct = True
                    input_chr = int(input_chr)
                else:
                    pass
            elif type(choice_list[0]) is str:
                if choice_list == []:
                    is_input_correct = True
                else:
                    for choice in choice_list:
                        if input_chr == choice:
                            is_input_correct = True
                            break
        is_first_input = False
    return input_chr

成功したケース

成功したケースは表題の通り、monkeypatchを引数に持ってきて、ビルトイン関数であるinput()

test_input_controller.py

from src.landmasterlibrarylocal.input_controller import repeat_input_with_multi_choices

class Test_Generaltool:

    def test_repeat_input_with_multi_choices_1_1(self, monkeypatch):
        first_message = "Select!"
        choice_list = ["A", "B", "C"]
        monkeypatch.setattr('builtins.input', lambda _: "A")
        actual = repeat_input_with_multi_choices(first_message, choice_list)
        expected = choice_list[0]
        assert actual == expected

出力

================================================================================================ test session starts ================================================================================================
platform darwin -- Python 3.9.7, pytest-7.1.1, pluggy-0.13.1
rootdir: /Users/landmaster/Downloads/landmasterlibrarylocal
plugins: freezegun-0.4.2, anyio-2.2.0, mock-3.7.0, cov-3.0.0
collected 1 item                                                                                                                                                                                                    

test/test_input_controller.py .
================================================================================================= 1 passed in 1.69s =================================================================================================

失敗したケースその1

以下、失敗したケースになりますが、このケースだと、”OSError: pytest: reading from stdin while output is captured! Consider using -s.”と表示されます。

エラー文の意味は、「インプット時のメッセージが出る前にインプットする内容を読み取っている。」ということなんですかね? よく分かりませんでした・・・が、とりあえずこれでは出来ないらしいと。

そこで、-sのオプションを付けて再度pytestを実行すると、インタラクティブモードが途中で挟んできますので、自動化出来ません。

test_input_controller.py

from src.landmasterlibrarylocal.input_controller import repeat_input_with_multi_choices

class Test_Generaltool:
    @pytest.mark.mock('builtins.input', lambda:'A')
        def test_repeat_input_with_multi_choices_1_1(self, monkeypatch):
            first_message = "Select!"
            choice_list = ["A", "B", "C"]
            actual = repeat_input_with_multi_choices(first_message, choice_list)
            expected = choice_list[0]
            assert actual == expected

出力

===================================================================================================== FAILURES ======================================================================================================
_____________________________________________________________________________ Test_Generaltool.test_repeat_input_with_multi_choices_1_1 _____________________________________________________________________________

self = <test.test_input_controller.Test_Generaltool object at 0x7ff150e45550>, monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x7ff150e40eb0>

    @pytest.mark.mock('builtins.input', lambda:'A')
    def test_repeat_input_with_multi_choices_1_1(self):
        first_message = "Select!"
        choice_list = ["A", "B", "C"]
>       actual = repeat_input_with_multi_choices(first_message, choice_list)

test/test_input_controller.py:28: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
src/landmasterlibrarylocal/input_controller.py:68: in repeat_input_with_multi_choices
    input_chr = input(input_message)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <_pytest.capture.DontReadFromInput object at 0x7ff15078e430>, args = ()

    def read(self, *args):
>       raise OSError(
            "pytest: reading from stdin while output is captured!  Consider using `-s`."
        )
E       OSError: pytest: reading from stdin while output is captured!  Consider using `-s`.

../../opt/anaconda3/lib/python3.9/site-packages/_pytest/capture.py:192: OSError
----------------------------------------------------------------------------------------------- Captured stdout call ------------------------------------------------------------------------------------------------
Select!
============================================================================================== short test summary info ==============================================================================================
FAILED test/test_input_controller.py::Test_Generaltool::test_repeat_input_with_multi_choices_1_1 - OSError: pytest: reading from stdin while output is captured!  Consider using `-s`.
================================================================================================ 1 failed in 1.70s ==================================================================================================

失敗したケースその2

これも失敗したケースになります。「builtinsの中に”input”とかいう属性は無いよ。」ということなんですかね。

でも、"input"がキーの中にあると思うんだけどな・・・。まあ、これもでとりあえず出来ないらしい。

test_input_controller.py

from src.landmasterlibrarylocal.input_controller import repeat_input_with_multi_choices

class Test_Generaltool:
    def test_repeat_input_with_multi_choices_1_1(self, mocker):
        first_message = "Select!"
        choice_list = ["A", "B", "C"]
        mocker.patch.object(__builtins__, 'input', lambda: choice_list[0])
        actual = repeat_input_with_multi_choices(first_message, choice_list)
        expected = choice_list[0]
        assert actual == expected

出力

(略)

===================================================================================================== FAILURES ======================================================================================================
_____________________________________________________________________________ Test_Generaltool.test_repeat_input_with_multi_choices_1_1 _____________________________________________________________________________

(略)

E           AttributeError: {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in'), '__build_class__': <built-in function __build_class__>, '__import__': <built-in function __import__>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'breakpoint': <built-in function breakpoint>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'max': <built-in function max>, 'min': <built-in function min>, 'next': <built-in function next>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'repr': <built-in function repr>, 'round': <built-in function round>, 'setattr': <built-in function setattr>, 'sorted': <built-in function sorted>, 'sum': <built-in function sum>, 'vars': <built-in function vars>, 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': <class 'bool'>, 'memoryview': <class 'memoryview'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'classmethod': <class 'classmethod'>, 'complex': <class 'complex'>, 'dict': <class 'dict'>, 'enumerate': <class 'enumerate'>, 'filter': <class 'filter'>, 'float': <class 'float'>, 'frozenset': <class 'frozenset'>, 'property': <class 'property'>, 'int': <class 'int'>, 'list': <class 'list'>, 'map': <class 'map'>, 'object': <class 'object'>, 'range': <class 'range'>, 'reversed': <class 'reversed'>, 'set': <class 'set'>, 'slice': <class 'slice'>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'zip': <class 'zip'>, '__debug__': True, 'BaseException': <class 'BaseException'>, 'Exception': <class 'Exception'>, 'TypeError': <class 'TypeError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'GeneratorExit': <class 'GeneratorExit'>, 'SystemExit': <class 'SystemExit'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'ImportError': <class 'ImportError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'OSError': <class 'OSError'>, 'EnvironmentError': <class 'OSError'>, 'IOError': <class 'OSError'>, 'EOFError': <class 'EOFError'>, 'RuntimeError': <class 'RuntimeError'>, 'RecursionError': <class 'RecursionError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'NameError': <class 'NameError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'SyntaxError': <class 'SyntaxError'>, 'IndentationError': <class 'IndentationError'>, 'TabError': <class 'TabError'>, 'LookupError': <class 'LookupError'>, 'IndexError': <class 'IndexError'>, 'KeyError': <class 'KeyError'>, 'ValueError': <class 'ValueError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'AssertionError': <class 'AssertionError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'OverflowError': <class 'OverflowError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'SystemError': <class 'SystemError'>, 'ReferenceError': <class 'ReferenceError'>, 'MemoryError': <class 'MemoryError'>, 'BufferError': <class 'BufferError'>, 'Warning': <class 'Warning'>, 'UserWarning': <class 'UserWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FutureWarning': <class 'FutureWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'ResourceWarning': <class 'ResourceWarning'>, 'ConnectionError': <class 'ConnectionError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'copyright': Copyright (c) 2001-2021 Python Software Foundation.
E           All Rights Reserved.
E           
E           Copyright (c) 2000 BeOpen.com.
E           All Rights Reserved.
E           
E           Copyright (c) 1995-2001 Corporation for National Research Initiatives.
E           All Rights Reserved.
E           
E           Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
E           All Rights Reserved., 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
E               for supporting Python development.  See www.python.org for more information., 'license': Type license() to see the full license text, 'help': Type help() for interactive help, or help(object) for help about object.} does not have the attribute 'input'

../../opt/anaconda3/lib/python3.9/unittest/mock.py:1378: AttributeError
============================================================================================== short test summary info ==============================================================================================
FAILED test/test_input_controller.py::Test_Generaltool::test_repeat_input_with_multi_choices_1_1 - AttributeError: {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNote...
================================================================================================= 1 failed in 1.76s =================================================================================================

おしまい

リサちゃん
リサちゃん

やったあ。ビルトイン関数も自動化出来たぞおお。

135ml
135ml

mockerで出来る方法を探したけど、見つからなかったな・・・

また機会があれば、格闘してみるか・・・

リサちゃん
リサちゃん

monkeypatchって、なんか可愛いよねえ。

以上になります!

コメント

タイトルとURLをコピーしました