doctest with Python
At home I'm translating some C++ code to Python for doing 3-D math with vectors and matrices. (Yes, I know about NumPy -- I have my reasons.) Matrix math requires care to get all the indices right, and it's a good application for writing tests to make sure I've done things correctly.
About the same time as I started this project, I saw the following response from Fredrik Lundh (effbot) to a comment on Reddit:
Of course, Fredrik here is referring to the doctest module. I'd seen Peter Norvig use it before in some of his Python code, and I should've paid attention then. Fredrik's comment gave me the push to finally try it. I found that it fits my style of Python coding very naturally, since I typically shake down my code at the REPL as I go. I cut and paste my interactions at the prompt into my class, and I've got some tests up and running quickly. The nice thing is that I'm helping to document my code (inline) as I go, which is a second advantage of doctest. I've never been that enamored with writing a separate test class like I've tried with the unittest library, for instance.
Good stuff. Thanks, Fredrik.
About the same time as I started this project, I saw the following response from Fredrik Lundh (effbot) to a comment on Reddit:
>what was I thinking using self.assertEqual() in Python?!
Yeah, what were you thinking? Here's how it's spelled in Python, when using the One True Testing Tool (wink):
>>> foo.bar
3
(where all you actually typed was foo.bar; the rest is just good old cut and paste).
Of course, Fredrik here is referring to the doctest module. I'd seen Peter Norvig use it before in some of his Python code, and I should've paid attention then. Fredrik's comment gave me the push to finally try it. I found that it fits my style of Python coding very naturally, since I typically shake down my code at the REPL as I go. I cut and paste my interactions at the prompt into my class, and I've got some tests up and running quickly. The nice thing is that I'm helping to document my code (inline) as I go, which is a second advantage of doctest. I've never been that enamored with writing a separate test class like I've tried with the unittest library, for instance.
Good stuff. Thanks, Fredrik.
