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

模擬函數以引發(fā)異常以測試 except 塊

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

問題描述

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

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() 的模擬調用來引發(fā)我的 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 類,以使模擬函數引發(fā)錯誤.

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,看起來我正在做與他們正在做的事情相同的事情,以導致他們的模擬引發(fā)異常.

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 引發(fā)異常 - 但將 Errno 設置為給定值

為什么設置 barMockside_effect 不會引發(fā)預期的 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 可以很好地引發(fā)異常,但是缺少 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.

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

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

相關文檔推薦

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(檢查多個模擬的調用順序)
主站蜘蛛池模板: 国产亚洲一区二区三区 | 紧缚调教一区二区三区视频 | 一级毛片黄片 | 国产激情视频在线 | 欧美区日韩区 | 亚洲视频在线观看 | 国产这里只有精品 | 国产精品久久久久久久久久免费看 | 国产ts人妖系列高潮 | 日本精品一区二区三区在线观看视频 | 一区二区在线 | 国产精品亚洲精品 | 99精品久久| 久久久久国产一区二区三区四区 | 久草在线 | 国产精品国产三级国产aⅴ原创 | 国产欧美日韩一区二区三区在线观看 | 精品久久久久一区二区国产 | 色免费在线视频 | 中文在线一区二区 | 天堂一区在线 | 日本精品一区二区在线观看 | 欧美日韩中文字幕在线 | 国产精品一区久久久 | 免费看欧美一级片 | 羞羞视频免费在线观看 | 亚洲国产成人精品女人久久久 | 成人网在线观看 | 日日操av | 国产高清精品在线 | 久久久久久国产精品免费免费男同 | 一区二区三区四区在线视频 | 日本中文字幕日韩精品免费 | 狠狠综合网| 欧美精品一区二区三区在线播放 | 欧美激情在线精品一区二区三区 | 国内精品久久影院 | 中文字幕黄色大片 | 日日操视频 | 欧美天堂 | 国产精品自拍av |