Question

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

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?

Was it helpful?

Solution

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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top