Re: Simulte user input using doctest

Discussion in 'Python' started by Steven Taschuk, Jun 27, 2003.

  1. 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()

    18
    """
    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()

    18
    """

    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
    "Our analysis begins with two outrageous benchmarks."
    -- "Implementation strategies for continuations", Clinger et al.
     
    Steven Taschuk, Jun 27, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    4
    Views:
    685
    Walter Roberson
    Sep 9, 2005
  2. Replies:
    3
    Views:
    411
  3. Andy Dingley

    Using doctest with simple text files ?

    Andy Dingley, Jun 8, 2007, in forum: Python
    Replies:
    0
    Views:
    239
    Andy Dingley
    Jun 8, 2007
  4. Chris Carlen
    Replies:
    1
    Views:
    635
    Gabriel Genellina
    Sep 18, 2007
  5. Tarkeshwar
    Replies:
    2
    Views:
    204
Loading...

Share This Page