The Python Oracle

Python - doctest vs. unittest

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Book End

--

Chapters
00:00 Question
00:26 Accepted answer (Score 194)
01:27 Answer 2 (Score 50)
02:03 Answer 3 (Score 37)
02:25 Answer 4 (Score 32)
03:44 Thank you

--

Full question
https://stackoverflow.com/questions/3616...

Accepted answer links:
[nose]: https://pypi.python.org/pypi/nose/

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #unittesting #comparison #doctest

#avk47



ACCEPTED ANSWER

Score 194


Both are valuable. I use both doctest and nose taking the place of unittest. I use doctest for cases where the test is giving an example of usage that is actually useful as documentation. Generally I don't make these tests comprehensive, aiming solely for informative. I'm effectively using doctest in reverse: not to test my code is correct based on my doctest, but to check that my documentation is correct based on the code.

The reason is that I find comprehensive doctests will clutter your documentation far too much, so you will either end up with either unusable docstrings, or incomplete testing.

For actually testing the code, the goal is to thoroughly test every case, rather than illustrate what is does by example, which is a different goal which I think is better met by other frameworks.




ANSWER 2

Score 50


I use unittest almost exclusively.

Once in a while, I'll put some stuff in a docstring that's usable by doctest.

95% of the test cases are unittest.

Why? I like keeping docstrings somewhat shorter and more to the point. Sometimes test cases help clarify a docstring. Most of the time, the application's test cases are too long for a docstring.




ANSWER 3

Score 38


Another advantage of doctesting is that you get to make sure your code does what your documentation says it does. After a while, software changes can make your documentation and code do different things. :-)




ANSWER 4

Score 14


If you're just getting started with the idea of unit testing, I would start with doctest because it is so simple to use. It also naturally provides some level of documentation. And for more comprehensive testing with doctest, you can place tests in an external file so it doesn't clutter up your documentation.

I would suggest unittest if you're coming from a background of having used JUnit or something similar, where you want to be able to write unit tests in generally the same way as you have been elsewhere.