<commit_before># -*- coding: utf-8 -*-
"""
A series of tests to establish that the command-line managment tools work as
advertised - especially with regards to the handling of the DJANGO_SETTINGS_MODULE
and default settings.py files.
"""
from __future__ import unicode_literals

import os
import re
import shutil
import socket
import subprocess
import sys
import codecs

from django import conf, bin, get_version
from django.conf import settings
from django.core.management import BaseCommand
from django.db import connection
from django.test.simple import DjangoTestSuiteRunner
from django.utils import unittest
from django.utils.encoding import force_str, force_text
from django.utils._os import upath
from django.utils.six import StringIO
from django.test import LiveServerTestCase


test_dir = os.path.join(os.environ['DJANGO_TEST_TEMP_DIR'], 'test_project')
if not os.path.exists(test_dir):
    os.mkdir(test_dir)
    open(os.path.join(test_dir, '__init__.py'), 'w').close()

custom_templates_dir = os.path.join(os.path.dirname(__file__), 'custom_templates')


class AdminScriptTestCase(unittest.TestCase):
    def write_settings(self, filename, apps=None, is_dir=False, sdict=None):
        if is_dir:
            settings_dir = os.path.join(test_dir, filename)
            os.mkdir(settings_dir)
            settings_file_path = os.path.join(settings_dir, '__init__.py')
        else:
            settings_file_path = os.path.join(test_dir, filename)

        with open(settings_file_path, 'w') as settings_file:
            settings_file.write('# Settings file automatically generated by admin_scripts test case\n')
            exports = [
                'DATABASES',
                'ROOT_URLCONF',
                'SECRET_KEY',
            ]
            for s in exports:
                if hasattr(settings, s):
                    o = getattr(settings, s)
                    if not isinstance(o, dict):
                        o = "'%s'" % o
                    settings_file.write("%s = %s\n" % (s, o))

            if apps is None:
                apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'admin_scripts']

            settings_file.write("INSTALLED_APPS = %s\n" % apps)

            if sdict:
                for k, v in sdict.items():
                    settings_file.write("%s = %s\n" % (k, v))

    def remove_settings(self, filename, is_dir=False):
        full_name = os.path.join(test_dir, filename)
        if is_dir:
            shutil.rmtree(full_name)
        else:
            os.remove(full_name)

        # Also try to remove the compiled file; if it exists, it could
        # mess up later tests that depend upon the .py file not existing
        try:
            if sys.platform.startswith('java'):
                # Jython produces module$py.class files
                os.remove(re.sub(r'\.py$', '$py.class', full_name))
            else:
                # CPython produces module.pyc files
                os.remove(full_name + 'c')
        except OSError:
            pass
        # Also remove a __pycache__ directory, if it exists
        cache_name = os.path.join(test_dir, '__pycache__')
        if os.path.isdir(cache_name):
            shutil.rmtree(cache_name)

    def _ext_backend_paths(self):
        """
        Returns the paths for any external backend packages.
        """
        paths = []
        first_package_re = re.compile(r'(^[^\.]+)\.')
        for backend in settings.DATABASES.values():
            result = first_package_re.findall(backend['ENGINE'])
            if result and result != ['django']:
                backend_pkg = __import__(result[0])
                backend_dir = os.path.dirname(backend_pkg.__file__)
                paths.append(os.path.dirname(backend_dir))
        return paths

    def run_test(self, script, args, settings_file=None, apps=None):
        project_dir = test_dir
        base_dir = os.path.dirname(test_dir)
        import django
        django_dir = os.path.dirname(os.path.dirname(django.__file__))
        tests_dir = os.path.join(django_dir, 'tests')
        ext_backend_base_dirs = self._ext_backend_paths()

        # Remember the old environment
        old_django_settings_module = os.environ.get('DJANGO_SETTINGS_MODULE', None)
        if sys.platform.startswith('java'):
            python_path_var_name = 'JYTHONPATH'
        else:
            python_path_var_name = 'PYTHONPATH'

        old_python_path = os.environ.get(python_path_var_name, None)
        old_cwd = os.getcwd()

        # Set the test environment
        if settings_file:
            os.environ['DJANGO_SETTINGS_MODULE'] = settings_file
        elif 'DJANGO_SETTINGS_MODULE' in os.environ:
            del os.environ['DJANGO_SETTINGS_MODULE']
        python_path = [base_dir, django_dir, tests_dir]
        python_path.extend(ext_backend_base_dirs)<commit_msg>Fixed discovery of the Django installation during tests.<commit_after># -*- coding: utf-8 -*-
"""
A series of tests to establish that the command-line managment tools work as
advertised - especially with regards to the handling of the DJANGO_SETTINGS_MODULE
and default settings.py files.
"""
from __future__ import unicode_literals

import os
import re
import shutil
import socket
import subprocess
import sys
import codecs

from django import conf, bin, get_version
from django.conf import settings
from django.core.management import BaseCommand
from django.db import connection
from django.test.simple import DjangoTestSuiteRunner
from django.utils import unittest
from django.utils.encoding import force_str, force_text
from django.utils._os import upath
from django.utils.six import StringIO
from django.test import LiveServerTestCase


test_dir = os.path.join(os.environ['DJANGO_TEST_TEMP_DIR'], 'test_project')
if not os.path.exists(test_dir):
    os.mkdir(test_dir)
    open(os.path.join(test_dir, '__init__.py'), 'w').close()

custom_templates_dir = os.path.join(os.path.dirname(__file__), 'custom_templates')


class AdminScriptTestCase(unittest.TestCase):
    def write_settings(self, filename, apps=None, is_dir=False, sdict=None):
        if is_dir:
            settings_dir = os.path.join(test_dir, filename)
            os.mkdir(settings_dir)
            settings_file_path = os.path.join(settings_dir, '__init__.py')
        else:
            settings_file_path = os.path.join(test_dir, filename)

        with open(settings_file_path, 'w') as settings_file:
            settings_file.write('# Settings file automatically generated by admin_scripts test case\n')
            exports = [
                'DATABASES',
                'ROOT_URLCONF',
                'SECRET_KEY',
            ]
            for s in exports:
                if hasattr(settings, s):
                    o = getattr(settings, s)
                    if not isinstance(o, dict):
                        o = "'%s'" % o
                    settings_file.write("%s = %s\n" % (s, o))

            if apps is None:
                apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'admin_scripts']

            settings_file.write("INSTALLED_APPS = %s\n" % apps)

            if sdict:
                for k, v in sdict.items():
                    settings_file.write("%s = %s\n" % (k, v))

    def remove_settings(self, filename, is_dir=False):
        full_name = os.path.join(test_dir, filename)
        if is_dir:
            shutil.rmtree(full_name)
        else:
            os.remove(full_name)

        # Also try to remove the compiled file; if it exists, it could
        # mess up later tests that depend upon the .py file not existing
        try:
            if sys.platform.startswith('java'):
                # Jython produces module$py.class files
                os.remove(re.sub(r'\.py$', '$py.class', full_name))
            else:
                # CPython produces module.pyc files
                os.remove(full_name + 'c')
        except OSError:
            pass
        # Also remove a __pycache__ directory, if it exists
        cache_name = os.path.join(test_dir, '__pycache__')
        if os.path.isdir(cache_name):
            shutil.rmtree(cache_name)

    def _ext_backend_paths(self):
        """
        Returns the paths for any external backend packages.
        """
        paths = []
        first_package_re = re.compile(r'(^[^\.]+)\.')
        for backend in settings.DATABASES.values():
            result = first_package_re.findall(backend['ENGINE'])
            if result and result != ['django']:
                backend_pkg = __import__(result[0])
                backend_dir = os.path.dirname(backend_pkg.__file__)
                paths.append(os.path.dirname(backend_dir))
        return paths

    def run_test(self, script, args, settings_file=None, apps=None):
        project_dir = test_dir
        base_dir = os.path.dirname(test_dir)
        # The base dir for Django's tests is one level up.
        tests_dir = os.path.dirname(os.path.dirname(__file__))
        # The base dir for Django is one level above the test dir. We don't use
        # `import django` to figure that out, so we don't pick up a Django
        # from site-packages or similar.
        django_dir = os.path.dirname(tests_dir)
        ext_backend_base_dirs = self._ext_backend_paths()

        # Remember the old environment
        old_django_settings_module = os.environ.get('DJANGO_SETTINGS_MODULE', None)
        if sys.platform.startswith('java'):
            python_path_var_name = 'JYTHONPATH'
        else:
            python_path_var_name = 'PYTHONPATH'

        old_python_path = os.environ.get(python_path_var_name, None)
        old_cwd = os.getcwd()

        # Set the test environment
        if settings_file:
            os.environ['DJANGO_SETTINGS_MODULE'] = settings_file
        elif 'DJANGO_SETTINGS_MODULE' in os.environ:
            del os.environ['DJANGO_SETTINGS_MODULE']
        python_path = [base_dir, django_dir, tests_dir]
        python_path.extend(ext_backend_base_dirs)
{'fraction_non_alphanumeric': 0.095995995995996, 'fraction_numerical': 0.0004004004004004004, 'mean_word_length': 2.3810490693739426, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5690925', 'n_tokens_mistral': 2973, 'n_tokens_neox': 2900, 'n_words': 733}