Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mocking global variables on python doesn't work

Tags:

python

mocking

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?

like image 753
incognito Avatar asked Jan 28 '17 22:01

incognito


People also ask

How do you mock a global variable?

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.

Can you mock a variable in Python?

With a module variable you can can either set the value directly or use mock.

Why should we not use global variables in Python?

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.


1 Answers

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()
like image 129
chepner Avatar answered Oct 18 '22 14:10

chepner