0

This is a very stripped back version of what I want to do. It may not seem totally useful, but that is because I have stripped away all elements not pertinent to this question;

dummy.py

from another_mod import some_val

class Dummy:
    A_DICT = {
         'a': some_val*5,
         'b': some_val*10,
    }

    def some_func(self, x):
         return x*Dummy.A_DICT['a']

For testing purposes, I want to modify the value of the import some_val using mocking. Lets say that the unmocked value for some_val is 20.

test_dummy.py

import pytest
from dummy import Dummy

def test_some_func(mocker):
    mocker.patch('dummy.some_val',10)
    d = Dummy()
    assert d.some_func(5) == 250

However, this fails, as d.some_func(5) = 500, which is the result if the mock was not applied.

I have some idea this is because the class variable A_DICT is probably set before the mock is applied. If this is so, is there anyway to do what I am trying to do? I have used mocking before, and am aware of the difficulties that often arise from mocking stuff from the wrong place. However, this is a specific case that I haven't had to deal with before...

If the example seems useless and contrived, it is, but I was trying to reduce an example just down to this very specific issue.

wstk
  • 1,040
  • 8
  • 14
  • 1
    You have to reload the patched module after patching it, see for example [this answer](https://stackoverflow.com/a/61227784/12480730). It uses `monkeypatch` instead of `mocker`, but the semantics is the same. – MrBean Bremen Oct 13 '21 at 17:29
  • Ah, yes, so I had tried this already but with no luck. However, your suggestion caused me to relook at it, and it *does* work correctly, as long as the mocked path is changed properly to `mocker.patch('mod.some_val)`. I don't know for sure, but presumably mocking the value in `dummy` and then reloading the module just overwrites the mock (maybe?), whereas mocking where the value actually comes from, and then reloading gives the desired result. Thanks for pointing me in the right direction! – wstk Oct 13 '21 at 18:29
  • Precisely, glad I could help! – MrBean Bremen Oct 13 '21 at 18:31

0 Answers0