How to test a function with input call?

后端 未结 6 1060
野性不改
野性不改 2020-11-29 04:16

I have a console program written in Python. It asks the user questions using the command:

some_input = input(\'Answer the question:\', ...)

6条回答
  •  隐瞒了意图╮
    2020-11-29 05:01

    You can replace sys.stdin with some custom Text IO, like input from a file or an in-memory StringIO buffer:

    import sys
    
    class Test:
        def test_function(self):
            sys.stdin = open("preprogrammed_inputs.txt")
            module.call_function()
    
        def setup_method(self):
            self.orig_stdin = sys.stdin
    
        def teardown_method(self):
            sys.stdin = self.orig_stdin
    

    this is more robust than only patching input(), as that won't be sufficient if the module uses any other methods of consuming text from stdin.

    This can also be done quite elegantly with a custom context manager

    import sys
    from contextlib import contextmanager
    
    @contextmanager
    def replace_stdin(target):
        orig = sys.stdin
        sys.stdin = target
        yield
        sys.stdin = orig
    

    And then just use it like this for example:

    with replace_stdin(StringIO("some preprogrammed input")):
        module.call_function()
    

提交回复
热议问题