Search code examples
python-3.xpytestpytest-mock

Not able to create mock object using mocker


I am trying to create mock object for unit testing but somehow always actual object is called. Below is the code for reference:-

  1. utility_functions.py
import os
import json


def get_module_configurations(key):
    config = os.getcwd()
    config = config + "\\xyz.json"
    with open(config) as f:
        module_config = json.load(f)
    module_config = module_config[key]
    return module_config

  1. load_class
from importlib import import_module
from inspect import isclass, isabstract


def load_module(data):
    package_path = data['Package']
    module_name = data['ModuleName']
    class_name = data['ClassName']

    try:
        module_name = str(module_name.split('.py')[0])
        module = import_module('.' + module_name, package_path)

    except Exception as error:
        pass

    try:
        _class = getattr(module, class_name)
    except Exception as error:
        pass
    if isclass(_class) and not (isabstract(_class)):
        return _class
    else:
        return None

  1. function1.py
import load_class
from utility_functions import get_module_configurations


def load_helpers(task_name):
    module = get_module_configurations(task_name)
    cls = load_class.load_module(module)
    return cls
  1. test_function.py
import pytest
from function1 import load_helpers


def test_mock(mocker):
    class_to_load = {"Package": "Test", "ModuleName": "default_class.py", "ClassName": 
                    "DefaultClass"}
    mocker.patch('function1.load_helpers', return_value= class_to_load)
    result = load_helpers('c')
    assert result is not None

Since I am mocking, load helpers should not be called but it always calls actual implementation saying path is invalid.

I am missing something basic but cannot figure out what. Any help will be great.


Solution

  • If you are importing the function into your module (from function1 import load_helpers), you need to patch it as if it was part of it. This means that instead of...

    mocker.patch('function1.load_helpers', return_value=class_to_load)
    

    ...you should use...

    mocker.patch('test_function.load_helpers', return_value=class_to_load)
    

    PS: I assume that you are just practicing mocking because otherwise your test function doesn't make sense.