While writing an article it occurred to me that it could be very useful to be able to use doctest to have unit tests in the method
Here is an example:
name = models.TextField()
>>> Person(name="Jane Doe")
<Person: Jane Doe>
Obviously now when running
doctest on a Django project this doesn’t work.
$ python3 -m doctest samples/models.py
I saw that in very old versions of Dajngo
doctest it was supported and then it was removed.
I think that having tests in the docstrings of the methods of a class could greatly simplify development, provide an immediate example of how to use the methods, following the principle of concentrating the information in one point and could also help newcomers to get started to write tests in their Django projects.
What do you think?
I think doctests are an antipattern for anything other than testing code examples in documentation to make sure they keep working. Specifically, they shouldn’t be part of your main testing strategy, especially as a beginner. I don’t think we should be adding anything to Django for this - if I understand correctly, this is why support was removed in 1.8.
Maybe there’s room to document how to integrate doctest and Django if the python docs on the subject are insufficient.
Yeah, I think this is probably right.
The romantic part of me misses doctests, but I think the tide has gone well away from it… — Q: are doctests really supported and developed in the stdlib still? I think not really… (like, they haven’t been removed but that’s about all we can say, unless I’ve missed something) so it’s tricky to suggest leaning hard into them in Django.
Actually, I wasn’t proposing to add support for
doctest in Django but only to describe how to use it for very trivial examples in the documentation.
I still think that in code samples or code snippets having the tests in a function’s docstrings can be very convenient and useful for TDD (eg. I used it them my AoC 2022 puzzle solutions)
I understood your feedback and your point of view. I don’t want to confuse others, especially newcomers, by encouraging them to use
doctests instead of “regular” tests.
I’m +0 on documenting how to use doctests with Django for testing documentation.
Gotcha. TBH I think it would be a confusion… — I’d love to see a blog post about it though! (I do think we lost something when doctest fell out of favour…)
I’d also like to read a blog post on this but am wary of adding anything to the official docs.
+1 to not adding it to official docs for the reasons already mentioned.