I just learned about python's descriptors, and I think they might be just the thing to solve a problem I have. I would like to write tests for the descriptor class I wrote and I found another post with some example code, but I don't really understand it.
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()
Two questions. First, what's the purpose of MockClass
? I simply wrote
class MockClass(object):
pass
and the tests seem to work. Does MockClass
need to have any functionality?
Second, what's the purpose of the DescriptorTests._make_one
method? Why not import DescriptorClass
right after unittest
and then create an instance of the descriptor within DescriptorTests.test_class_access
like so:
import unittest
from original_module import DescriptorClass
class DescriptorTests(unittest.TestCase):
def test_class_access(self):
desc = DescriptorClass()
# other code
Thanks in advance.
Background, FWIW
I'm writing a program that models a physical phenomenon and so I am writing classes that require several public data attributes that behave like physical properties. For example, my class needs a temperature
attribute that store's the object's temperature in Kelvin. Negative values of temperature in Kelvin make no sense. Other physical properties have similar constraints (negative values of mass make no sense, etc.). Instead of writing a bunch of essentially the same @property
s, I have abstracted this functionality into a descriptor class.
I have written a PhysicalProperty
descriptor class that is supposed to take a lower bound when instantiated and raise an exception if the user tries to set the value less than the lower bound. I want to test PhysicalProperty
to make sure it throws the exception appropriately.