I have a python file with module variables that are getting assigned at run time, as below; now the challenge is that I need to mock methods in this module. I am not able to mock below module scopes variable that are evaluated at run time session -> client -> get_secret_value_response.
Sample Code below
The below is module code from file that is under test
import boto3
import os
from github import Github
from github.Auth import Auth
X_REGION: str=os.environ['X_REGION']
X_ID: str = os.environ['X_ID']
session = boto3.session.Session()
client = session.client(
service_name='test-module',
region_name=X_REGION
)
get_secret_value_response = client.get_secret_value(
SecretId=X_ID
)
git_token = get_secret_value_response['secret']
class CommonGit:
# functions to fetch file from git repo using 'git_token'
def get_file_from_repo(self):
g = Github(git_token)
# Get the authenticated user
user = g.get_user()
# Print all repositories for the authenticated user
for repo in user.get_repos():
print(repo.name)
Unit Test 1
import os
from unittest.mock import patch
import pytest
@pytest.fixture()
def setup():
os.environ["SOME_REGION"] = "abc"
os.environ["GIT_CREDS"] = "GIT_CREDS"
os.environ["GIT_ORG"] = "some-org"
os.environ["GIT_REPO"] = 'some-repo'
os.environ['GIT_ENDPOINT'] = 'https://dummy'
@pytest.fixture
def util(setup):
from abc import GitCommons
return GitCommons()
@patch("client.get_secret_value")
def test_read_template_from_git(util, setup):
util.read_template_from_git("test", "test")
Unit Test 2 with monkeypatch:
@pytest.fixture(scope="module")
def util(monkeypatch):
os.environ["SOME_REGION"] = "abc"
os.environ["SOME_ID"] = "SOME_ID"
os.environ["GIT_ORG"] = "SOME ORG"
os.environ["GIT_REPO"] = 'SOME REPO'
os.environ['GIT_ENDPOINT'] = 'https://dummy'
# @patch("src.packg.git_commons.get_token", return_value='test123')
session = boto3.session.Session
client = session.client()
get_secret_value_response = client.get_secret_value()
monkeypatch.setattr("src.search_utils.git_commons","get_secret_value_response", get_secret_value_response)
from src.search_utils.git_commons import GitCommons
return GitCommons()
I tried @patch(“client.get_secret_value”)
I am getting error as ” ModuleNotFoundError: No module named ‘client'”
In the second variation, I tried @pytest.fixture(scope=”module”) & monkeypatch together but did not work as when module is loaded, the module level dynamic code needs above mentioned constants, with in the module scoped fixture we cannot use function scoped monkeypatch. I tried different scopes but much luck.
Please guide me if any of you have experience in similar mocking.
Please let me know if you need any more details. I tried to clarify with more details.
Srini is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2