簡體   English   中英

有沒有一種方法可以配置Python日志記錄來記錄斷言失敗的內容或上下文?

[英]Is there a way to configure Python logging to log content or context of assert failures?

我正在運行測試用例,我想以一種自動記錄所有測試失敗的情況的方式設置日志,但是我想獲得自定義響應,例如,如果斷言失敗,我會d想獲得對我的測試提出的請求的響應,而不僅僅是獲得斷言失敗的默認消息。 目前,我只知道斷言失敗,但是我不知道程序返回了什么。

假設我正在測試一個視圖函數,例如,我有一個看起來像這樣的測試(整個TestCase類的一部分)

def edit_profile(self):
    return self.app.get("/edit_profile", follow_redirects=True)

def test_edit_profile(self):
    rv = self.edit_profile()
    assert "Edit your profile admin" in rv.data

我有沒有辦法配置日志記錄,使每次測試失敗都會將rv.data記錄到日志文件中?

目前,我只是簡單地在先前測試失敗的斷言之前添加logging.debug(rv.data),再次運行測試,調試問題,然后繼續,但這是無效的,很容易忘記那些loggging.debug()稍后,如果我有一個自動將網頁響應記錄到測試請求(如果測試請求失敗)的功能,它將更快。

您可以執行以下操作:

def test_edit_profile(self):
    rv = self.edit_profile()
    try:
        assert "Edit your profile admin" in rv.data
    except AssertionError:
        # Do your logging here

編輯:指出這基本上取消了斷言功能,因為斷言由except塊處理。 歡迎提出建議。

編輯:這將工作,但很草率。

def test_edit_profile(self):
    rv = self.edit_profile()
    try:
        assert "Edit your profile admin" in rv.data
    except AssertionError:
        assert "Edit your profile admin" in rv.data
        # Do your logging here
self.assertIn('Edit your profile admin', rv.data, msg=rv.data)

使用assertWhatever方法。 我不完全理解為什么,但是您不應該在unittest中將assert語句用於斷言。 (其他框架允許您使用assert進行assert 。)

作為參考,將消息添加到assert斷言的過程如下:

assert 'Edit your profile admin' in rv.data, rv.data

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM