Browse files

Database fixture refactor (#362)

  • Loading branch information...
1 parent def2882 commit e540acef62fe4a672b52dbc63b14ce4990d00c5b @pelme pelme committed on GitHub Jul 3, 2016
Showing with 419 additions and 160 deletions.
  1. +16 −1 docs/changelog.rst
  2. +272 −0 docs/database.rst
  3. +2 −43 pytest_django/db_reuse.py
  4. +77 −35 pytest_django/fixtures.py
  5. +49 −35 pytest_django/plugin.py
  6. +0 −42 tests/test_db_name.py
  7. +3 −4 tests/test_db_setup.py
View
17 docs/changelog.rst
@@ -15,6 +15,15 @@ Features
* Added a new option `--migrations` to negate a default usage of
`--nomigrations`.
+* The previously internal pytest-django fixture that handles database creation
+ and setup has been refactored, refined and made a public API.
+
+ This opens up more flexibility and advanced use cases to configure the test
+ database in new ways.
+
+ See :ref:`advanced-database-configuration` for more information on the new
+ fixtures and example use cases.
+
Compatibility
^^^^^^^^^^^^^
* Django versions 1.4, 1.5 and 1.6 is no longer supported. The supported
@@ -29,9 +38,15 @@ Compatibility
database access was prevented on the cursor level. To be safer and prevent
more cases, it is now prevented at the connection level. If you previously
had tests which interacted with the databases without a database cursor, you
- will need to mark them with the `pytest.mark.django_db` marker or request the
+ will need to mark them with the :func:`pytest.mark.django_db` marker or request the
`db` fixture.
+* The previously undocumented internal fixtures ``_django_db_setup``,
+ ``_django_cursor_wrapper`` has been removed in favour of the new public
+ fixtures. If you previously relied on these internal fixtures, you must
+ update your code. See :ref:`advanced-database-configuration` for more
+ information on the new fixtures and example use cases.
+
2.9.1
-----
View
272 docs/database.rst
@@ -128,3 +128,275 @@ Using ``--nomigrations`` will disable Django migrations and create the database
by inspecting all models. It may be faster when there are several migrations to
run in the database setup. You can use ``--migrations`` to force running
migrations in case ``--nomigrations`` is used, e.g. in ``setup.cfg``.
+
+.. _advanced-database-configuration:
+
+Advanced database configuration
+-------------------------------
+
+pytest-django provides options to customize the way database is configured. The
+default database construction mostly follows Django's own test runner. You can
+however influence all parts of the database setup process to make it fit in
+projects with special requirements.
+
+This section assumes some familiary with the Django test runner, Django
+database creation and pytest fixtures.
+
+Fixtures
+########
+
+There are some fixtures which will let you change the way the database is
+configured in your own project. These fixtures can be overridden in your own
+project by specifying a fixture with the same name and scope in ``conftest.py``.
+
+.. admonition:: Use the pytest-django source code
+
+ The default implementation of these fixtures can be found in
+ `fixtures.py <https://github.com/pytest-dev/pytest-django/blob/master/pytest_django/fixtures.py>`_.
+
+ The code is relatively short and straightforward and can provide a
+ starting point when you need to customize database setup in your own
+ project.
+
+
+django_db_setup
+"""""""""""""""
+
+.. fixture:: django_db_setup
+
+This is the top-level fixture that ensures that the test databases are created
+and available. This fixture is session scoped (it will be run once per test
+session) and is responsible for making sure the test database is available for tests
+that need it.
+
+The default implementation creates the test database by applying migrations and removes
+databases after the test run.
+
+You can override this fixture in your own ``conftest.py`` to customize how test
+databases are constructed.
+
+django_db_modify_db_settings
+""""""""""""""""""""""""""""
+
+.. fixture:: django_db_modify_db_settings
+
+This fixture allows modifying `django.conf.settings.DATABASES` just before the
+databases are configured.
+
+If you need to customize the location of your test database, this is the
+fixture you want to override.
+
+The default implementation of this fixture requests the
+:fixture:`django_db_modify_db_settings_xdist_suffix` to provide compatibility
+with pytest-xdist.
+
+This fixture is by default requested from :fixture:`django_db_setup`.
+
+django_db_modify_db_settings_xdist_suffix
+"""""""""""""""""""""""""""""""""""""""""
+
+.. fixture:: django_db_modify_db_settings_xdist_suffix
+
+Requesting this fixture will add a suffix to the database name when the tests
+are run via pytest-xdist.
+
+This fixture is by default requsted from
+:fixture:`django_db_modify_db_settings_xdist_suffix`.
+
+django_db_use_migrations
+""""""""""""""""""""""""
+
+.. fixture:: django_db_use_migrations
+
+Returns whether or not to use migrations to create the test
+databases.
+
+The default implementation returns the value of the
+``--migrations``/``--nomigrations`` command line options.
+
+This fixture is by default requested from :fixture:`django_db_setup`.
+
+django_db_keepdb
+""""""""""""""""
+
+.. fixture:: django_db_keepdb
+
+Returns whether or not to re-use an existing database and to keep it after the
+test run.
+
+The default implementation handles the ``--reuse-db`` and ``--create-db``
+command line options.
+
+This fixture is by default requested from :fixture:`django_db_setup`.
+
+django_db_blocker
+"""""""""""""""""
+
+.. fixture:: django_db_blocker
+
+.. warning::
+ It does not manage transactions and changes made to the database will not
+ be automatically restored. Using the :func:`pytest.mark.django_db` marker
+ or :fixture:`db` fixture, which wraps database changes in a transaction and
+ restores the state is generally the thing you want in tests. This marker
+ can be used when you are trying to influence the way the database is
+ configured.
+
+Database access is by default not allowed. ``django_db_blocker`` is the object
+which can allow specific code paths to have access to the database. This
+fixture is used internally to implement the ``db`` fixture.
+
+
+:fixture:`django_db_blocker` can be used as a context manager to enable database
+access for the specified block::
+
+ @pytest.fixture
+ def myfixture(django_db_blocker):
+ with django_db_blocker:
+ ... # modify something in the database
+
+You can also manage the access manually via these methods:
+
+.. py:method:: django_db_blocker.enable_database_access()
+
+ Enable database access. Should be followed by a call to
+ :func:`~django_db_blocker.restore_previous_access`.
+
+.. py:method:: django_db_blocker.disable_database_access()
+
+ Disable database access. Should be followed by a call to
+ :func:`~django_db_blocker.restore_previous_access`.
+
+.. py:function:: django_db_blocker.restore_previous_access()
+
+ Restore the previous state of the database blocking.
+
+Examples
+########
+
+Using a template database for tests
+"""""""""""""""""""""""""""""""""""
+
+This example shows how a pre-created PostgreSQL source database can be copied
+and used for tests.
+
+Put this into ``conftest.py``::
+
+ import pytest
+ from django.db import connections
+
+ import psycopg2
+ from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
+
+
+ def run_sql(sql):
+ conn = psycopg2.connect(database='postgres')
+ conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
+ cur = conn.cursor()
+ cur.execute(sql)
+ conn.close()
+
+
+ @pytest.yield_fixture(scope='session')
+ def django_db_setup():
+ from django.conf import settings
+
+ settings.DATABASES['default']['NAME'] = 'the_copied_db'
+
+ run_sql('DROP DATABASE IF EXISTS the_copied_db')
+ run_sql('CREATE DATABASE the_copied_db TEMPLATE the_source_db')
+
+ yield
+
+ for connection in connections.all():
+ connection.close()
+
+ run_sql('DROP DATABASE the_copied_db')
+
+
+Using an existing, external database for tests
+""""""""""""""""""""""""""""""""""""""""""""""
+
+This example shows how you can connect to an existing database and use it for
+your tests. This example is trivial, you just need to disable all of
+pytest-django and Django's test database creation and point to the existing
+database. This is achieved by simply implementing a no-op
+:fixture:`django_db_setup` fixture.
+
+Put this into ``conftest.py``::
+
+ import pytest
+
+
+ @pytest.fixture(scope='session')
+ def django_db_setup():
+ settings.DATABASES['default'] = {
+ 'ENGINE': 'django.db.backends.mysql',
+ 'HOST': 'db.example.com',
+ 'NAME': 'external_db',
+ }
+
+
+Populate the database with initial test data
+""""""""""""""""""""""""""""""""""""""""""""
+
+This example shows how you can populate the test database with test data. The
+test data will be saved in the database, i.e. it will not just be part of a
+transactions. This example uses Django's fixture loading mechanism, but it can
+be replaced with any way of loading data into the database.
+
+Notice that :fixture:`django_db_setup` is in the argument list. This may look
+odd at first, but it will make sure that the sure that the original
+pytest-django fixture is used to create the test database. When
+``call_command`` is invoked, the test database is already prepared and
+configured.
+
+Put this in ``conftest.py``::
+
+ import pytest
+
+ from django.core.management import call_command
+
+ @pytest.fixture(scope='session')
+ def django_db_setup(django_db_setup, django_db_blocker):
+ with django_db_blocker:
+ call_command('loaddata', 'your_data_fixture.json')
+
+Use the same database for all xdist processes
+"""""""""""""""""""""""""""""""""""""""""""""
+
+By default, each xdist process gets its own database to run tests on. This is
+needed to have transactional tests that does not interfere with eachother.
+
+If you instead want your tests to use the same database, override the
+:fixture:`django_db_modify_db_settings` to not do anything. Put this in
+``conftest.py``::
+
+ import pytest
+
+
+ @pytest.fixture(scope='session')
+ def django_db_modify_db_settings():
+ pass
+
+Randomize database sequences
+""""""""""""""""""""""""""""
+
+You can customize the test database after it has been created by extending the
+:fixture:`django_db_setup` fixture. This example shows how to give a PostgreSQL
+sequence a random starting value. This can be used to detect and prevent
+primary key id's from being hard-coded in tests.
+
+Put this in ``conftest.py``::
+
+ import random
+ import pytest
+ from django.db import connection
+
+
+ @pytest.fixture(scope='session')
+ def django_db_setup(django_db_setup, django_db_blocker):
+ with django_db_blocker:
+ cur = connection.cursor()
+ cur.execute('ALTER SEQUENCE app_model_id_seq RESTART WITH %s;',
+ [random.randint(10000, 20000)])
View
45 pytest_django/db_reuse.py
@@ -1,7 +1,4 @@
-"""Functions to aid in preserving the test database between test runs.
-
-The code in this module is heavily inspired by django-nose:
-https://github.com/jbalogh/django-nose/
+"""Functions to aid in creating, reusing and destroying Django test databases
"""
import os.path
import sys
@@ -36,7 +33,7 @@ def test_database_exists_from_previous_run(connection):
def _monkeypatch(obj, method_name, new_method):
- assert hasattr(obj, method_name)
+ assert hasattr(obj, method_name), method_name
if sys.version_info < (3, 0):
wrapped_method = types.MethodType(new_method, obj, obj.__class__)
@@ -46,44 +43,6 @@ def _monkeypatch(obj, method_name, new_method):
setattr(obj, method_name, wrapped_method)
-def _get_db_name(db_settings, suffix):
- "This provides the default test db name that Django uses."
- name = None
- try:
- name = db_settings['TEST']['NAME']
- except KeyError:
- pass
-
- if not name:
- if db_settings['ENGINE'] == 'django.db.backends.sqlite3':
- return ':memory:'
- else:
- name = 'test_' + db_settings['NAME']
-
- if suffix:
- name = '%s_%s' % (name, suffix)
- return name
-
-
-def monkey_patch_creation_for_db_suffix(suffix=None):
- from django.db import connections
-
- if suffix is not None:
- def _get_test_db_name(self):
- """Internal: return the name of the test DB that will be created.
-
- This is only useful when called from create_test_db() and
- _create_test_db() and when no external munging is done with the
- 'NAME' or 'TEST_NAME' settings.
- """
- db_name = _get_db_name(self.connection.settings_dict, suffix)
- return db_name
-
- for connection in connections.all():
- _monkeypatch(connection.creation,
- '_get_test_db_name', _get_test_db_name)
-
-
def create_test_db_with_reuse(self, verbosity=1, autoclobber=False,
keepdb=False, serialize=False):
"""
View
112 pytest_django/fixtures.py
@@ -7,71 +7,113 @@
import pytest
from . import live_server_helper
-from .db_reuse import (monkey_patch_creation_for_db_reuse,
- monkey_patch_creation_for_db_suffix)
+
from .django_compat import is_django_unittest
+
from .lazy_django import get_django_version, skip_if_no_django
-__all__ = ['_django_db_setup', 'db', 'transactional_db', 'admin_user',
+__all__ = ['django_db_setup', 'db', 'transactional_db', 'admin_user',
'django_user_model', 'django_username_field',
'client', 'admin_client', 'rf', 'settings', 'live_server',
'_live_server_helper']
-# ############### Internal Fixtures ################
+@pytest.fixture(scope='session')
+def django_db_modify_db_settings_xdist_suffix(request):
+ skip_if_no_django()
+
+ from django.conf import settings
+
+ for db_settings in settings.DATABASES.values():
+
+ try:
+ test_name = db_settings['TEST']['NAME']
+ except KeyError:
+ test_name = None
+
+ if not test_name:
+ if db_settings['ENGINE'] == 'django.db.backends.sqlite3':
+ return ':memory:'
+ else:
+ test_name = 'test_{}'.format(db_settings['NAME'])
+
+ # Put a suffix like _gw0, _gw1 etc on xdist processes
+ xdist_suffix = getattr(request.config, 'slaveinput', {}).get('slaveid')
+ if test_name != ':memory:' and xdist_suffix is not None:
+ test_name = '{}_{}'.format(test_name, xdist_suffix)
+
+ db_settings.setdefault('TEST', {})
+ db_settings['TEST']['NAME'] = test_name
+
@pytest.fixture(scope='session')
-def _django_db_setup(request,
- _django_test_environment,
- _django_cursor_wrapper):
- """Session-wide database setup, internal to pytest-django"""
+def django_db_modify_db_settings(django_db_modify_db_settings_xdist_suffix):
skip_if_no_django()
- from django.test.runner import setup_databases, DiscoverRunner
- # xdist
- if hasattr(request.config, 'slaveinput'):
- db_suffix = request.config.slaveinput['slaveid']
- else:
- db_suffix = None
+@pytest.fixture(scope='session')
+def django_db_use_migrations(request):
+ return not request.config.getvalue('nomigrations')
+
+
+@pytest.fixture(scope='session')
+def django_db_keepdb(request):
+ return request.config.getvalue('reuse_db') and not request.config.getvalue('create_db')
- monkey_patch_creation_for_db_suffix(db_suffix)
- if request.config.getvalue('nomigrations'):
+@pytest.fixture(scope='session')
+def django_db_setup(
+ request,
+ django_test_environment,
+ django_db_blocker,
+ django_db_use_migrations,
+ django_db_keepdb,
+ django_db_modify_db_settings,
+):
+ """Top level fixture to ensure test databases are available"""
+ from django.test.runner import setup_databases, DiscoverRunner
+
+ setup_databases_args = {}
+
+ if not django_db_use_migrations:
_disable_native_migrations()
- db_args = {}
- with _django_cursor_wrapper:
- if (request.config.getvalue('reuse_db') and
- not request.config.getvalue('create_db')):
- if get_django_version() >= (1, 8):
- db_args['keepdb'] = True
- else:
+ if django_db_keepdb:
+ if get_django_version() >= (1, 8):
+ setup_databases_args['keepdb'] = True
+ else:
+ # Django 1.7 compatibility
+ from .db_reuse import monkey_patch_creation_for_db_reuse
+
+ with django_db_blocker:
monkey_patch_creation_for_db_reuse()
- # Create the database
- db_cfg = setup_databases(verbosity=pytest.config.option.verbose,
- interactive=False, **db_args)
+ with django_db_blocker:
+ db_cfg = setup_databases(
+ verbosity=pytest.config.option.verbose,
+ interactive=False,
+ **setup_databases_args
+ )
def teardown_database():
- with _django_cursor_wrapper:
+ with django_db_blocker:
(DiscoverRunner(verbosity=pytest.config.option.verbose, interactive=False)
.teardown_databases(db_cfg))
- if not request.config.getvalue('reuse_db'):
+ if not django_db_keepdb:
request.addfinalizer(teardown_database)
-def _django_db_fixture_helper(transactional, request, _django_cursor_wrapper):
+def _django_db_fixture_helper(transactional, request, django_db_blocker):
if is_django_unittest(request):
return
if not transactional and 'live_server' in request.funcargnames:
# Do nothing, we get called with transactional=True, too.
return
- _django_cursor_wrapper.enable()
- request.addfinalizer(_django_cursor_wrapper.disable)
+ django_db_blocker.enable_database_access()
+ request.addfinalizer(django_db_blocker.restore_previous_access)
if transactional:
from django.test import TransactionTestCase as django_case
@@ -93,7 +135,7 @@ def _disable_native_migrations():
# ############### User visible fixtures ################
@pytest.fixture(scope='function')
-def db(request, _django_db_setup, _django_cursor_wrapper):
+def db(request, django_db_setup, django_db_blocker):
"""Require a django test database
This database will be setup with the default fixtures and will have
@@ -111,11 +153,11 @@ def db(request, _django_db_setup, _django_cursor_wrapper):
or 'live_server' in request.funcargnames:
request.getfuncargvalue('transactional_db')
else:
- _django_db_fixture_helper(False, request, _django_cursor_wrapper)
+ _django_db_fixture_helper(False, request, django_db_blocker)
@pytest.fixture(scope='function')
-def transactional_db(request, _django_db_setup, _django_cursor_wrapper):
+def transactional_db(request, django_db_setup, django_db_blocker):
"""Require a django test database with transaction support
This will re-initialise the django database for each test and is
@@ -126,7 +168,7 @@ def transactional_db(request, _django_db_setup, _django_cursor_wrapper):
database setup will behave as only ``transactional_db`` was
requested.
"""
- _django_db_fixture_helper(True, request, _django_cursor_wrapper)
+ _django_db_fixture_helper(True, request, django_db_blocker)
@pytest.fixture()
View
84 pytest_django/plugin.py
@@ -14,17 +14,25 @@
import py
import pytest
-from .django_compat import is_django_unittest
-from .fixtures import (_django_db_setup, _live_server_helper, admin_client,
- admin_user, client, db, django_user_model,
- django_username_field, live_server, rf, settings,
- transactional_db)
-from .lazy_django import django_settings_is_configured, skip_if_no_django
+from .django_compat import is_django_unittest # noqa
+from .fixtures import django_db_setup # noqa
+from .fixtures import django_db_use_migrations # noqa
+from .fixtures import django_db_keepdb # noqa
+from .fixtures import django_db_modify_db_settings # noqa
+from .fixtures import django_db_modify_db_settings_xdist_suffix # noqa
+from .fixtures import _live_server_helper # noqa
+from .fixtures import admin_client # noqa
+from .fixtures import admin_user # noqa
+from .fixtures import client # noqa
+from .fixtures import db # noqa
+from .fixtures import django_user_model # noqa
+from .fixtures import django_username_field # noqa
+from .fixtures import live_server # noqa
+from .fixtures import rf # noqa
+from .fixtures import settings # noqa
+from .fixtures import transactional_db # noqa
-# Silence linters for imported fixtures.
-(_django_db_setup, _live_server_helper, admin_client, admin_user, client, db,
- django_user_model, django_username_field, live_server, rf, settings,
- transactional_db)
+from .lazy_django import django_settings_is_configured, skip_if_no_django
SETTINGS_MODULE_ENV = 'DJANGO_SETTINGS_MODULE'
@@ -137,7 +145,7 @@ def _setup_django():
return
django.setup()
- _blocking_manager.disable()
+ _blocking_manager.disable_database_access()
def _parse_django_find_project_ini(x):
@@ -231,7 +239,7 @@ def pytest_load_initial_conftests(early_config, parser, args):
# Forcefully load django settings, throws ImportError or
# ImproperlyConfigured if settings cannot be loaded.
- from django.conf import settings
+ from django.conf import settings # noqa
with _handle_import_error(_django_project_scan_outcome):
settings.DATABASES
@@ -311,7 +319,7 @@ def pytest_runtest_setup(item):
@pytest.fixture(autouse=True, scope='session')
-def _django_test_environment(request):
+def django_test_environment(request):
"""
Ensure that Django is loaded and has its testing environment setup.
@@ -324,20 +332,26 @@ def _django_test_environment(request):
"""
if django_settings_is_configured():
_setup_django()
- from django.conf import settings
+ from django.conf import settings # noqa
from django.test.utils import setup_test_environment, teardown_test_environment
settings.DEBUG = False
setup_test_environment()
request.addfinalizer(teardown_test_environment)
-@pytest.fixture(autouse=True, scope='session')
-def _django_cursor_wrapper(request):
- """Wrapper around Django's database access, internal to pytest-django.
+@pytest.fixture(scope='session')
+def django_db_blocker():
+ """Wrapper around Django's database access.
+
+ This object can be used to re-enable database access. This fixture is used
+ internally in pytest-django to build the other fixtures and can be used for
+ special database handling.
+
+ The object is a context manager and provides the methods
+ .enable_database_access()/.disable_database_access() and .restore_database_access() to
+ temporarily enable database access.
- This will globally disable all database access. The object
- returned has a .enable() and a .disable() method which can be used
- to temporarily enable database access.
+ This is an advanced feature that is meant to be used to implement database fixtures.
"""
if not django_settings_is_configured():
return None
@@ -362,13 +376,13 @@ def _django_db_marker(request):
@pytest.fixture(autouse=True, scope='class')
-def _django_setup_unittest(request, _django_cursor_wrapper):
+def _django_setup_unittest(request, django_db_blocker):
"""Setup a django unittest, internal to pytest-django."""
if django_settings_is_configured() and is_django_unittest(request):
- request.getfuncargvalue('_django_test_environment')
- request.getfuncargvalue('_django_db_setup')
+ request.getfuncargvalue('django_test_environment')
+ request.getfuncargvalue('django_db_setup')
- _django_cursor_wrapper.enable()
+ django_db_blocker.enable_database_access()
cls = request.node.cls
@@ -379,7 +393,7 @@ def _django_setup_unittest(request, _django_cursor_wrapper):
def teardown():
_restore_class_methods(cls)
cls.tearDownClass()
- _django_cursor_wrapper.restore()
+ django_db_blocker.restore_previous_access()
request.addfinalizer(teardown)
@@ -476,7 +490,7 @@ def __mod__(self, var):
if os.environ.get(INVALID_TEMPLATE_VARS_ENV, 'false') == 'true':
if django_settings_is_configured():
import django
- from django.conf import settings
+ from django.conf import settings # noqa
if django.VERSION >= (1, 8) and settings.TEMPLATES:
settings.TEMPLATES[0]['OPTIONS']['string_if_invalid'] = InvalidVarException()
@@ -492,7 +506,7 @@ def _template_string_if_invalid_marker(request):
if os.environ.get(INVALID_TEMPLATE_VARS_ENV, 'false') == 'true':
if marker and django_settings_is_configured():
import django
- from django.conf import settings
+ from django.conf import settings # noqa
if django.VERSION >= (1, 8) and settings.TEMPLATES:
settings.TEMPLATES[0]['OPTIONS']['string_if_invalid'].fail = False
@@ -502,10 +516,10 @@ def _template_string_if_invalid_marker(request):
# ############### Helper Functions ################
-class BlockDjangoDatabaseManager(object):
+class _DatabaseBlocker(object):
"""Manager for django.db.backends.base.base.BaseDatabaseWrapper.
- This is the object returned by _django_cursor_wrapper.
+ This is the object returned by django_db_blocker.
"""
def __init__(self):
@@ -536,27 +550,27 @@ def _blocking_wrapper(*args, **kwargs):
pytest.fail('Database access not allowed, '
'use the "django_db" mark to enable it.')
- def enable(self):
+ def enable_database_access(self):
"""Enable access to the Django database."""
self._save_active_wrapper()
self._dj_db_wrapper.ensure_connection = self._real_ensure_connection
- def disable(self):
+ def disable_database_access(self):
"""Disable access to the Django database."""
self._save_active_wrapper()
self._dj_db_wrapper.ensure_connection = self._blocking_wrapper
- def restore(self):
+ def restore_previous_access(self):
self._dj_db_wrapper.ensure_connection = self._history.pop()
def __enter__(self):
- self.enable()
+ self.enable_database_access()
def __exit__(self, exc_type, exc_value, traceback):
- self.restore()
+ self.restore_previous_access()
-_blocking_manager = BlockDjangoDatabaseManager()
+_blocking_manager = _DatabaseBlocker()
def validate_django_db(marker):
View
42 tests/test_db_name.py
@@ -1,42 +0,0 @@
-# coding: utf-8
-
-from pytest_django.db_reuse import _get_db_name
-
-
-def test_name():
- db_settings = {
- 'ENGINE': 'django.db.backends.postgresql_psycopg2',
- 'NAME': 'pytest_django',
- 'TEST_NAME': '',
- 'HOST': 'localhost',
- 'USER': '',
- }
- assert _get_db_name(db_settings, None) == 'test_pytest_django'
- assert _get_db_name(db_settings, 'abc') == 'test_pytest_django_abc'
-
-
-def test_name_sqlite():
- db_settings = {
- 'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': 'pytest_django',
- 'HOST': 'localhost',
- 'USER': '',
- }
- assert _get_db_name(db_settings, None) == ':memory:'
- assert _get_db_name(db_settings, 'abc') == ':memory:'
-
- db_settings['TEST'] = {'NAME': 'custom_test_db'}
- assert _get_db_name(db_settings, None) == 'custom_test_db'
- assert _get_db_name(db_settings, 'abc') == 'custom_test_db_abc'
-
-
-def test_testname():
- db_settings = {
- 'ENGINE': 'django.db.backends.postgresql_psycopg2',
- 'NAME': 'pytest_django',
- 'HOST': 'localhost',
- 'USER': '',
- }
- db_settings['TEST'] = {'NAME': 'test123'}
- assert _get_db_name(db_settings, None) == 'test123'
- assert _get_db_name(db_settings, 'abc') == 'test123_abc'
View
7 tests/test_db_setup.py
@@ -27,9 +27,7 @@ def test_db_can_be_accessed():
def test_db_reuse(django_testdir):
"""
- Test the re-use db functionality. This test requires a PostgreSQL server
- to be available and the environment variables PG_HOST, PG_DB, PG_USER to
- be defined.
+ Test the re-use db functionality.
"""
skip_if_sqlite_in_memory()
@@ -194,7 +192,8 @@ def test_a():
(conn, ) = connections.all()
assert conn.vendor == 'sqlite'
- assert conn.creation._get_test_db_name() == ':memory:'
+ db_name = conn.creation._get_test_db_name()
+ assert 'file:memorydb' in db_name or db_name == ':memory:'
''')
result = django_testdir.runpytest_subprocess('--tb=short', '-vv', '-n1')

0 comments on commit e540ace

Please sign in to comment.