如何模拟Python静态方法和类方法

时间:2014-04-24 00:07:48

标签: python unit-testing mocking

如何模拟具有未绑定方法的类?例如,此类有@classmethod@staticmethod

class Calculator(object):
    def __init__(self, multiplier):
        self._multiplier = multiplier
    def multiply(self, n):
        return self._multiplier * n
    @classmethod
    def increment(cls, n):
        return n + 1
    @staticmethod
    def decrement(n):
        return n - 1

calculator = Calculator(2)
assert calculator.multiply(3) == 6    
assert calculator.increment(3) == 4
assert calculator.decrement(3) == 2
assert Calculator.increment(3) == 4
assert Calculator.decrement(3) == 2

上面几乎描述了我的问题。以下是一个工作示例,演示了我尝试过的事情。

班级Machine包含Calculator的实例。我将使用模拟Machine来测试Calculator。为了演示我的问题,Machine通过Calculator的实例和Calculator类调用未绑定的方法:

class Machine(object):
    def __init__(self, calculator):
        self._calculator = calculator
    def mult(self, n):
        return self._calculator.multiply(n)
    def incr_bound(self, n):
        return self._calculator.increment(n)
    def decr_bound(self, n):
        return self._calculator.decrement(n)
    def incr_unbound(self, n):
        return Calculator.increment(n)
    def decr_unbound(self, n):
        return Calculator.decrement(n)

machine = Machine(Calculator(3))
assert machine.mult(3) == 9

assert machine.incr_bound(3) == 4
assert machine.incr_unbound(3) == 4

assert machine.decr_bound(3) == 2
assert machine.decr_unbound(3) == 2

上面的所有功能代码都可以正常工作。接下来是不起作用的部分。

我创建了一个Calculator模拟器,用于测试Machine

from mock import Mock

def MockCalculator(multiplier):
    mock = Mock(spec=Calculator, name='MockCalculator')

    def multiply_proxy(n):
        '''Multiply by 2*multiplier instead so we can see the difference'''
        return 2 * multiplier * n
    mock.multiply = multiply_proxy

    def increment_proxy(n):
        '''Increment by 2 instead of 1 so we can see the difference'''
        return n + 2
    mock.increment = increment_proxy

    def decrement_proxy(n):
        '''Decrement by 2 instead of 1 so we can see the difference'''
        return n - 2
    mock.decrement = decrement_proxy

    return mock

在下面的单元测试中,绑定的方法使用了MockCalculator,正如我所希望的那样。但是,对Calculator.increment()Calculator.decrement()的调用仍使用Calculator

import unittest

class TestMachine(unittest.TestCase):
    def test_bound(self):
        '''The bound methods of Calculator are replaced with MockCalculator'''
        machine = Machine(MockCalculator(3))
        self.assertEqual(machine.mult(3), 18)
        self.assertEqual(machine.incr_bound(3), 5)
        self.assertEqual(machine.decr_bound(3), 1)

    def test_unbound(self):
        '''Machine.incr_unbound() and Machine.decr_unbound() are still using
        Calculator.increment() and Calculator.decrement(n), which is wrong.
        '''
        machine = Machine(MockCalculator(3))
        self.assertEqual(machine.incr_unbound(3), 4)    # I wish this was 5
        self.assertEqual(machine.decr_unbound(3), 2)    # I wish this was 1

所以我尝试修补Calculator.increment()Calculator.decrement()

def MockCalculatorImproved(multiplier):
    mock = Mock(spec=Calculator, name='MockCalculatorImproved')

    def multiply_proxy(n):
        '''Multiply by 2*multiplier instead of multiplier so we can see the difference'''
        return 2 * multiplier * n
    mock.multiply = multiply_proxy
    return mock

def increment_proxy(n):
    '''Increment by 2 instead of 1 so we can see the difference'''
    return n + 2

def decrement_proxy(n):
    '''Decrement by 2 instead of 1 so we can see the difference'''
    return n - 2


from mock import patch

@patch.object(Calculator, 'increment', increment_proxy)
@patch.object(Calculator, 'decrement', decrement_proxy)
class TestMachineImproved(unittest.TestCase):
    def test_bound(self):
        '''The bound methods of Calculator are replaced with MockCalculator'''
        machine = Machine(MockCalculatorImproved(3))
        self.assertEqual(machine.mult(3), 18)
        self.assertEqual(machine.incr_bound(3), 5)
        self.assertEqual(machine.decr_bound(3), 1)

    def test_unbound(self):
        '''machine.incr_unbound() and Machine.decr_unbound() should use
        increment_proxy() and decrement_proxy(n).
        '''
        machine = Machine(MockCalculatorImproved(3))
        self.assertEqual(machine.incr_unbound(3), 5)
        self.assertEqual(machine.decr_unbound(3), 1)

即使在修补之后,未绑定的方法也需要Calculator的实例作为参数:

  

TypeError:必须使用Calculator实例作为第一个参数调用未绑定方法in​​crement_proxy()(改为使用int实例)

如何模拟类方法Calculator.increment()和静态方法Calculator.decrement()

4 个答案:

答案 0 :(得分:5)

你正在修补错误的对象。您必须修补Calculator课程中的Machine,而不是普通Calculator课程。阅读它here

from mock import patch
import unittest

from calculator import Calculator
from machine import Machine


class TestMachine(unittest.TestCase):
    def my_mocked_mult(self, multiplier):
        return 2 * multiplier * 3
    def test_bound(self):
        '''The bound methods of Calculator are replaced with MockCalculator'''
        machine = Machine(Calculator(3))
        with patch.object(machine, "mult") as mocked_mult:
            mocked_mult.side_effect = self.my_mocked_mult
            self.assertEqual(machine.mult(3), 18)
            self.assertEqual(machine.incr_bound(3), 5)
            self.assertEqual(machine.decr_bound(3), 1)

    def test_unbound(self):
        '''Machine.incr_unbound() and Machine.decr_unbound() are still using
        Calculator.increment() and Calculator.decrement(n), which is wrong.
        '''
        machine = Machine(Calculator(3))
        self.assertEqual(machine.incr_unbound(3), 4)    # I wish this was 5
        self.assertEqual(machine.decr_unbound(3), 2)    # I wish this was 1

答案 1 :(得分:0)

一种方法是

def test_increment(mocker):
    mocker.patch.object(Calculator, attribute='increment', return_value=10)
    ...actual test code...

答案 2 :(得分:0)

我只是做了一些可以转化为你的案例的事情:

class BaseFile(UidMixin, BaseModel):
    __metaclass__ = ABCMeta

    upload_directory = ""

    def generate_filename(self, filename):
        return "uploads/"


class SeamlessFile(BaseFile):
    def generate_filename(self, filename):
        return os.path.join("seam/", basename(filename))

    actual_file = models.FileField(
        default=None, null=True, blank=True,
        upload_to=generate_filename,
    )


class FrontEndAuditFile(SeamlessFile):
    def generate_filename(self, filename):
        print("FrontEndAuditFile -> generate_filename")
        return os.path.join("fro/", basename(filename))

然后,在您的测试中,像这样简单的事情:

class Calculator_Mock(object):
    def __init__(self, multiplier):
        ... # add whatever you need here

    def multiply(self, n):
        ... # add whatever you need here

    @classmethod
    def increment(self, n):
        ... # add whatever you need here

答案 3 :(得分:-1)

C#,Java和C ++程序员倾向于过度使用Python中的类和静态方法。 Pythonic方法是使用模块函数。

首先,这是测试中的重构软件,方法increment()decrement()作为模块函数。界面确实改变了,但功能是相同的:

# Module machines

class Calculator(object):
    def __init__(self, multiplier):
        self._multiplier = multiplier
    def multiply(self, n):
        return self._multiplier * n

def increment(n):
    return n + 1

def decrement(n):
    return n - 1

calculator = Calculator(2)
assert calculator.multiply(3) == 6
assert increment(3) == 4
assert decrement(3) == 2


class Machine(object):
    '''A larger machine that has a calculator.'''
    def __init__(self, calculator):
        self._calculator = calculator
    def mult(self, n):
        return self._calculator.multiply(n)
    def incr(self, n):
        return increment(n)
    def decr(self, n):
        return decrement(n)

machine = Machine(Calculator(3))
assert machine.mult(3) == 9
assert machine.incr(3) == 4
assert machine.decr(3) == 2

向模拟increment_mock()decrement_mock()添加函数increment()decrement()

from mock import Mock
import machines

def MockCalculator(multiplier):
    mock = Mock(spec=machines.Calculator, name='MockCalculator')

    def multiply_proxy(n):
        '''Multiply by 2*multiplier instead of multiplier so we can see the
        difference.
        '''
        return 2 * multiplier * n
    mock.multiply = multiply_proxy

    return mock

def increment_mock(n):
    '''Increment by 2 instead of 1 so we can see the difference.'''
    return n + 2

def decrement_mock(n):
    '''Decrement by 2 instead of 1 so we can see the difference.'''
    return n - 2

现在好的部分。修补程序increment()decrement()用它们的模拟替换它们:

import unittest
from mock import patch
import machines

@patch('machines.increment', increment_mock)
@patch('machines.decrement', decrement_mock)
class TestMachine(unittest.TestCase):
    def test_mult(self):
        '''The bound method of Calculator is replaced with MockCalculator'''
        machine = machines.Machine(MockCalculator(3))
        self.assertEqual(machine.mult(3), 18)

    def test_incr(self):
        '''increment() is replaced with increment_mock()'''
        machine = machines.Machine(MockCalculator(3))
        self.assertEqual(machine.incr(3), 5)

    def test_decr(self):
        '''decrement() is replaced with decrement_mock()'''
        machine = machines.Machine(MockCalculator(3))
        self.assertEqual(machine.decr(3), 1)