How to supply stdin, files and environment variable inputs to Python unit tests?

后端 未结 4 436
囚心锁ツ
囚心锁ツ 2020-11-29 03:51

How to write tests where conditions like the following arise:

  1. Test user Input.
  2. Test input read from a file.
  3. Test input read from an environme
4条回答
  •  青春惊慌失措
    2020-11-29 04:28

    If you are tied to using raw_input (or any other specific input source), I'm a big proponent of the mock library. Given the code that Mark Rushakoff used in his example:

    def say_hello():
        name = raw_input("What is your name? ")
        return "Hello " + name
    

    Your test code could use mock:

    import mock
    
    def test_say_hello():
         with mock.patch('__builtin__.raw_input', return_value='dbw'):
             assert say_hello() == 'Hello dbw'
    
         with mock.patch('__builtin__.raw_input', side_effect=['dbw', 'uki']):
             assert say_hello() == 'Hello dbw'
             assert say_hello() == 'Hello uki'
    

    These assertions would pass. Note that side_effect returns the elements of the list in order. It can do so much more! I'd recommend checking out the documentation.

提交回复
热议问题