[Tutor] how to unittest cli input

Cameron Simpson cs at zip.com.au
Sun Oct 11 03:10:54 CEST 2015


On 10Oct2015 17:41, Alex Kleider <akleider at sonic.net> wrote:
>I'm trying to follow a test driven development paradigm (using
>unittest) but can't figure out how to test functions that collect
>info from the command line such as the following.

Aside: I'd say "the standard input" , not "the command line"; to me the latter 
connotes to command line arguments fro sys.argv.

Anyway, ...

I would supply test data either as a string in the unit tests or as a file kept 
with the source tree eg:

  os.path.join(os.path.dirname(__file__), 'test_data.txt')

and then parameterise the input source in you functions. For example:

  def collect_data(src=None):
      if src is None:
          src = sys.stdin

and supply src.

However, you'r eusing input(), which unconditionally uses stdin and stdout. In 
that circumstance I'd consider this:

  def collect_data(src=None, out=None):
      if src is None:
          src = sys.stdin
      if out is None:
          out = sys.stdout
      ostdin = sys.stdin
      sys.stdin = src
      ostdout = sys.stdout
      sys.stdout = out
      ret = {}
      ret['first'] = input("Enter your first name: ")
      ... etc ...
      sys.stdout = ostdout
      sys.stdin = ostdin

Note that this is not thread safe because sys.stdin is a global, but it should 
work for testing.

Anyway, perhap that gives you some way forward.

Cheers,
Cameron Simpson <cs at zip.com.au>


More information about the Tutor mailing list