Programming Tests - Because I'm lazy

I recently had an epiphany, which may seem painfully obvious to most programmers, but it took me a little while longer to realize.

Under Python there is a module called doctest, which allows you to script an interactive session and look at the results. A sample would be:

>>> print 2+2 4

If I put this snippet into a text file, test.txt, and ran it with python -m doctest test.txt, I'd get no output, because the test passed (printing 2+2 under python gives us 4). However, if I put the following into the test.txt file:

>>> print 2+2 3.14159

and run it with the same command, I get the following:

craig@lister:~$ python -m doctest test.txt ********************************************************************** File "test.txt", line 1, in test.txt Failed example: print 2+2 Expected: 3.14159 Got: 4 ********************************************************************** 1 items had failures: 1 of 1 in test.txt ***Test Failed*** 1 failures.

Which is expected. (There's no way that 2+2 is going to equal 3.14159).

So, you may be asking yourself, how does adding this to my normal code make me lazy? Isn't this more work?

Well, considering when I'm writing new code, I'm constantly running the code in an interactive environment, and essentially doing the same scripted commands over and over again (albeit, a lot slower than the computer can), this is a huge time-saver. Essentially, I can script the session, and test the new code in seconds, and be alerted if something changes.

Anyone who says they don't have time for testing their code is deluding themselves. If you think you don't have time for testing, ask yourself if you couldn't save a few keystrokes testing the code manually? Why not have the computer do it for you instead? After all, isn't that what computers are for? (Handing tasks that would otherwise be drudgery).

EDIT: And yes, I know that doctest doesn't scale well the same way that the unittest framework does. Right now with the code I have, it's not that big of a deal. I know that eventually I will need to switch. :)


Comments !

blogroll

social