Background Image
Table of Contents Table of Contents
Previous Page  244 / 478 Next Page
Information
Show Menu
Previous Page 244 / 478 Next Page
Page Background

1. You could also check out

assertSequenceEqual

from

unittest

, and

assertQuerysetEqual

fromDjango’s

test tools, although I confess when I last looked at

assertQuerysetEqual

I was quite baffled…

Urp? It has worked; you can see the items

are

in the same order, but the tests are confused.

I keep running into this problem actually—Django querysets don’t compare well with

lists. We can fix it by converting the queryset to a list

1

in our test:

lists/tests/test_models.py (ch09l036).

self

.

assertEqual

(

list

(

Item

.

objects

.

all

()),

[

item1

,

item2

,

item3

]

)

That works; we get a fully passing test suite:

OK

Rewriting the Old Model Test

That long-winded model test did serendipitously help us find an unexpected bug, but

now it’s time to rewrite it. I wrote it in a very verbose style to introduce the Django

ORM, but in fact, now that we have the explicit test for ordering, we can get the same

coverage from a couple of much shorter tests. Delete

test_saving_and_retriev

ing_items

and replace with this:

lists/tests/test_models.py (ch12l010).

class

ListAndItemModelsTest

(

TestCase

):

def

test_default_text

(

self

):

item

=

Item

()

self

.

assertEqual

(

item

.

text

,

''

)

def

test_item_is_related_to_list

(

self

):

list_

=

List

.

objects

.

create

()

item

=

Item

()

item

.

list

=

list_

item

.

save

()

self

.

assertIn

(

item

,

list_

.

item_set

.

all

())

[

...

]

That’s more than enough really—a check of the default values of attributes on a freshly

initialized model object is enough to sanity-check that we’ve probably set some fields

up in

models.py

. The “item is related to list” test is a real “belt and braces” test to make

sure that our foreign key relationship works.

While we’re at it, we can split this file out into tests for

Item

and tests for

List

(there’s

only one of the latter,

test_get_absolute_url

:

216

|

Chapter 12: More Advanced Forms