久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

模擬函數以引發異常以測試 except 塊

Mocking a function to raise an Exception to test an except block(模擬函數以引發異常以測試 except 塊)
本文介紹了模擬函數以引發異常以測試 except 塊的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我有一個函數 (foo),它調用另一個函數 (bar).如果調用bar()引發了HttpError,如果狀態碼是404我想特別處理,否則重新引發.

I have a function (foo) which calls another function (bar). If invoking bar() raises an HttpError, I want to handle it specially if the status code is 404, otherwise re-raise.

我正在嘗試圍繞這個 foo 函數編寫一些單元測試,模擬對 bar() 的調用.不幸的是,我無法獲得對 bar() 的模擬調用來引發我的 except 塊捕獲的異常.

I am trying to write some unit tests around this foo function, mocking out the call to bar(). Unfortunately, I am unable to get the mocked call to bar() to raise an Exception which is caught by my except block.

這是說明我的問題的代碼:

Here is my code which illustrates my problem:

import unittest
import mock
from apiclient.errors import HttpError


class FooTests(unittest.TestCase):
    @mock.patch('my_tests.bar')
    def test_foo_shouldReturnResultOfBar_whenBarSucceeds(self, barMock):
        barMock.return_value = True
        result = foo()
        self.assertTrue(result)  # passes

    @mock.patch('my_tests.bar')
    def test_foo_shouldReturnNone_whenBarRaiseHttpError404(self, barMock):
        barMock.side_effect = HttpError(mock.Mock(return_value={'status': 404}), 'not found')
        result = foo()
        self.assertIsNone(result)  # fails, test raises HttpError

    @mock.patch('my_tests.bar')
    def test_foo_shouldRaiseHttpError_whenBarRaiseHttpErrorNot404(self, barMock):
        barMock.side_effect = HttpError(mock.Mock(return_value={'status': 500}), 'error')
        with self.assertRaises(HttpError):  # passes
            foo()

def foo():
    try:
        result = bar()
        return result
    except HttpError as error:
        if error.resp.status == 404:
            print '404 - %s' % error.message
            return None
        raise

def bar():
    raise NotImplementedError()

我按照 Mock docs 說您應該將 Mock 實例的 side_effect 設置為 Exception 類,以使模擬函數引發錯誤.

I followed the Mock docs which say that you should set the side_effect of a Mock instance to an Exception class to have the mocked function raise the error.

我還查看了一些其他相關的 StackOverflow Q&As,看起來我正在做與他們正在做的事情相同的事情,以導致他們的模擬引發異常.

I also looked at some other related StackOverflow Q&As, and it looks like I am doing the same thing they are doing to cause and Exception to be raised by their mock.

  • https://stackoverflow.com/a/10310532/346561
  • 如何使用 Python Mock 引發異常 - 但將 Errno 設置為給定值

為什么設置 barMockside_effect 不會引發預期的 Exception?如果我在做一些奇怪的事情,我應該如何在我的 except 塊中測試邏輯?

Why is setting the side_effect of barMock not causing the expected Exception to be raised? If I am doing something weird, how should I go about testing logic in my except block?

推薦答案

你的 mock 可以很好地引發異常,但是缺少 error.resp.status 值.與其使用 return_value,不如告訴 Mock status 是一個屬性:

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Mock() 的附加關鍵字參數被設置為結果對象的屬性.

Additional keyword arguments to Mock() are set as attributes on the resulting object.

我將您的 foobar 定義放在 my_tests 模塊中,并添加到 HttpError class 所以我可以使用它也一樣,然后你的測試就可以成功了:

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

您甚至可以看到 print '404 - %s' % error.message 行運行,但我認為您想在那里使用 error.content ;無論如何,這就是 HttpError() 從第二個參數設置的屬性.

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

這篇關于模擬函數以引發異常以測試 except 塊的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How should I verify a log message when testing Python code under nose?(在鼻子下測試 Python 代碼時,我應該如何驗證日志消息?)
Patch __call__ of a function(修補函數的 __call__)
How to call self in a mock method of an object in Python?(如何在 Python 中對象的模擬方法中調用 self?)
Mocking only a single method on an object(僅模擬對象上的單個方法)
Mocking a subprocess call in Python(在 Python 中模擬子進程調用)
Checking call order across multiple mocks(檢查多個模擬的調用順序)
主站蜘蛛池模板: 黄色免费观看 | 中文字幕精品视频 | 一区二区三区播放 | 久久久国产一区二区三区 | 国产精品国产成人国产三级 | 一级黄色片免费 | 精品国产伦一区二区三区观看方式 | 九九热在线免费观看 | 亚洲九色 | 美女天天操| 亚洲成人精品久久 | 国产色婷婷久久99精品91 | 一级片免费观看 | 欧美一区二区综合 | 欧州一区二区三区 | 国产精品夜色一区二区三区 | 国产japanhdxxxx麻豆 | 成人精品一区二区 | 91在线视频免费观看 | 亚洲成av人片在线观看无码 | 91久久久久 | 伊人一二三 | 精品免费国产一区二区三区四区介绍 | 国产一区不卡 | 成年人免费在线视频 | 日日干日日射 | 日韩免费1区二区电影 | 久久精品国产久精国产 | 爱爱免费视频网站 | 一区在线免费视频 | 精区3d动漫一品二品精区 | 中文字幕一级 | 888久久久 | 国产偷录视频叫床高潮对白 | 日本天堂一区 | 99久久精品国产麻豆演员表 | 亚洲综合无码一区二区 | 久久久国产精品网站 | 久久久久久久久久久久久久av | 精品1区 | 国产91视频一区二区 |