Pytest PropertyMock not returning different attribute values

21 Views Asked by At

I'm trying to mock an attribute of an object to return different values when invoked. Right now I have

class A:
   def __init__(self):
      self.a1 = [1, 1]
      self.a2 = [2, 2]
      self.a3 = [3, 3]
   def run(self):
      for i in self.a2:
         print(f"val in a2: {i}")

def test_A(mocker):
   myObj = A()
   myObj.a2 = mocker.PropertyMock(side_effect = [[2, 3], [3,4], [4,5]])
   myObj.run()

is giving TypeError: 'PropertyMock' object is not iterable

1

There are 1 best solutions below

0
Adam On BEST ANSWER

I found out that the way to do this is to grab the type of the object and mock the property of the type. The solution is therefore

def test_A(mocker):
    myObj = A()
    type(myObj).a2 = mocker.PropertyMock(
        side_effect=iter([[2, 3], [3, 4], [4, 5]])
    )
    myObj.run()