[Tutor] using generators to mock raw_input for doctest
broek at cc.umanitoba.ca
broek at cc.umanitoba.ca
Sun Aug 10 07:38:18 CEST 2008
Hi all,
I'm building a tool that will be run in a shell and depends heavily on
raw_input. I'm also using doctest (mostly via doctest.testfile) to
create unit tests for it.
After thinking a while about how to use doctest for invocations of
raw_input, I came up with the general sort of idea shown in the toy
code below.
I have two questions:
1) As I've never really made generators `mine,' I'm not sure if this is
the best (read `best' as `easiest and simplest') way to use a generator
for this task. Should I be doing it differently?
2) Is there some better way to enable doctesting of code that uses
raw_input? All I found when googling was the suggestion that in place of:
def myfunc():
# code employing raw_input here
one could write:
def myfunc(input_meth=raw_input):
# code with raw_input calls replaced with input_meth calls
but that seems like complicating my code for the non-doctest case.
Perhaps that worries me too much, though---I've yet to become test
infected ;-)
Thanks for any input,
Brian vdB
import sys
class myraw(object):
def __init__(self, values):
self.values = values
self.stream = self.mygen()
def mygen(self):
for i in self.values:
yield i
def readline(self):
return str(self.stream.next())
def double_user_input():
"""A silly example to illustrate my method for testing.
>>> sys.stdin = myraw([1,21,12.5,3.1415])
>>> double_user_input()
2
>>> double_user_input()
42
>>> double_user_input()
25
>>> double_user_input() # doctest: +ELLIPSIS
6.28300...
>>> sys.stdin = sys.__stdin__
"""
val = float(raw_input()) * 2
val = [val, int(val)][val == int(val)]
return val
def __test():
import doctest
doctest.testmod()
if __name__ == "__main__":
__test()
More information about the Tutor
mailing list