I have some python program which expects user input, let's call it myprogram.py, but would like an automated test that checks that the program gets to the first input() call. Any ideas how to do this, without changing the source code of the program itself?
I thought the easiest way would be to redefine the input() built in, if at all possible. Something along the lines of:
import sys
def input():
sys.exit(0)
run("./src/myprogram.py")
(Note that I need the redefined input() function to work in imported modules as well).
After searching more generally I found this from a mailing list:
https://mail.python.org/pipermail/python-list/2010-April/573829.html
Solved it using builtins global - leaving the solution here for others searching:
#!/usr/bin/env python3
"""Test that program starts"""
import path_fix # Not important - adds src package to path
import sys
global __builtins__
def input():
sys.exit(0)
__builtins__.input = input
from src import myprogram
myprogram.main()
(Assumes myprogram has a callable main function, mine has).
Edit: Or in py.test:
import sys
import builtins
def test_starts():
def input():
sys.exit(0)
builtins.input = input
from src import myprogram
try:
myprogram.main()
raise Exception
except SystemExit as se:
if se.code != 0:
raise Exception