Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The short answer is to <a href="http://en.wikipedia.org/wiki/Monkey_patch" rel="nofollow noreferrer">monkey patch</a> <code>raw_input()</code>.</p> <p>There are some good examples in the answer to <a href="https://stackoverflow.com/questions/5812333/how-to-display-the-redirected-stdin-in-python">How to display the redirected stdin in Python?</a></p> <p>Here is a simple, trivial example using a <code>lambda</code> that throws away the prompt and returns what we want.</p> <h2>System Under Test</h2> <pre><code>cat ./name_getter.py #!/usr/bin/env python class NameGetter(object): def get_name(self): self.name = raw_input('What is your name? ') def greet(self): print 'Hello, ', self.name, '!' def run(self): self.get_name() self.greet() if __name__ == '__main__': ng = NameGetter() ng.run() $ echo Derek | ./name_getter.py What is your name? Hello, Derek ! </code></pre> <h2>Test case:</h2> <pre><code>$ cat ./t_name_getter.py #!/usr/bin/env python import unittest import name_getter class TestNameGetter(unittest.TestCase): def test_get_alice(self): name_getter.raw_input = lambda _: 'Alice' ng = name_getter.NameGetter() ng.get_name() self.assertEquals(ng.name, 'Alice') def test_get_bob(self): name_getter.raw_input = lambda _: 'Bob' ng = name_getter.NameGetter() ng.get_name() self.assertEquals(ng.name, 'Bob') if __name__ == '__main__': unittest.main() $ ./t_name_getter.py -v test_get_alice (__main__.TestNameGetter) ... ok test_get_bob (__main__.TestNameGetter) ... ok ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload