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

后端 未结 4 424
囚心锁ツ
囚心锁ツ 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:29

    Using pytest:

    import os
    
    
    def test_user_input(monkeypatch):
        inputs = [10, 'y']
        input_generator = (i for i in inputs)
        monkeypatch.setattr('__builtin__.raw_input', lambda prompt: next(input_generator))
        assert raw_input('how many?') == 10
        assert raw_input('you sure?') == 'y'
    
    
    def test_file_input(tmpdir):
        fixture = tmpdir.join('fixture.txt')
        fixture.write(os.linesep.join(['1', '2', '3']))
        fixture_path = str(fixture.realpath())
        with open(fixture_path) as f:
            assert f.readline() == '1' + os.linesep
    
    
    def test_environment_input(monkeypatch):
        monkeypatch.setenv('STAGING', 1)
        assert os.environ['STAGING'] == '1'
    

提交回复
热议问题