简体   繁体   中英

assign mock side_effect to a boto exception and assert calls

I have a class that uses boto to download a file from s3, the method uses the S3Connection class to initiliase a connection and later on uses the get_key method to get the 'file'. Here is the code block

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)

I want to mock out the get_bucket method and give it a side_effect of S3ResponseError , so that I can alo mock out the sys.exit method and assert it was called.

Here is how I am doing it.

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)

However, the assertion is failing, any help or guidance is appreciated.

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

It looks to me like the problem is that MyClass.get_file() doesn't call get_bucket() . That's why you're not seeing the call to sys.exit() . Either mock get_key() or call get_bucket() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM