测试 Python 描述符 [英] Testing Python descriptors

查看:42
本文介绍了测试 Python 描述符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人有任何测试 Python 描述符的技巧或好的做法?

Does anyone have any tips or good practices for testing Python descriptors?

我正在编写一些描述符来封装数据验证,并希望为它们编写测试.

I'm writing some descriptors to encapsulate data validation and want to write tests for them.

一方面,我想知道是否应该通过在测试中创建描述符的实例然后显式调用 __get____set__ 方法来测试它们.

For one thing, I'm wondering if I should test them by creating instances of the descriptors in my tests and then calling the __get__ or __set__ methods explicitly.

或者我应该在我的测试文件中创建一个使用描述符类的特殊类,然后在我的测试中使用那个类?

Or should I create a special class in my test file which uses the descriptor class and then use that class in my tests?

或者我应该将描述符添加到我的 unittest.TestCase 子类中吗?

Or should I add the descriptor to my subclass of unittest.TestCase?

任何其他提示将不胜感激.

Any other tips would be appreciated.

推荐答案

我会直接调用描述符方法.您正在对描述符进行单元测试,而不是 Python 通常如何使用描述符.

I'd call the descriptor methods directly. You are unit testing the descriptors, not how Python uses descriptors in general.

这样,您还可以更好地控制传入的内容;你可以模拟出你的心内容的类型和实例参数.

That way, you also have far more control over what exactly gets passed in; you can mock out the type and instance arguments to your hearts content.

import unittest


class MockClass(object):
    # add any methods to assert access here


class DescriptorTests(unittest.TestCase):
    def _make_one(self, *args, **kw):
        from original_module import DescriptorClass
        return DescriptorClass(*args, **kw)

    def test_class_access(self):
        # only a type is passed in, no instance
        desc = self._make_one()
        res = desc.__get__(None, MockClass)
        self.assertEqual(res.someattribute, 'somevalue')

    # etc.  


if __name__ == '__main__':
    unittest.main()

这篇关于测试 Python 描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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