天天看點

python 存根_如何用Python編寫類方法的存根

您的單元測試代碼(可能在它的setUp方法中,如果這是跨多個測試方法所需要的,是以可以作為fixture來使用)應該: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)

然後撤銷這個monkey更新檔(例如,如果更新檔是在setUp中完成的,則在tearDown方法中)通過

^{pr2}$

考試後不一定要把東西放回去,但這是很好的一般做法。在

更優雅的方法是通過依賴注入(DI)模式設計代碼的可測試性: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以極低的成本為您帶來了很大的靈活性(測試性方面,但在許多其他環境中也是如此),這使得它成為我最喜歡的設計模式之一(我甯願盡可能避免monkey-patching)。當然,如果您将測試中的代碼設計為使用DI,那麼您在測試中需要做的就是通過調用執行個體的set_remote_command_function來适當地準備該執行個體,無論您想使用什麼僞函數!在