2016-09-25 113 views
1

一类的所有方法我已成立了一个单元测试,看来看去像电话:如何忽视或忽略为测试

from unittest import TestCase 
from . import main 
from PIL import Image 
class TestTableScreenBased(TestCase): 
def test_get_game_number_on_screen2(self): 
     t = main.TableScreenBased() 
     t.entireScreenPIL = Image.open('tests/1773793_PreFlop_0.png') 
     t.get_dealer_position() 

,我想测试被称为get_dealer_position功能。在这个功能我更新我的GUI中的某些项目未初始化的测试,所以我得到预期的错误:NameError: name 'ui_action_and_signals' is not defined

def get_dealer_position(self): 
    func_dict = self.coo[inspect.stack()[0][3]][self.tbl] 
    ui_action_and_signals.signal_progressbar_increase.emit(5) 
    ui_action_and_signals.signal_status.emit("Analyse dealer position") 
    pil_image = self.crop_image(self.entireScreenPIL, self.tlc[0] + 0, self.tlc[1] + 0, 
           self.tlc[0] +800, self.tlc[1] + 500) 

什么是“忽略”或覆盖的方法的所有调用的最佳方式在那个班ui_action_and_signals?这个类包含了很多方法(对于数百个gui项目),我不希望分别重写每一个。有没有办法告诉python测试应该忽略与ui_action_and_signals相关的所有内容?是否有任何优雅的方式与猴子修补或嘲笑将使用应用程序在此?

回答

2

如果您使用Python> = 3.3,则可以使用内置的unittest.mock模块。如果您使用的是较早版本的Python,则可以使用Pip安装the backport来使用相同的工具。

您将需要一个模拟对象,以取代丢失的依赖 - 有很多方法可以做到这一点,但一个方法是使用补丁装饰这需要在测试之后删除模拟对象的护理:

from unittest.mock import patch 
from unittest import TestCase 
from . import main 
from PIL import Image 
class TestTableScreenBased(TestCase): 
    @patch('module.path.of.ui_action_and_signals') 
    def test_get_game_number_on_screen2(self, mock_ui_action_and_signals): 
     t = main.TableScreenBased() 
     t.entireScreenPIL = Image.open('tests/1773793_PreFlop_0.png') 
     t.get_dealer_position() 

有关于修补程序修饰符in the official documentation的更多信息,包括一些hints on where to patch,有时不完全明显。

模拟系统还有许多其他功能,您可能想要使用它们,例如复制现有类的规格,或查找在测试过程中对您的Mock对象进行的调用。