如何在python中模拟依赖 [英] how to mock dependency in python

查看:46
本文介绍了如何在python中模拟依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 python 单元测试框架的新手,在模拟依赖方面有很多困惑.

I am new to python unit testing framework and lot of confusion in mocking dependency.

我正在尝试为类的以下成员函数编写单元测试,(check_something()):

I am trying to write unit tests for below member function of a class, (check_something()):

class Validations:    
    def check_something(self):
        abc = os.environ['PLATFORM']
        xyz = Node()
        no_of_nodes = len(xyz.some_type_var)
        if abc != "X_PLATFORM" or no_of_nodes != 1:
            raise someException()

我们如何消除依赖?

  1. 需要模拟 Node() 吗?
  2. 我们如何确保为 abc 分配了 X_PLATFORM ?
  3. 如何给变量no_of_nodes赋值1?这反过来又派生自 Node() 对象.

  1. Need to mock Node() ?
  2. How do we make sure abc is assigned with X_PLATFORM ?
  3. How to assign value 1 to variable no_of_nodes? which is in turn derived from Node() object.

class Node(object):
    def __init__(self):
        self.nodes = DEF()
        self.some_type_var = someclass().getType()
        self.localnode = os.environ['HOSTNAME']
        self.peertype = self.get_peer_type()

    def get_peer_type(self):
        return node

我尝试在单元测试下编写.我无法检查失败和通过条件.我不确定它是否正确.

I tried writing below unit test. I am unable to check for fail and pass condition. I am not sure whether it is correct or not.

class TestValidation(unittest.TestCase):

    @mock.patch.object(Node, "get_peer_type")
    @mock.patch('somefile.Node', spec=True)
    def test_1(self, mock_object1, mock_object2):
        os.environ['PLATFORM'] = 'X_PLATFORM'
        obj = Validations()
        self.assertRaises(someException, obj.check_something)

验证类使用 Node() 类对象,Node 类使用其他类.

Validation class uses Node() Class object and Node class uses some other class.

  1. 如何根据条件确定是否引发异常?

推荐答案

是的,您可以模拟被测代码单元外部的任何内容.这里的意思是 os.environ 字典和 Node() 类.

Yes, you'd mock anything external to the unit of code under test. Here that means the os.environ dictionary and the Node() class.

补丁需要应用到你的代码所在的模块;@mock.patch('somefile.Node', spec=True) 如果 somefileValidations 是同一个模块,则正确;请参阅在哪里打补丁部分 至于为什么会这样.

The patch needs to be applied to the module your code is in; @mock.patch('somefile.Node', spec=True) is correct if somefile is the same module as Validations; see the Where to patch section as to why that is.

我不确定在这里使用 spec=True 是否有帮助;你的 Node 属性都是在 Node.__init__ 中创建的实例属性,所以它们在 class 上不可用,这就是规范的内容.请参阅 autospeccing 部分,了解如何克服该问题,如果你真的想设置一个规范.

I'm not sure that using spec=True is all that helpful here; your Node attributes are all instance attributes created in Node.__init__, so they are not available on the class, which is what informs the spec. See the section on autospeccing on how to overcome that if you really want to set a spec.

abc 是从 os.environ 设置的,你可以使用 patch.dict() 对象 根据您的需要修补该字典.

abc is set from os.environ, you can use the patch.dict() object to patch that dictionary for your needs.

xyz = len(xyz.some_type_var) 只需将 some_type_var 属性设置为具有正确长度的对象, 通过设置 xyz.some_type_var.__len__.return_value,因为它是为 len() 调用的 xyz.some_type_var.__len__() 方法代码>函数.

The xyz = len(xyz.some_type_var) is simply handled by either setting the some_type_var attribute to an object with the right length, or by setting xyz.some_type_var.__len__.return_value, since it is the xyz.some_type_var.__len__() method that is called for the len() function.

因此,要进行测试,您可以:

So, to test, you'd do:

class TestValidation(unittest.TestCase):
    @mock.patch('somefile.Node')
    def test_1(self, mock_node):
        # set up the Node() instance, with the correct length
        node_instance = mock_node.return_value
        node_instance.some_type_var.__len__ = 2
        # or, alternatively, node_instance.some_type_var = (1, 2)

        # set up os.environ['PLATFORM']
        with mock.patch.dict('os.environ', PLATFORM='X_PLATFORM'):
            obj = Validations()
            with self.assertRaises(someException):
                obj.check_something()

这篇关于如何在python中模拟依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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