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

mockList

.

return_value

=

mock_list

request

=

HttpRequest

()

request

.

user

=

User

.

objects

.

create

()

#

request

.

POST

[

'text'

]

=

'new list item'

new_list

(

request

)

self

.

assertEqual

(

mock_list

.

owner

,

request

.

user

)

#

We mock out the

List

function to be able to get access to any lists that might

be created by the view.

Then we create a real List object for the view to use. It has to be a real List object,

otherwise the Item that the view is trying to save will fail with a foreign key error

(this is an indication that the test is only partially isolated).

We set a real user on the request object.

And now we can make assertions about whether the list has had the

.owner

attribute set on it.

If we try to run this test now, it should pass.

$

python3 manage.py test lists

[...]

Ran 37 tests in 0.145s

OK

If you don’t see a pass, make sure that your views code in

views.py

is exactly as I’ve shown

it, using

List()

, not

List.objects.create

.

Using mocks does tie you to specific ways of using an API. This is one

of the many trade-offs involved in the use of mock objects.

Using Mock side_effects to Check the Sequence of Events

The trouble with this test is that it can still let us get away with writing the wrong code

by mistake. Imagine if we accidentally call save before we we assign the owner:

lists/views.py.

if

form

.

is_valid

():

list_

=

List

()

list_

.

save

()

list_

.

owner

=

request

.

user

form

.

save

(

for_list

=

list_

)

return

redirect

(

list_

)

The test, as it’s written now, still passes:

OK

A First Attempt at Using Mocks for Isolation

|

339