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

self

.

assertEqual

(

response

,

mock_redirect

.

return_value

)

mock_redirect

.

assert_called_once_with

(

mock_form

.

save

.

return_value

)

#

The mocked

form.save

function is returning an object, which we expect our

view to be able to use.

Identifying Implicit Contracts

It’s worth reviewing each of the tests in

NewListViewUnitTest

and seeing what each

mock is saying about the implicit contract:

lists/tests/test_views.py.

def

test_passes_POST_data_to_NewListForm

(

self

,

mockNewListForm

):

[

...

]

mockNewListForm

.

assert_called_once_with

(

data

=

self

.

request

.

POST

)

#

def

test_saves_form_with_owner_if_form_valid

(

self

,

mockNewListForm

):

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

)

#

def

test_does_not_save_if_form_invalid

(

self

,

mockNewListForm

):

[

...

]

mock_form

.

is_valid

.

return_value

=

False

#

[

...

]

@patch

(

'lists.views.redirect'

)

def

test_redirects_to_form_returned_object_if_form_valid

(

self

,

mock_redirect

,

mockNewListForm

):

[

...

]

mock_redirect

.

assert_called_once_with

(

mock_form

.

save

.

return_value

)

#

def

test_renders_home_template_with_form_if_form_invalid

(

[

...

]

We need to be able to initialise our form by passing it a POST request as data.

It should have an

is_valid()

function which returns True or False

appropriately, based on the input data.

The form should have a

.save

method which will accept a

request.user

, which

may or may not be a logged-in user, and deal with it appropriately.

The form’s

.save

method should return a new list object, for our view to redirect

the user to.

356

|

Chapter 19: Test Isolation, and “Listening to Your Tests”