![Show Menu](styles/mobile-menu.png)
![Page Background](./../common/page-substrates/page0339.png)
Managing the Test Database on Staging
Now we can rerun our FTs, and get to the next failure: our attempt to create pre-
authenticated sessions doesn’t work, so the “My Lists” test fails:
$
python3 manage.py test functional_tests \
--liveserver=superlists-staging.ottg.eu
ERROR: test_logged_in_users_lists_are_saved_as_my_lists
(functional_tests.test_my_lists.MyListsTest)
[...]
selenium.common.exceptions.TimeoutException: Message: 'Could not find element
with id id_logout. Page text was Superlists\nSign in\nStart a new To-Do list'
Ran 7 tests in 72.742s
FAILED (errors=1)
It’s because our test utility function
create_pre_authenticated_session
only acts on
the local database. Let’s find out how our tests can manage the database on the server.
A Django Management Command to Create Sessions
To do things on the server, we’ll need to build a self-contained script that can be run
from the command line on the server, most probably via Fabric.
When trying to build standalone scripts that work with the Django environment, can
talk to the database and so on, there are some fiddly issues you need to get right, like
setting the
DJANGO_SETTINGS_MODULE
environment variable correctly, and getting the
sys.path
right. Instead of messing about with all that, Django lets you create your own
“management commands” (commands you can run with
python manage.py
), which
will do all that path mangling for you. They live in a folder called
management/
commands
inside your apps:
$
mkdir -p functional_tests/management/commands
$
touch functional_tests/management/__init__.py
$
touch functional_tests/management/commands/__init__.py
The boilerplate in a management command is a class that inherits from
djan
go.core.management.BaseCommand
, and that defines a method called
handle
:
functional_tests/management/commands/create_session.py.
from
django.conf
import
settings
from
django.contrib.auth
import
BACKEND_SESSION_KEY
,
SESSION_KEY
,
get_user_model
User
=
get_user_model
()
from
django.contrib.sessions.backends.db
import
SessionStore
from
django.core.management.base
import
BaseCommand
class
Command
(
BaseCommand
):
Managing the Test Database on Staging
|
311