[英]In Python, how do I write unit tests that can access private attributes without exposing them?
[英]Python UnitTest - How can I access subTests messages without having to write them manually?
有一點上下文:我正在將Python和Selenium用於QA Web Automation,並且正在使用Page Object Model模式。 我目前正在使記錄器成為系統的一部分,並且我想使代碼更高效,而不必編寫很多重復的代碼。 我在文檔中檢查了subTests,但是找不到特別的東西,這就是我在這里的原因。 因此,我想知道是否有一種方法可以訪問這部分代碼(因此,我不必每次都寫每個記錄器消息,這不是很實際):
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
並在需要時進行訪問/修改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.