Now let's expand the test_populate_tasks()
method seen in our initial skeleton. The simplest tests we can write, run some code from the tested object, query for a result to verify, and then use an assert to compare with an expected result.
The test_populate_tasks()
method will test the do_populate_tasks()
Todo method. Since our setup made sure we have two open Todos, after running it we expect the wizard task_ids
to be referencing these two records.
# class TestWizard(TransactionCase): def test_populate_tasks(self): "Populate tasks buttons should add two tasks" self.wizard.do_populate_tasks() count = len(self.wizard.task_ids) self.assertEqual(count, 2, 'Wrong number of populated tasks')
The docstring, at the first line of the method definition, is useful to describe the test and is printed out when running it.
The check verifying if the test succeeded or failed is the self.assertEqual
statement. The last parameter is optional, but is recommended since it provides a more informative message when the test fails.
The assertEquals
is one of the most used, but it is just one of the assert methods available. We should use the assert function appropriate for each case, since they will be more helpful to understand the cause of failing tests. For example, instead of comparing the length of task_ids
, one could have prepared a recordset with the two expected tasks, and then use:
self.assertItemsEquals( self.wizard.task_ids, expected_tasks, 'Incorrect set of populated tasks')
This would give the best output in case of failure, with a full comparison of the expected tasks versus the actual.
The unittest
documentation provides a good reference on all the methods available at https://docs.python.org/2/library/unittest.html#test-cases.
To add a new test case, add to the class another method with it's implementation. Next we will test the do_mass_update()
wizard method. This is the one doing the work when we click on the wizard's OK button:
def test_mass_change(self): "Mass change deadline date" self.wizard.do_populate_tasks() self.wizard.new_deadline = self.todo1.date_deadline self.wizard.do_mass_update() self.assertEqual( self.todo1.date_deadline, self.todo2.date_deadline)
We start by running do_populate_tasks()
again. Remember that with TransactionCase
tests, a rollback is done at the end of each test. So the operations done in the previous test were reverted, and we need to again populate the wizard's Todo Task list. Next we simulate the user filling in the new deadline field and performing the mass update. At the end our check is to see if both Todo Tasks ended up with the same date.