AssertionsInLaunchpad

Not logged in - Log In / Register

Assertions In Launchpad

Introduction

Assertions are part of good programming practice, and they should be used in Launchpad code.

Rules

Although assertions are good, we shouldn't be using them just anywhere. These are the rules that we have to follow when using them in Launchpad:

As as example of how to use assertions, we have the method bugTasksWithSharedInterest() in PersonView, which is meant to be called only when we have a logged in user. This method is used only in one template, and protected by a tal:condition to make sure we have a logged in user. In this case, it's pretty fair to use an assertion, because calling this method without a logged in user is something that should not happen. This is the code:

    def bugTasksWithSharedInterest(self):
        assert self.user is not None, 'This method should not be called without a logged in user'

Here is an example of an assertion that does not need one. In this case, we should be raising an error, instead.

    def marryPersons(self, person1, person2):
        assert person1 is not None
        assert person2 is not None

It is interesting to note what Tim Peters thinks of assertions.

Testing your asserts

As with any other code, asserts should be documented and tested to make sure misbehaving programmers will be caught. But they shouldn't be in the general flow of documentation, because they're not part of the API. For this reason the test of asserts should be either in a separate file or in a separate section of the same file.

AssertionsInLaunchpad (last edited 2012-02-24 17:26:21 by bac)