Alex Rivera | Logout

How can I simulate input to stdin for pyunit?

Asked 2011-06-07T21:40:38.430
28

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 | ./spellchecker.py

In the name of test automation, is there any way that pyunit can fake input to raw_input()?

Edit
Report

1 Answer

4

You didn't describe what sort of code is in spellchecker.py, which gives me freedom to speculate.

Suppose it's something like this:

import sys

def check_stdin():
  # some code that uses sys.stdin

To improve testability of check_stdin function, I propose to refactor it like so:

def check_stdin():
  return check(sys.stdin)

def check(input_stream):
  # same as original code, but instead of
  # sys.stdin it is written it terms of input_stream.

Now most of your logic is in check function, and you can hand-craft whatever input you can imagine in order to test it properly, without any need to deal with stdin.

My 2 cents.

answered 2011-06-08T03:42:21.107

Your Answer