簡體   English   中英

將模擬side_effect分配給boto異常並斷言調用

[英]assign mock side_effect to a boto exception and assert calls

我有一個使用boto從s3下載文件的類,該方法使用S3Connection類來初始化連接,然后使用get_key方法獲取'file'。 這是代碼塊

import sys

from boto.exception import S3ResponseError, S3DataError
from boto.s3.connection import S3Connection

class MyClass(object):
    def __init__(self):
        self.s3conn = S3Connection(
                AWS_ACCESS_KEY_ID,
                AWS_SECRET_ACCESS_KEY,
                host=HOST,
                is_secure=True
        )
        self.bucket = self.s3conn.get_bucket(BUCKET_NAME)
    def get_file(self, key):
        try:
            return self.bucket.get_key(key)
        except (S3ResponseError, S3DataError):
            sys.exit(3)

我想模擬get_bucket方法並給它一個side_effect的S3ResponseError ,這樣我就可以模擬出sys.exit方法並斷言它被調用了。

我是這樣做的。

import unittest
import mock
from boto.exception import S3ResponseError, S3DataError
from mymodule import MyClass

class TestS3(unittest.TestCase):
    def setUp(self):
        self.key = 'sample/bubket/key.txt'
        self.myclass = MyClass()

    def test_my_method(self):
        exit_method = (
            'mymodule.'
            'sys.'
            'exit'
        )
        s3_get_bucket = (
            'mymodule.'
            'S3Connection.'
            'get_bucket'
        )


        with mock.patch(s3_get_bucket) as mocked_bucket, \
            mock.patch(exit_method) as mocked_exit:
                mocked_bucket.side_effect = S3ResponseError
                self.myclass.get_file(self.key)
                mocked_exit.assert_called_once_with(3)

但是,斷言失敗,任何幫助或指導都表示贊賞。

AssertionError: Expected to be called once. Called 0 times.

它看起來像我的問題是MyClass.get_file()不調用get_bucket() 這就是為什么你沒有看到對sys.exit()的調用。 模擬get_key()或調用get_bucket()

暫無
暫無

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

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