I am trying to mock global variable using mock engine, but it seems that it doesn't simply work for my variables. When I patch for example os.name
it works perfectly fine, however for my custom variables it doesn't work.
Here is the code:
global_var.py
var = 10
use_global_var.py
from global_var import var
def test_call():
return var
test.py
import mock
from use_global_var import test_call
@mock.patch('global_var.var', 50)
def test_check():
print(test_call())
test_check()
print
is supposed to return 50 if I understand it right, but it returns 10.
Does anybody know what is the problem here and how to solve it?
If you need to mock a global variable for all of your tests, you can use the setupFiles in your Jest config and point it to a file that mocks the necessary variables. This way, you will have the global variable mocked globally for all test suites.
With a module variable you can can either set the value directly or use mock.
While in many or most other programming languages variables are treated as global if not declared otherwise, Python deals with variables the other way around. They are local, if not otherwise declared. The driving reason behind this approach is that global variables are generally bad practice and should be avoided.
You aren't mocking the right name. use_global_var.test_call
is looking at the name use_global_var.var
, but you are mocking global_var.var
.
@mock.patch('use_global_var.var', 50)
def test_check():
print(test_call())
test_check()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With