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?
-
4That seems like an odd thing to test for. If you want to ensure that the output looks good, then test that. If the desired output can be achieved by inheriting a generic implementation, why should this be prohibited? – May 05 '14 at 13:55
-
4You *can* do it (test for the presence of the name in the class `__dict__` dictionary) but as delnan says: why is this something you'd test for *at all*? – Martijn Pieters May 05 '14 at 13:56
-
This sounds more like a case for [abstract methods](https://docs.python.org/2/library/abc.html#abc.abstractmethod) rather than unittests. – Jonas Schäfer May 05 '14 at 14:58
1 Answers
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.

- 48,559
- 18
- 128
- 201