0

I am trying to mock a method used in a global variable's format method in a module. The file I want to test is as follows:

do_work.py

from foo import bar

LINK = "foobar.com"

def generate_foobar():
    return "visit {}".format(bar(LINK))

FOOBAR = generate_foobar()

The bar function is defined as follows:

foo.py

def bar(link):
    return "<{}>".format(link)

Test is defined as follows:

test_foobar.py

import pytest

from do_work import LINK, generate_foobar

def test_foobar(mocker):
    mocker.patch("do_work.bar", return_value=LINK)
    from do_work import FOOBAR
    expected_value = "visit {}".format(LINK)
    assert generate_foobar() == expected_value # <- this assert passes
    assert FOOBAR == expected_value # <- this assert fails

Even after patching the function bar() the assert with GLOBAL VARIABLE fails. I am not sure why the method used in global variable is not mocked. Is there a way to mock this? Or is it something we can't patch as the function is executed in its own scope then the variable is imported as static value?

harsh8398
  • 36
  • 6
  • 1
    This will not work because `FOOBAR` is already set while importing `do_work`. Even if you move all imports after the `patch`, the module is still imported while it is patched, so that won't help either. – MrBean Bremen Oct 11 '20 at 11:45
  • @MrBeanBremen any workarounds? – harsh8398 Oct 13 '20 at 15:50
  • I don't see any without touching the tested code. This is generally a problem with globals - better avoid them if you want your code to be easily testable. Often a `reload` helps in such cases, but not if the mocked object is in the same module as the global as in this case. – MrBean Bremen Oct 13 '20 at 16:28
  • You can post a answer. I'll accept. This question was just part of the problem. But I got the answer that I needed. – harsh8398 Oct 15 '20 at 12:12
  • Well, I don't have a real solution, other than a hint how to improve the code. If you have solved the issue, you can post the solution as an answer. – MrBean Bremen Oct 15 '20 at 12:44

0 Answers0