[Tutor] TDD: How to test input()?

Alan Gauld alan.gauld at yahoo.co.uk
Sat Oct 8 04:18:16 EDT 2016


On 08/10/16 07:18, Steven D'Aprano wrote:

> Testing code that depends on user input is always tricky. There are a 
> few ways to deal with it:
> 
> (5) Or you could manually monkey-patch sys.stdin as you do.

A variation on this that I have used is to read the input
from stdin as usual but redirect stdin when you run the
code:

python test_input.py < testdata.txt

That way I can use multiple sets of test data and run
the tests using the different data sets. The test suite
is then exercised by a simple shell script that runs
against each test file in turn.

I find that easier and more flexible than using a
StringIO buffer. You can catch EOF errors in your
test rig or write the tests to read a finite set
of data and create the data to match.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list