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

mock_form

=

mockNewListForm

.

return_value

mock_form

.

is_valid

.

return_value

=

True

new_list2

(

self

.

request

)

mock_form

.

save

.

assert_called_once_with

(

owner

=

self

.

request

.

user

)

That takes us to this:

lists/views.py (ch19l014).

def

new_list2

(

request

):

form

=

NewListForm

(

data

=

request

.

POST

)

form

.

save

(

owner

=

request

.

user

)

In the case where the form is valid, we want the view to return a redirect, to send us to

see the object that the form has just created. So we mock out another of the view’s

collaborators, the

redirect

function:

lists/tests/test_views.py (ch19l015).

@patch

(

'lists.views.redirect'

)

#

def

test_redirects_to_form_returned_object_if_form_valid

(

self

,

mock_redirect

,

mockNewListForm

#

):

mock_form

=

mockNewListForm

.

return_value

mock_form

.

is_valid

.

return_value

=

True

#

response

=

new_list2

(

self

.

request

)

self

.

assertEqual

(

response

,

mock_redirect

.

return_value

)

#

mock_redirect

.

assert_called_once_with

(

mock_form

.

save

.

return_value

)

#

We mock out the

redirect

function, this time at the method level.

patch

decorators are applied innermost first, so the new mock is injected to our

method as before the

mockNewListForm

.

We specify we’re testing the case where the form is valid.

We check that the response from the view is the result of the

redirect

function.

And we check that the redirect function was called with the object that the form

returns on save.

That takes us to here:

lists/views.py (ch19l016).

def

new_list2

(

request

):

form

=

NewListForm

(

data

=

request

.

POST

)

list_

=

form

.

save

(

owner

=

request

.

user

)

return

redirect

(

list_

)

$

python3 manage.py test lists

[...]

Ran 40 tests in 0.163s

OK

And now the failure case—if the form is invalid, we want to render the home page

template:

Rewriting Our Tests for the View to Be Fully Isolated

|

345