How to make fun of the boto3 / call client object

I am trying to make fun of one specific boto3 function. My Cleanup module imports boto3. Cleanup also has a cleaner class. During init, the cleaner creates an ec2 client:

self.ec2_client = boto3.client('ec2') 

I want to make fun of the ec2 client method: desribe_tags (), which python says:

 <bound method EC2.describe_tags of <botocore.client.EC2 object at 0x7fd98660add0>> 

The longest I got was importing the botocore into a test file and trying:

 mock.patch(Cleaner.botocore.client.EC2.describe_tags) 

which fails:

 AttributeError: 'module' object has no attribute 'EC2' 

How do I make fun of this method?

The cleanup looks like this:

 import boto3 class cleaner(object): def __init__(self): self.ec2_client = boto3.client('ec2') 

An ec2_client object is one that has a desribe_tags () method. This is a botocore.client.EC2 object, but I never directly import botocores.

+5
source share
2 answers

I found a solution for this when trying to mock another method for an S3 client

 import botocore from mock import patch import boto3 orig = botocore.client.BaseClient._make_api_call def mock_make_api_call(self, operation_name, kwarg): if operation_name == 'DescribeTags': # Your Operation here! print(kwarg) return orig(self, operation_name, kwarg) with patch('botocore.client.BaseClient._make_api_call', new=mock_make_api_call): client = boto3.client('ec2') # Calling describe tags will perform your mocked operation eg print args e = client.describe_tags() 

Hope this helps :)

+1
source

You have to mock where you are testing. So, if you are testing your cleaner class (which I suggest you use PEP8 here and make it a cleaner ), then you want to taunt where you are testing. So your fix should be something like:

 class SomeTest(Unittest.TestCase): @mock.patch('path.to.Cleaner.boto3.client', return_value=Mock()) def setUp(self, boto_client_mock): self.cleaner_client = boto_client_mock.return_value def your_test(self): # call the method you are looking to test here # simple test to check that the method you are looking to mock was called self.cleaner_client.desribe_tags.assert_called_with() 

I suggest reading the mocking documentation , which has many examples of what you are trying to do.

0
source

Source: https://habr.com/ru/post/1247144/


All Articles