I love assert
steve+comp.lang.python at pearwood.info
Sat Nov 29 02:30:48 CET 2014
> And as may wiser people than me have already highlighted Assertions can
> be switched off in python which means they cannot be relied upon in
> production code invalidating the authors suggestion that they can
> automate bug reports & "Extend testing into the lifetime of the product"
I'm afraid that you appear to have missed the point of assertions as tests.
Since they should never be used to *enforce* correct behaviour, but only to
*verify* behaviour is correct (i.e. as a form of testing), it doesn't
matter if you disable them. If I turn them off, all that happens is that
the tests won't run *for me*. The software will still be just as correct,
or just as buggy, regardless of the assertions.
But not everyone will turn them off. Even if *everybody else* turns them
off, you, the developer of the software, surely won't since you're not
an idiot. (Why write assertions only to never use them?) That means that
whenever you run your software during the process of development, your
assertions will run.
In a complex, rich software application, you may not have unit tests for
every possible path through the software. But if you put assertions at the
intersections of paths (e.g. at the top of each loop, or the entry and exit
of each function), then even if you don't have a unit test for a particular
path, at least the assertions will be there to provide limited testing. In
other words, correctly written assertions can provide simple but effective
test coverage of 100% of your application.
I stress that assertions aren't a replacement for unit testing, but they
compliment unit testing: assertions can help cover code missed by your unit
tests, and check that your unit tests are correct.
If the user of your application disables assertions, they will be no worse
off than if you didn't write those assertions at all. And if they enable
assertions, then they get extended testing throughout the lifetime of the
product *for free*.
(Well, perhaps not *quite* for free, since assertions do have some
performance cost. But very cheaply.)
 Thanks to Python defaulting to __debug__ = True, the problem is getting
people to remember to test their software with assertions disabled, not to
get them to enable them.
More information about the Python-list