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

from

django.contrib.sessions.backends.db

import

SessionStore

from

.base

import

FunctionalTest

class

MyListsTest

(

FunctionalTest

):

def

create_pre_authenticated_session

(

self

,

email

):

user

=

User

.

objects

.

create

(

email

=

email

)

session

=

SessionStore

()

session

[

SESSION_KEY

]

=

user

.

pk

#

session

[

BACKEND_SESSION_KEY

]

=

settings

.

AUTHENTICATION_BACKENDS

[

0

]

session

.

save

()

## to set a cookie we need to first visit the domain.

## 404 pages load the quickest!

self

.

browser

.

get

(

self

.

server_url

+

"/404_no_such_url/"

)

self

.

browser

.

add_cookie

(

dict

(

name

=

settings

.

SESSION_COOKIE_NAME

,

value

=

session

.

session_key

,

#

path

=

'/'

,

))

We create a session object in the database. The session key is the primary key of

the user object (which is actually their email address).

We then add a cookie to the browser that matches the session on the server—

on our next visit to the site, the server should recognise us as a logged-in user.

Note that, as it is, this will only work because we’re using

LiveServerTestCase

, so the

User

and

Session

objects we create will end up in the same database as the test server.

Later we’ll need to modify it so that it works against the database on the staging server

too.

JSON Test Fixtures Considered Harmful

When we pre-populate the database with test data, as we’ve done here with the

User

object and its associated

Session

object, what we’re doing is setting up a “test fixture”.

Django comes with built-in support for saving database objects as JSON (using the

manage.py dumpdata

), and automatically loading them in your test runs using the

fixtures

class attribute on

TestCase

.

More and more people are starting to say:

don’t use JSON fixtures .

They’re a nightmare

to maintain when your model changes. Instead, if you can, load data directly using the

Django ORM, or look into a tool like

factory_boy .

304

|

Chapter 17: Test Fixtures, Logging, and Server-Side Debugging