繁体   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