Python: how to make fun of class attribute initialization function

I would like to make fun of the module level function used to initialize a class attribute (not an instance). Here's a simplified example:

# a.py    
def fn(): 
    return 'asdf'

class C:
    cls_var = fn()

Here unittest tries to do mock a.fn ():

# test_a.py 
import unittest, mock
import a

class TestStuff(unittest.TestCase):
    # we want to mock a.fn so that the class variable
    # C.cls_var gets assigned the output of our mock

    @mock.patch('a.fn', return_value='1234')
    def test_mock_fn(self, mocked_fn):
        print mocked_fn(), " -- as expected, prints '1234'"
        self.assertEqual('1234', a.C.cls_var) # fails! C.cls_var is 'asdf'

I believe that the problem is where to fix it , but I tried both import options with no luck. I even tried moving the import statement to test_mock_fn (), so that the mocked a.fn () will exist before aC enters the scope - no, it still fails.

Any understanding would be greatly appreciated!

+4
source share
2 answers

, , , fn() . , , , .

, , , , .

, , :

def fn():
    print("I have run")
    return "asdf"

, a , , , I have run , a.

, , . PropertyMock, , , :

@mock.patch('a.C.cls_var', new_callable=PropertyMock)
def test_mock_fn(self, mocked_p):
    mocked_p.return_value = '1234'

    self.assertEqual('1234', a.C.cls_var)

, , , fn, "1234" cls_var PropertyMock, .

(, , ) , . , , , C, , .

, :

class C:
    def __init__(self):
        self.var = fn()

:

@mock.patch('a.fn', return_value='1234')
def test_mock_fn(self, mocked_p):
    self.assertEqual('1234', a.C().var)
+2

@idjaw , , , , - a.C.cls_var .

@mock.patch('a.C.cls_var', '1234')

, : use PropertyMock , , .

, , @idjaw.

0

Source: https://habr.com/ru/post/1629729/


All Articles