File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change @@ -268,3 +268,43 @@ You can also manage the access manually via these methods:
268
268
.. py :function :: django_db_blocker.restore_previous_access()
269
269
270
270
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')
You can’t perform that action at this time.
0 commit comments