Python UnitTest - 如何访问子测试消息而无需手动编写它们?



一点上下文:我正在使用Python和Selenium进行QA Web自动化,并且正在使用页面对象模型模式。 我目前正在使记录器成为系统的一部分,我想使代码更高效,而无需 不得不编写大量的代码。我检查了子测试的文档,但找不到任何特别的东西,这就是我在这里的原因。所以我想知道是否有办法访问这部分代码(所以我不必 每次写每个记录器消息,这不是很实用):

class TestScenario(unittest.TestCase):
.... # set Up class
def logger(self,info):
logger.error(f"Error happened at {info}")
def test_method(self):
with self.subTest("MESSAGE"):---------------------------------------------                                     
             |
try:                                                                 |
... something                                                    |
except AssertionError:                                               | 
self.logger(#Is there a way to access subTest msg parameter?) <---
raise
.... other subTests which will follow the same pattern

提前谢谢你!

您可以执行self.logger(self._subtest._message)来获取消息。

请注意,您正在访问 unittest 的内部变量,因此此代码可能会在下一个版本的 python 中被破坏而不会发出警告。

可能的方法:

class Message:
def __init__(self, message=''):
self.message = message
def __str__(self):
return self.message
# separate message for every subtest or one message continually modified between subtests
msg = Message('qwe')
...
with self.subTest(msg=msg):
msg.message = 'asd'  # access or modify
self.assertTrue(True)
...

或者,您可以在测试的setUp方法中创建属性message,并使用它来将消息传递到subTest并在需要时访问/修改。

最新更新