[Python] Difference between mock.patch.dict as function decorator and context manager in...

Discussão em 'Python' iniciado por Stack, Maio 23, 2025.

  1. Stack

    Stack Membro Participativo

    I have a configuration module, config with data config.data where I want to add a value for testing. Ideally, I want to use mock.patch.dict as a context manager because the value is a class attribute and I need to use self.test_value. The problem is it doesn't work. The dict patching only works when used as a decorator, but not when used as a context manager and I can't figure out why.

    This is more or less what I have:

    This works:

    @mock.patch.dict("config.data", {"test": 123})
    @mock.patch("config.load_data", return_value=None, autospec=True)
    def run(self, m_load, *args, **kwargs):
    return super().run(*args, **kwargs)


    This doesn't work:

    def run(self, *args, **kwargs):
    with mock.patch.dict("config.data", {"test": 123}) and mock.patch(
    "config.load_data", return_value=None, autospec=True
    ) as m_load:
    return super().run(*args, **kwargs)


    The config.load_data is patched so the data doesn't reload, and the module is sort of a singleton.

    Continue reading...

Compartilhe esta Página