测试程序启动时没有错误 - 将 input() 重新定义为 sys.exit(0)?
Test that program starts without errors - redefine input() to sys.exit(0)?
我有一些需要用户输入的 python 程序,我们称它为 myprogram.py,但我想要一个自动测试来检查程序是否到达第一个 input() 调用。在不更改程序本身的源代码的情况下如何做到这一点有什么想法吗?
我认为最简单的方法是重新定义内置的 input(),如果可能的话。大致如下:
import sys
def input():
sys.exit(0)
run("./src/myprogram.py")
(请注意,我也需要重新定义的 input() 函数才能在导入的模块中工作)。
经过更广泛的搜索后,我从邮件列表中找到了这个:
https://mail.python.org/pipermail/python-list/2010-April/573829.html
使用 builtins global 解决了它 - 将解决方案留在这里供其他人搜索:
#!/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()
(假设我的程序有一个可调用的主函数,我的有)。
编辑: 或 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
您可以更改当前正在执行的 Python 程序的内置函数(以及大多数其他函数):
import builtins
import sys
def input():
sys.exit(0)
builtins.input = input
...rest of program...
并且它将影响从该点开始在内该程序执行的代码,包括随后导入的任何其他模块。但是,它 不会 影响作为单独进程在外部执行的其他脚本(假设您在问题中写 run
时的意思是 subprocess.run()
)。
我有一些需要用户输入的 python 程序,我们称它为 myprogram.py,但我想要一个自动测试来检查程序是否到达第一个 input() 调用。在不更改程序本身的源代码的情况下如何做到这一点有什么想法吗?
我认为最简单的方法是重新定义内置的 input(),如果可能的话。大致如下:
import sys
def input():
sys.exit(0)
run("./src/myprogram.py")
(请注意,我也需要重新定义的 input() 函数才能在导入的模块中工作)。
经过更广泛的搜索后,我从邮件列表中找到了这个:
https://mail.python.org/pipermail/python-list/2010-April/573829.html
使用 builtins global 解决了它 - 将解决方案留在这里供其他人搜索:
#!/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()
(假设我的程序有一个可调用的主函数,我的有)。
编辑: 或 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
您可以更改当前正在执行的 Python 程序的内置函数(以及大多数其他函数):
import builtins
import sys
def input():
sys.exit(0)
builtins.input = input
...rest of program...
并且它将影响从该点开始在内该程序执行的代码,包括随后导入的任何其他模块。但是,它 不会 影响作为单独进程在外部执行的其他脚本(假设您在问题中写 run
时的意思是 subprocess.run()
)。