1

When I run my pytest and mock patch a global variable in the python file that has a function call assigned to capture the output, I'm unable to mock it (I dont want to actually execute the function during tests). I find that the function is still getting called. How can I prevent it from being called?

file 1: /app/file1.py
def some_func():
 return "the sky is like super blue"

file 2: /app/file2.py
from app.file1 import some_func
VAR1 = some_func()

file 3: /tests/app/test_file2.py
import mock
import pytest
from app.file2 import VAR1

@mock.patch('app.file2.VAR1', return_value=None)
def test_file_2_func(baba_fake_val):
  print('made it to my test :)'
  print(VAR1)

1 Answer 1

2
  1. VAR = some_func() will be executed when you import app.file2, so you have to mock before importing it if you want to prevent som_func call.
  2. In order to prevent this function call you have to mock some_func, not VAR1 like this:
import mock
import pytest
import app.file1

@mock.patch('app.file1.some_func', return_value=None)
def test_file_2_func(baba_fake_val):
  from app.file2 import VAR1
  print('made it to my test :)'
  print(VAR1)
Sign up to request clarification or add additional context in comments.

1 Comment

If there are multiple tests involving app.file2, though, the module will only be evaluated once, meaning the value supplied by this patch will apply to anyone else trying to import the same module (needing either the "real" value or a different patched value).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.