Skip to content

Commit ffb7d27

Browse files
committed
Add a documented example how to use a template database for tests.
Refs pytest-dev#37.
1 parent 36625b4 commit ffb7d27

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

docs/database.rst

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,3 +268,43 @@ You can also manage the access manually via these methods:
268268
.. py:function:: django_db_blocker.restore_previous_access()
269269
270270
Restore the previous state of the database blocking.
271+
272+
Examples
273+
########
274+
275+
Using a template database for tests
276+
"""""""""""""""""""""""""""""""""""
277+
278+
This example shows how a pre-created PostgreSQL source database can be copied
279+
and used for tests.::
280+
281+
import pytest
282+
from django.db import connections
283+
284+
import psycopg2
285+
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
286+
287+
288+
def run_sql(sql):
289+
conn = psycopg2.connect(database='postgres')
290+
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
291+
cur = conn.cursor()
292+
cur.execute(sql)
293+
conn.close()
294+
295+
296+
@pytest.yield_fixture(scope='session')
297+
def django_db_setup():
298+
from django.conf import settings
299+
300+
settings.DATABASES['default']['NAME'] = 'the_copied_db'
301+
302+
run_sql('DROP DATABASE IF EXISTS the_copied_db')
303+
run_sql('CREATE DATABASE the_copied_db TEMPLATE the_source_db')
304+
305+
yield
306+
307+
for connection in connections.all():
308+
connection.close()
309+
310+
run_sql('DROP DATABASE the_copied_db')

0 commit comments

Comments
 (0)