Testing Python descriptors

假如想象 提交于 2019-12-11 09:23:05

问题


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.

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?

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

Any other tips would be appreciated.


回答1:


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()


来源:https://stackoverflow.com/questions/21754442/testing-python-descriptors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!