2

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?

asked Apr 23, 2016 at 19:54

2 Answers 2

3

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.

answered Apr 23, 2016 at 20:09
Sign up to request clarification or add additional context in comments.

Comments

2

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))
answered Aug 6, 2017 at 11:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.