2

I need to test a code that has a global variable which is populated by a function that returns a value after making a connection to external server. For the pytest, I need to figure out a way so that the function does not get called.

I've tried patching both the global variable and the function, but neither worked.

Here's the python code - my_module.py:

import datetime

# %%
def server_function_1 ():
    try:
        return_val = "Assume the external server function returns a string"
    except Exception as e:
        print("Failed")
        print(e)
        raise e
    else:
        return return_val
    finally:
        # assume when called from the testing environment, the server connection will raise a exception
        raise Exception("Cannot connect to server")

global_result_of_server_func = server_function_1()

# %%
def get_current_datetime_str():
    return datetime.datetime.now().strftime('%Y%m%d.%H%M%S.%f')

# %%
def some_function():
    return global_result_of_server_func, get_current_datetime_str()

Here's the pytest file - test_my_module.py:

# %%
import pytest
from unittest import mock
import datetime
import logging
import sys

# %%
import my_module

logger = logging.getLogger(__name__)

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)

frozen_time = datetime.datetime(year=2022, month=6, day=1, hour=1, minute=0, second=0, microsecond=0)
mock_server_str = "Mock Server String"


# %%
class TestMyModule () :
    def test_handler_1 (self):
        with mock.patch("my_module.get_current_datetime_str", return_value=frozen_time.strftime('%Y%m%d.%H%M%S.%f')), \
            mock.patch("my_module.global_result_of_server_func", new=mock_server_str):
            test_server_val, test_frozen_time = my_module.some_function()
            assert test_frozen_time == frozen_time.strftime('%Y%m%d.%H%M%S.%f')
            assert test_server_val == mock_server_str
    def test_handler_2 (self):
        with mock.patch("my_module.get_current_datetime_str", return_value=frozen_time.strftime('%Y%m%d.%H%M%S.%f')), \
            mock.patch("my_module.server_function_1", return_value=mock_server_str):
            test_server_val, test_frozen_time = my_module.some_function()
            assert test_frozen_time == frozen_time.strftime('%Y%m%d.%H%M%S.%f')
            assert test_server_val == mock_server_str

What I am trying to achieve is that variable global_result_of_server_func gets the mock value, and the function server_function_1 doesn't get called and tries to make a connection to the server.

Thanks.

Delaying the import like the suggestion in this question didn't seem to make any difference.

Kevin Tianyu Xu
  • 646
  • 2
  • 8
  • 15
  • 3
    Does this answer your question? [Mock function called on import](https://stackoverflow.com/questions/22616934/mock-function-called-on-import) – STerliakov Jul 24 '22 at 11:12

0 Answers0