Ram
Ram

Reputation: 319

Mock a global variable in python

I have a function in main module which takes in two values and performs opertaions on them.This uses a global variable which is created before calling this function

def calc(keys,values):
    if globalvar == "calc":
        return sum(keys)
    else:
        return sum(values)

Now in unittesting

class Testcalc(TestCase):
@mock.patch('module.globalvar ', "calc")
def test_unit(self,calc):
    keys=[1,2,3]
    values=[4,5,6]
    sum=module.calc(keys,values)
    """
    check asserts
    """

I am getting an type error with invalid arguments.

TypeError('test_unit() takes exactly 2 arguments (1 given)',)

Could anyone show me the correct way of mocking the global variable

Update: This worked for me not sure why

class Testcalc(TestCase):
@mock.patch('module.globalvar')
def test_unit(self,var):
    keys=[1,2,3]
    values=[4,5,6]
    var="calc"
    sum=module.calc(keys,values)
    """
    check asserts
    """

Thank you everyone

Upvotes: 5

Views: 12994

Answers (1)

Gang
Gang

Reputation: 2778

A module.globalvar = 'anything' should be enough, no need to mock.patch

def test_calc2(self):
    keys = [1, 2, 3]
    values = [4, 5, 6]

    module.globalvar = "calc"
    sum = module.calc(keys, values)
    self.assertEqual(module.globalvar, 'calc')
    self.assertEqual(sum, 6)

    module.globalvar = 'other'
    sum = module.calc(keys, values)
    self.assertEqual(sum, 15)

This works using PropertyMock

@mock.patch('module.globalvar', new_callable=mock.PropertyMock)
def test_calc3(self, mocked_globalvar):

This is syntax right, but will fail the test, since the globalvar has to be set by PropertyMock

@mock.patch('module.globalvar')
def test_unit(self, mock_globalvar):

Upvotes: 9

Related Questions