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

lists/tests/test_views.py (ch19l017).

@patch

(

'lists.views.render'

)

def

test_renders_home_template_with_form_if_form_invalid

(

self

,

mock_render

,

mockNewListForm

):

mock_form

=

mockNewListForm

.

return_value

mock_form

.

is_valid

.

return_value

=

False

response

=

new_list2

(

self

.

request

)

self

.

assertEqual

(

response

,

mock_render

.

return_value

)

mock_render

.

assert_called_once_with

(

self

.

request

,

'home.html'

, {

'form'

:

mock_form

}

)

That gives us:

AssertionError: <django.http.response.HttpResponseRedirect object at

0x7f8d3f338a50> != <MagicMock name='render()' id='140244627467408'>

When using assert methods on mocks, like

assert_called_

once_with

, it’s doubly important to make sure you run the test and

see it fail. It’s all too easy to make a typo in your assert function name

and end up calling a mock method that does nothing (mine was to

write

asssert_called_once_with

with three essses, try it!)

We make a deliberate mistake, just to make sure our tests are comprehensive:

lists/views.py (ch19l018).

def

new_list2

(

request

):

form

=

NewListForm

(

data

=

request

.

POST

)

list_

=

form

.

save

(

owner

=

request

.

user

)

if

form

.

is_valid

():

return

redirect

(

list_

)

return

render

(

request

,

'home.html'

, {

'form'

:

form

})

That passes but it shouldn’t! One more test then:

lists/tests/test_views.py (ch19l019).

def

test_does_not_save_if_form_invalid

(

self

,

mockNewListForm

):

mock_form

=

mockNewListForm

.

return_value

mock_form

.

is_valid

.

return_value

=

False

new_list2

(

self

.

request

)

self

.

assertFalse

(

mock_form

.

save

.

called

)

346

|

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