【问题标题】:How do I capture the function name with the class name right outside it?如何在函数名之外捕获带有类名的函数名?
【发布时间】: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


【解决方案1】:

我对 Tkinter 或如何选择事物并不是很熟悉,但这可能会为您指明正确的方向。

正如我在 cmets 中提供的链接所示,实例(即类)没有名称。如果要为实例命名,只需将其包含在def __init__(self): 中。当调用来自test_ABC(也继承self)的任何方法(即函数)时,您将始终可以访问self.name

class test_Abc():
    def __init__(self):
        self.name = 'test_Abc'
    def test_x(self):
       return self.name
    def test_y(self):
       return self.name

abc = test_Abc()

a = abc.test_x()

print('pytest testFile.py::' + a + '::test_x')

返回:

pytest testFile.py::test_Abc::test_x

【讨论】:

    猜你喜欢
    • 2016-07-12
    • 1970-01-01
    • 2012-09-08
    • 2013-04-01
    • 1970-01-01
    • 2019-11-24
    • 2015-12-01
    • 1970-01-01
    • 2015-11-13
    相关资源
    最近更新 更多