Skip to main content

One post tagged with "mocking"

View All Tags

· 4 min read
Hreniuc Cristian-Alexandru

An example on how you can mock things in python.

Let's assume we have the following folder structure:

 - project
- src
- test
- utils
- aws.SSMClient.AWSFactory
- and so on, check below in the code

To run the unit tests:

cd src

python3 -m unittest discover -p "*test*" -v

If you added a new subfolder in test, you need to also add an empty file called __init__.py, to be discovered by the command from above.

When adding unit tests, you can enable logging for a specific testa case if you add the following line in the beginning of the test case:

logging.disable(logging.DEBUG)

Also, in all unit tests we inject fake response from aws using mock and we also enforce that a method be called with a specific set of params. To see the mock calls made on the boto3(aws) instances you can temporary add the following prints:

print(f'\n{self.mock_ssm.mock_calls}\n')
print(f'\n{self.mock_ec2.mock_calls}\n')
print(f'\n{self.mock_sqs.mock_calls}\n')

This will print all calls made on the aws instances, this way you can verify and add mock expectations in your tests.

In the file below you will notice that we import fake data or Helpers, those things are just strings that we want to return or the call params of a mock method, eg: