【发布时间】:2019-12-08 04:59:58
【问题描述】:
我开发了一个 Tkinter 应用程序,它基本上会在测试文件中显示测试函数,用户可以选择特定的测试函数并在其上运行 pytest。到目前为止,它运行良好,因为我只有测试功能而没有类。现在,里面有类和函数。我如何捕捉到这些函数进入那个特定的类?我想过使用正则表达式,但类外也可能有函数。所以,我不知道如何解决这个问题。
到目前为止,我有这样的事情:
测试文件:
def test_x():
....
def test_y():
....
源代码:
with open("{}.py".format(testFile), "r") as fp:
line = fp.readline()
while line:
line = fp.readline()
if ("#" not in line) and ("def" and "test_" in line):
x = line.split()[1].split('(')[0]
gFunctionList.append([testName, x])
基于所有选择:
#var2State is the checkbutton states
for j in range(len(var2State)):
if var2State[j].get() == 1:
runString += "{}.py::{} ".format(gFunctionList[j][0],
gFunctionList[j][1])
else:
continue
if runString != "":
res = os.system("pytest " + runString)
从上面的代码中,如果选择了test_x,它将运行:pytest testFile.py::test_x。
现在如果测试文件是这样的:
Class test_Abc():
def test_x():
....
def test_y():
....
def test_j():
....
Class test_Xyz():
def k():
....
def test_l():
....
Class test_Rst():
def test_k():
....
def ltest_():
....
现在,如果选择了test_l,它应该运行:pytest testFile.py::test_Xyz::test_l。
但是我如何获得上面的test_Xyz?
如果选择了test_j,它应该运行:pytest testFile.py::test_j。
那么,我如何在一组特定的测试函数之外捕获类名,如果它不在类内则不捕获?
【问题讨论】:
-
@dubbbdan,我不太明白它的解释。我的问题是选择特定的测试功能时如何获取类名?如果只选择了一个没有类的函数,则不采用任何类。
-
您天真地尝试解析 python 代码不会让您走得太远。但为什么要打扰呢? python 解释器已经知道如何做到这一点,并且exposes 标准库中的功能。
-
当涉及到参数化或动态生成的测试时,即使是 AST 解析也不会让您走得太远;你需要运行
pytest.main(args='--collect-only', '--quiet'),捕获并解析输出。
标签: python python-2.7 pytest string-concatenation