jeudi 4 mars 2021

Python test function decorator with a context manager - mock context manager

I have a decorator that uses a context manager that records some data:

# file1.py
from path.to.library import contextManager, helperClass

def record(metadata_1, metadata_2):
    def record_decorator(func):
        def wrapper(*args):
            with contextManager("contextName", helperClass):
                return func(*args)
        return wrapper
    return record_decorator

I would like to test this decorator by checking that the context manager starts and gets initialized with the correct parameters. Currently, I am trying the following:

@mock.patch("file1.contextManager")
@mock.patch("file1.helperClass")
def test_decorator(helperClass_mock, contextManager_mock):
    
    @record("data1", "data2")
    def helperFunction(param1):
        return param1

    helperFunction("just to test decorator")

    contextManager_mock().__enter__.assert_called_once()
    contextManager_mock.__init__.assert_called_once_with("contextName", helperClass_mock)
    

I am getting an error that says I am missing a required argument (by the argument name, I assume is the first param on the constructor of the contextManager). Any suggestion/help would be greatly appreciated

Aucun commentaire:

Enregistrer un commentaire