[英]Python UnitTest - How can I access subTests messages without having to write them manually?
A little bit of context: I am using Python and Selenium for QA Web Automation and I am using the Page Object Model pattern. 有一点上下文:我正在将Python和Selenium用于QA Web Automation,并且正在使用Page Object Model模式。 I am currently in the process of making the logger part of the system, and I want to make the code more efficient, without having to write a lot of dublicate code.
我目前正在使记录器成为系统的一部分,并且我想使代码更高效,而不必编写很多重复的代码。 I checked the docs for subTests, but can't find anything in particular and this is the reason I am here.
我在文档中检查了subTests,但是找不到特别的东西,这就是我在这里的原因。 So I am wondering if there is a way to access this part of the code (so I don't have to write each logger message each time, which is not very practical):
因此,我想知道是否有一种方法可以访问这部分代码(因此,我不必每次都写每个记录器消息,这不是很实际):
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
Thank you in advance! 先感谢您!
You can do self.logger(self._subtest._message)
to get the message. 您可以执行
self.logger(self._subtest._message)
来获取消息。
Beware, you are accessing internals variable of unittest thus this code can be broken in the next release of python without warning. 当心,您正在访问unittest的内部变量,因此该代码可以在下一版本的python中被破坏,而不会发出警告。
Possible approach: 可能的方法:
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)
...
Or you may create attribute message
in the setUp
method of the test and use it to pass message into subTest
and access/modify when you need. 或者,您可以在测试的
setUp
方法中创建属性message
,并将其用于将消息传递到subTest
并在需要时进行访问/修改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.