How to mock global modules
So, imagine if you want to mock an external dependency in a script, like this one that is connection to AWS
# script.py
import boto3
client = boto3.client("ssm")
If you follow python documentation and apply for this case, will not work. For this case, you need to mock the module itself.
Unfortunately, I wasn’t able to mock boto3
entirely, but I can mock the client()
, this way:
# test.py
from unittest.mock import patch
@patch("boto3.client")
def test_boto(boto3):
import script
assert isinstance(script.client, MagicMock)
And done :)