Reputation: 1914
Our group is working on a Python project. We want to make sure that some classes we create define their own __repr__ and __str__ methods and not just inherit from object or other classes. How can we test for it with unittest library?
Upvotes: 2
Views: 1178
Reputation: 49816
We want to make sure that some classes we create define their own
__repr__
and__str__
methods and not just inherit from object or other classes. How can we test for it with unittest library?
That's not a unit test. That's a coding convention.
What you should test is that their repr and str representations conform to your desired output. Regexes or exemplar text will be the easiest way to do this. Consider negative and positive tests (i.e. check that it is like what you want, and that it is not like the default python implementation).
Update: as @JonasWielicki notes: Abstract methods would be the programmatic way of enforcing the presence of such methods https://docs.python.org/2/library/abc.html#abc.abstractmethod. Note that it wouldn't force each level in the hierarchy to have their own method, but that would in any case be undesirable. Much better to write a sufficiently generic base implementation, and override only when necessary.
Upvotes: 1