Reputation: 2998
I'm trying to write a test (using unittest
) for a simple Python program. It is an interactive program, specifcally it will be a text-based game, for now basically a port of World of Zuul to Python.
So now I want to do good test-driven development and write a test and make sure that when the user inputs command x, that y results happen. Example: when the user inputs "quit", I want the program to end. I want to ensure that behavior. The only problem is, I can't seem to think of a way to give my own program input without actually typing that input into the shell, so I can't think of how to write a test for this.
Currently, I have embedded the program in its own thread... I was thinking this would allow me to asynchronously give it input, but I still don't see how this can be done.
Is there a way to programmatically and dynamically give my own program input? ... Like, using stdin
or something? If so I am thoroughly confused, and would appreciate an example.
Finally, if I am on the wrong track here, please tell me, because I am new to both Python and test-driven development, and I would appreciate any suggestions.
Upvotes: 1
Views: 740
Reputation: 363607
You can set up tests that run the program's main function and read the input that the user would provide from a file (or from a string) if you set up the code like this:
def main(inp):
# play game
if __name__ == '__main__':
main(sys.stdin)
Then the test involves setting up an input stream (perhaps a StringIO
), feeding that to main
, and monitoring the output. If you think the program might hang, you can run it in a separate thread and give it a timeout.
If you want to get fancy, you can even use a pty
to simulate terminal input.
Upvotes: 1