incognito
incognito

Reputation: 457

mocking global variables on python doesn't work

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?

Upvotes: 7

Views: 7044

Answers (1)

chepner
chepner

Reputation: 530872

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()

Upvotes: 13

Related Questions