1

I have a test file where I'm mocking a function to return a boolean value. For example, file1.py is in a directory called service.

file1.py

def is_development():
    return is_not_other_env() or is_not_other_other_env()

APP_ENVIRONMENT = 'development' is is_development() else 'production'

And then the test file is to test that the variable APP_ENVIRONMENT is what I expect it to be. test_file1.py

from service import file1
from unittest.mock import patch

@patch('service.file1.is_development', return_value=False)
def test_app_environment_prod():
     assert file1.APP_ENVIRONMENT == 'production'

But this test fails. I thought maybe I needed to reload the import so I used importlib to reload the module after patching but the test still fails.

Why does the patch fail here?

When I call the function directly after patching it does return False as I patched it, but when accessing the variable which should run the function with the patch it fails.

ti7
  • 16,375
  • 6
  • 40
  • 68
Paul
  • 1,101
  • 1
  • 11
  • 20
  • Depending on how you import `is_development`, your patch string is probably wrong, see [where to patch](https://docs.python.org/3/library/unittest.mock.html#where-to-patch). – MrBean Bremen Aug 11 '22 at 04:50
  • The problem is that `is_development` is being called when you import `file1` before doing the patch. – aarcas Nov 03 '22 at 16:55

0 Answers0