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

Which fails:

self.assertFalse(mock_form.save.called)

AssertionError: True is not false

And we get to to our neat, small finished view:

lists/views.py.

def

new_list2

(

request

):

form

=

NewListForm

(

data

=

request

.

POST

)

if

form

.

is_valid

():

list_

=

form

.

save

(

owner

=

request

.

user

)

return

redirect

(

list_

)

return

render

(

request

,

'home.html'

, {

'form'

:

form

})

$

python3 manage.py test lists

[...]

Ran 42 tests in 0.163s

OK

Moving Down to the Forms Layer

So we’ve built up our view function based on a “wishful thinking” version of a form

called

NewItemForm

, which doesn’t even exist yet.

We’ll need the form’s save method to create a new list, and a new item based on the text

from the form’s validated POST data. If we were to just dive in and use the ORM, the

code might look something a bit like this:

class

NewListForm

(

models

.

Form

):

def

save

(

self

,

owner

):

list_

=

List

()

if

owner

:

list_

.

owner

owner

list_

.

save

()

item

=

Item

()

item

.

list

=

list_

item

.

text

=

self

.

cleaned_data

[

'text'

]

item

.

save

()

This implementation depends on two classes from the model layer,

Item

and

List

. So,

what would a well isolated test look like?

class

NewListFormTest

(

unittest

.

TestCase

):

@patch

(

'lists.forms.List'

)

#

@patch

(

'lists.forms.Item'

)

#

def

test_save_creates_new_list_and_item_from_post_data

(

self

,

mockItem

,

mockList

#

):

Moving Down to the Forms Layer

|

347