python2

时间:2016-04-23 19:54:38

标签: python python-2.7 pytest monkeypatching

我有一个名为square.py的模块:

import math

class Square(object):
    def __init__(radius):
        self.radius = radius

    def calculate_area(self):
        return math.sqrt(self.radius) * math.pi 

我已经使用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

在python 2中运行此测试给出了以下输出:

>       assert Square.calculate_area() ==  1
E       TypeError: unbound method <lambda>() must be called with Square instance as first argument (got nothing instead)

但是python 3中的相同测试通过了。你知道为什么会这样,我怎样才能修复这个测试以使用python 2?

2 个答案:

答案 0 :(得分:3)

你需要在一个instane上调用Square,但是你在{{1}}类上调用了它。你从未创建过一个正方形来计算面积。

答案 1 :(得分:1)

Python 2确保始终调用类上的方法,第一个参数是该类的实例(通常称为self)。

所以,期待这样的事情:

Square().calculate_area()
# Whih is equivalent to
Square.calculate_area(Square())

但这也会引发错误,因为它是一个意外的参数(TypeError: <lambda>() takes no arguments (1 given)

要阻止检查self参数,请使用staticmethod装饰器:

monkeypatch.setattr('test_class_pytest.Square.calculate_area', staticmethod(lambda: 1))