Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: Simulte user input using doctest

Thread Tools

Re: Simulte user input using doctest

Steven Taschuk
Posts: n/a
Quoth Bartolomé Sintes Marco:
> Is it possible to simulate user input in a doctest docstring? For example, I
> want to test if this module writes "Andy" when the user writes "Andy". What
> would be the docstring?
> def askyourname():
> print "What's your name?",
> myname = raw_input()
> print myname

Redefining raw_input as Terry suggested is conceivable. Note,
though, that the simplest approach won't work:

def foo():
>>> def bar():

... return 18
>>> foo()

return bar()

def bar():
return 3

This test fails because the new bar is not defined in any
lexically enclosing scope of foo. You could do, say,

>>> def bar():

... return 18
>>> foo.func_globals['bar'] = bar
>>> foo()


instead, but this is very hackish.

A better approach IMO is to make the function you want to test
more flexible:

def foo(inputfunc=raw_input):
print "What's your name?",
name = inputfunc()
print name

Now you can call foo with your own input function instead of
raw_input, and the test is easy:

>>> foo(inputfunc=lambda: "Andy")

What's your name? Andy

Such a technique can be considered to fall under the principle
"design for testing": write your code in such a way that it's easy
to test. (Advocates of test-driven development will observe that
their methodology produces such code by construction.)

Steven Taschuk Removed)
"Our analysis begins with two outrageous benchmarks."
-- "Implementation strategies for continuations", Clinger et al.

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Entering strings as user input but interpreting as Python input (sortof) Chris Carlen Python 1 09-18-2007 01:58 AM
Using doctest with simple text files ? Andy Dingley Python 0 06-08-2007 02:47 PM
how to restrict user from input in <input type="file"> Tarkeshwar Javascript 2 04-17-2006 11:44 AM
Getting User Input after getting Input from a file C++ 3 03-23-2006 05:01 AM
can I use scanf to get input (some times user enters input sometimes not, just hit keyboard)? C Programming 4 09-09-2005 03:38 AM