On Thu, Dec 23, 2010 at 5:44 AM, Luke Plant <l.plant...@cantab.net> wrote: > Hi all, > > This is a question of test code style. > > In tests in my own projects, I use both the Python 'assert' statement > and the unittest TestCase.assert* methods, with the following > distinction: > > * The 'assert' statement is used to make assertions about the > assumptions built in to *this* bit of code (i.e. the test itself). > > * The TestCase.assert* methods are used to make assertions about the > outcome of the bit of code that is being tested.
I like this pattern, at least as a notational style -- it is helpful to know when your tests are failing because they are making incorrect assumptions, rather than your application code being incorrect. The danger, of course, is that a failing 'assert' in your test setup could still be a bug in your code, rather than in the tests, and if you blindly fix the "bug" in the tests, then you end up solidifying a real bug in the code. (If your unit tests are factored properly, though, then the assertions you make about your test should themselves be tested in another location, so you should be able to rely on them.) > Looking at Django's test suite, I can find a few instances where this > pattern is followed (e.g. [1], [2]). Sometimes the assert statement is > also used where it is impractical to call TestCase methods (e.g. [3]). > There are a few instances where the 'assert' statement is called when it > should be a TestCase method (e.g. [4]). And there are many instances > where TestCase asserts are called, when IMO it should be an assert > statement. (e.g. [5]). >From a technical standpoint, I don't know if I see a real difference -- using "self.assert_(expr)" in a TestCase should never be impractical -- at least not more than calling "assert" directly. unittest.TestCase.assert_ just does the test manually, and raises AssertionError if it is passed anything false. The only difference between the two should be the fact that the raw "assert" can be optimized away. You'd have to call 'python -O manage.py test' deliberately for that, and I don't know why you'd ever want to optimize away parts of your test code. > So, the question is, going forward do we: > > 1) Use the pattern I outlined above? > 2) Use a different pattern (e.g. always use TestCase assert methods > where it is possible)? > 3) Simply not care about any of this? I'm +1 for #1, for consistency and clarity, but not for any technical reasons. -- Regards, Ian Clelland <clell...@gmail.com> -- You received this message because you are subscribed to the Google Groups "Django developers" group. To post to this group, send email to django-develop...@googlegroups.com. To unsubscribe from this group, send email to django-developers+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-developers?hl=en.