import __builtin__
import sys
from contextlib import contextmanager
@contextmanager
def mock_raw_input(*input_list):
"""Monkey patch the raw_input()"""
_raw_input = __builtin__.raw_input
def _stub(prompt='', input_iter=iter(input_list), orig=_raw_input):
try:
_input = next(input_iter)
sys.stdout.write(prompt)
return _input
except StopIteration:
__builtin__.raw_input = _raw_input
return raw_input(prompt)
__builtin__.raw_input = _stub
try:
yield
finally:
__builtin__.raw_input = _raw_input
def main():
with mock_raw_input('abc','cde'):
print raw_input('abc?\n')
print raw_input()
print raw_input('no more expected value? ')
raw_input('raw_input should be back to default here, right? ')
if __name__ == "__main__":
main()
Thursday, July 11, 2013
Monkey patch (mock) the built-in raw_input function
For testing without mock (thirdparty or 3.x), I wrote a mock context manager function for raw_input. If you do not provide enough response in the mock_raw_input argument list, the raw_input is back to normal.
Subscribe to:
Post Comments (Atom)
1 comment:
Emperor Casino | Shootercasino.com
Check out the official website of Emperor Casino, 제왕 카지노 to play at the casino and win real cash in their 바카라 free casino spins. Rating: 4.7 · Review by Shootercasino หาเงินออนไลน์
Post a Comment