How can I simulate input to stdin for pyunit?

前端 未结 5 1004
清酒与你
清酒与你 2020-12-03 10:56

I\'m trying to test a function that takes input from stdin, which I\'m currently testing with something like this:

cat /usr/share/dict/words | .         


        
5条回答
  •  無奈伤痛
    2020-12-03 11:05

    Replace sys.stdin with an instance of StringIO, and load the StringIO instance with the data you want returned via sys.stdin. Also, sys.__stdin__ contains the original sys.stdin object, so restoring sys.stdin after your test is as simple as sys.stdin = sys.__stdin__.

    Fudge is a great python mock module, with convenient decorators for doing patching like this for you, with automatic cleanup. You should check it out.

提交回复
热议问题