1
0
mirror of https://github.com/django/django.git synced 2025-10-24 06:06:09 +00:00

Made migrations tests write to a temporary directory.

This is preferrable to writing in the current working directory because
it eliminates the risk to leak unwanted files, which can result in very
weird test failures.

Also this will help if we ever try to run these tests concurrently.
This commit is contained in:
Aymeric Augustin
2015-02-22 21:50:16 +01:00
committed by Aymeric Augustin
parent b9c619abc1
commit 903d1a57ab
2 changed files with 176 additions and 176 deletions

View File

@@ -1,8 +1,14 @@
import os
import shutil
import tempfile
from contextlib import contextmanager
from importlib import import_module
from django.apps import apps
from django.db import connection
from django.test import TransactionTestCase
from django.utils._os import upath
from django.test.utils import extend_sys_path
from django.utils.module_loading import module_dir
class MigrationTestBase(TransactionTestCase):
@@ -11,7 +17,6 @@ class MigrationTestBase(TransactionTestCase):
"""
available_apps = ["migrations"]
test_dir = os.path.abspath(os.path.dirname(upath(__file__)))
def get_table_description(self, table):
with connection.cursor() as cursor:
@@ -64,3 +69,46 @@ class MigrationTestBase(TransactionTestCase):
def assertFKNotExists(self, table, columns, to, value=True):
return self.assertFKExists(table, columns, to, False)
@contextmanager
def temporary_migration_module(self, app_label='migrations', module=None):
"""
Allows testing management commands in a temporary migrations module.
Wrap all invocations to makemigrations and squashmigrations with this
context manager in order to avoid creating migration files in your
source tree inadvertently.
Takes the application label that will be passed to makemigrations or
squashmigrations and the Python path to a migrations module.
The migrations module is used as a template for creating the temporary
migrations module. If it isn't provided, the application's migrations
module is used, if it exists.
Returns the filesystem path to the temporary migrations module.
"""
temp_dir = tempfile.mkdtemp()
try:
target_dir = tempfile.mkdtemp(dir=temp_dir)
with open(os.path.join(target_dir, '__init__.py'), 'w'):
pass
target_migrations_dir = os.path.join(target_dir, 'migrations')
if module is None:
module = apps.get_app_config(app_label).name + '.migrations'
try:
source_migrations_dir = module_dir(import_module(module))
except (ImportError, ValueError):
pass
else:
shutil.copytree(source_migrations_dir, target_migrations_dir)
with extend_sys_path(temp_dir):
new_module = os.path.basename(target_dir) + '.migrations'
with self.settings(MIGRATION_MODULES={app_label: new_module}):
yield target_migrations_dir
finally:
shutil.rmtree(temp_dir)