pythonmockingmockitopytest

Mocking a function in pytest with Patch doesnt work


I have written the test file status_update/tests/test_status_update.py which has the following content:

from lib.sync_mdl_status import update_mdl_status
    
@patch('scripts.aws_secrets.fetch_aws_secret')
def test_status_updater_mdl(self, new=MockFetchAwsSecrets()):
    db_ops_testing_insert_requests(TEST_FILE)
    db_ops_testing_insert_table_info(TABLE_INFO_FILE)
    db_ops_testing_insert_batch(BATCH_DATA_FILE)

    db_ops_testing_insert_mdl_work_requests(MDL_WORK_REQUESTS_DATA_FILE)
    db_ops_testing_insert_batch_table_mapping(BTM_DATA_FILE)

    db_ops_testing_insert_mdlendpoint_info(MDL_ENDPOINT_FILE)

    update_mdl_status(self.postgresql.url(), "test", 1, "roe-api-secrets")`

The update_mdl_status() function is inside the module status_update/lib/sync_mdl_status.py.
Furthermore update_mdl_status() return with a call to the function fetch_aws_secret() from scripts/aws_secrets.py.

I have mocked the function fetch_aws_secret() but the mock doesn't work and it tries to access the aws secret url and then fails. Why does the mock not work.

status_update and scripts folders are on same level.

I have tried to mock using patch and magic mock but it doesn't work the same.


Solution

  • I suppose that the file status_update/lib/sync_mdl_status.py contains the following import (if not, please, update your question and add the real import):

    from scripts.aws_secrets import fetch_aws_secret
    

    So you have to change your patch as following:

    @patch('scripts.aws_secrets.fetch_aws_secret')
    

    becomes:

    @patch('lib.sync_mdl_status.fetch_aws_secret')