Home > database >  How to mock functions on import of main module?
How to mock functions on import of main module?

Time:03-14

I have the following problem:

My main.py contains:

from google.cloud import secretmanager    

secret_name = "abc"

def function_1(secret):
    client = secretmanager.SecretManagerServiceClient()
    name = f"projects/123/secrets/{secret}/versions/latest"
    response = client.access_secret_version(name=name)
    return response.payload.data.decode("UTF-8")

def function_2():
    secret = function_1(secret_name)
    return secret

secret = function_2()

and my test_main.py has:

def test_function_1():
    import main
    ...

When running this and other tests in test_main.py I get an error because by importing main function_2 is called and e.g. the access_secret_version method is called unmocked. I don't want to change my main.py and for example put secret = function_2() under if __name__=="__main__". I want to fix this in test_main.py.

I tried different things like

@patch('main.secretmanager.SecretManagerServiceClient')
@patch('main.secretmanager.SecretManagerServiceClient.access_secret_version')
def test_function_1():
    import main
    ...

but import main is always calling these methods unmocked. How can I do this? How can I mock what function_2 is calling?

Here Mock function called on import the OP found a similar workaround.

Thank you in advance for any help.

CodePudding user response:

The module in the @patch decorator should be google.cloud instead of main, otherwise you're importing from main in order to patch (which runs function_2 before it's patched).

@patch('google.cloud.secretmanager.SecretManagerServiceClient')
  • Related