如果测试方法驻留在所有测试共用的类中,如何记录测试类的名称?

2024-09-30 06:23:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我的项目结构如下:

/root
  /tests
    common_test_case.py
    test_case_1.py
    test_case_2.py
    ...
  project_file.py
  ...

每个测试test_case_...都继承自^{}common_test_case.CommonTestCase。类CommonTestCase包含应该由所有测试执行的测试方法(尽管使用每个测试唯一的数据,存储和访问在测试的self.something中)。如果一个确切的测试用例需要一些特定的测试,则直接将它们添加到特定的类中。你知道吗

目前,我正在努力添加日志到我的测试。除此之外,我还想记录从中运行方法的类(因为上面的方法对不同的类意味着相同的测试方法名称)。我想使用内置的logging模块来实现这一点。你知道吗

我试过以下LogRecord attributes%(filename)s%(module)s%(pathname)s。不过,对于common_test_case.py中定义的方法,它们都将路径/名称返回给common_test_case.py,而不是实际运行它们的测试模块。你知道吗

我的问题是:

  1. 有没有一种方法可以实现我想要的,只使用内置的logging模块?你知道吗
  2. 使用一些第三方/其他模块(我想可能是一些带有^{}的“黑客”解决方案)?你知道吗
  3. 有可能实现(在Python中)吗?你知道吗

Tags: 模块项目方法pytestproject名称logging
2条回答

您的问题与此one类似,解决方法如下:

self.id()

请参阅函数定义here,它为实例化的TestCase类的实例调用self.__class__。如果您使用的是多重继承,multiple inheritance rules from Python将应用:

For most purposes, in the simplest cases, you can think of the search for attributes inherited from a parent class as depth-first, left-to-right, not searching twice in the same class where there is an overlap in the hierarchy.

这意味着common_test_case.CommonTestCase将被搜索,然后unittest.TestCase。如果在common_test_case.CommonTestCase中没有id函数,则应该像它只从unittest.TestCase派生一样工作。如果您觉得有必要将id函数添加到CommonTestCase,可以这样做(如果确实需要):

def id(self):
  if issubclass(self,unittest.TestCase):
    return super(unittest.TestCase,self).id()

解决方案I've found(到目前为止,这是关键): 你知道吗

import inspect

class_called_from = inspect.stack()[1][0].f_locals['self'].__class__.__name__

不过,我仍然在想,是否有一个“更清晰”的方法,或者是否可以使用logging模块来实现。你知道吗


配方,基于West's answer(在python3.6.1上测试): 你知道吗

test_name = self.id().split('.')[-1]
class_called_from = self.id().split('.')[-2]

相关问题 更多 >

    热门问题