如何在 Python 中为类方法编写存根 [英] How to write a stub for a classmethod in Python

查看:37
本文介绍了如何在 Python 中为类方法编写存根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法调用另一个类的类方法

I have a method which calls for a classmethod of another class

def get_interface_params_by_mac(self, host, mac_unified):
        lines = RemoteCommand.remote_command(host, cls.IFCONFIG)

...

class RemoteCommand(object):

    @classmethod
    def remote_command(cls, host, cmd, sh = None):
    ...

我将为 get_interface_params_by_mac 方法编写一个单元测试,我想在其中更改 remote_command 的实现(我认为它调用 stub - fix如果我错了,我)

I'm going to write a unit test for get_interface_params_by_mac method, in which I'd like to change an implementation of remote_command (I think it calls stub - fix me if I wrong)

在 Python 中执行此操作的正确方法是什么?

What the right way to do this in Python?

推荐答案

你的单元测试代码(可能在它的 setUp 方法中,如果这在多个测试方法中需要并且因此有资格作为夹具) 应该这样做:

Your unit-test code (maybe in its setUp method, if this is needed across several test methods and thus qualifies as a fixture) should do:

def fake_command(cls, host, cmd, sh=None):
  pass  # whatever you want in here
self.save_remote_command = somemodule.RemoteCommand.remote_command
somemodule.RemoteCommand.remote_command = classmethod(fake_command)

然后通过

somemodule.RemoteCommand.remote_command = self.save_remote_command 

测试后并不总是需要把东西放回去,但这是一个很好的一般做法.

It's not always necessary to put things back after a test, but it's good general practice.

更优雅的方法是通过依赖注入 (DI) 模式设计可测试性代码:

A more elegant approach would be to design your code for testability via the Dependency Injection (DI) pattern:

def __init__(self, ...):
   ...
   self.remote_command = RemoteCommand.remote_command
   ...

def set_remote_command_function(self, thefunction):
   self.remote_command = thefunction

def get_interface_params_by_mac(self, host, mac_unified):
        lines = self.remote_command(host, cls.IFCONFIG)

DI 以很低的成本为您提供了很大的灵活性(在可测试性方面,但在许多其他情况下也是如此),这使其成为我最喜欢的设计模式之一(我宁愿尽可能避免猴子修补).当然,如果您将被测代码设计为使用 DI,则您在测试中需要做的就是通过使用您想要使用的任何伪函数调用实例的 set_remote_command_function 来适当地准备该实例!

DI buys you a lot of flexibility (testability-wise, but also in many other contexts) at very little cost, which makes it one of my favorite design patterns (I'd much rather avoid monkey patching wherever I possibly can). Of course, if you design your code under test to use DI, all you need to do in your test is appropriately prepare that instance by calling the instance's set_remote_command_function with whatever fake-function you want to use!

这篇关于如何在 Python 中为类方法编写存根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆