I have module named square.py:
import math
class Square(object):
def __init__(radius):
self.radius = radius
def calculate_area(self):
return math.sqrt(self.radius) * math.pi
And I have written test for this using py.test:
from square import Square
def test_mocking_class_methods(monkeypatch):
monkeypatch.setattr('test_class_pytest.Square.calculate_area', lambda: 1)
assert Square.calculate_area() == 1
Running this test in python 2 gives me the following output:
> assert Square.calculate_area() == 1
E TypeError: unbound method <lambda>() must be called with Square instance as first argument (got nothing instead)
But the same test in python 3 passes. Do you know why is that and how can I fix this test to work with python 2?
2 Answers 2
You need to call calculate_area() on an instane, but you called it on the Square class. You never created a square to calculate the area of.
Comments
Python 2 ensures that a method on a class is always called with the first argument being an instance of that class (Usually called self).
So, it is expecting something like this:
Square().calculate_area()
# Whih is equivalent to
Square.calculate_area(Square())
But this will also throw an error, as it is an unexpected argument (TypeError: <lambda>() takes no arguments (1 given))
To prevent checking for the self parameter, use the staticmethod decorator:
monkeypatch.setattr('test_class_pytest.Square.calculate_area', staticmethod(lambda: 1))
Comments
Explore related questions
See similar questions with these tags.