# coding:utf-8
#########################################################################
""" Run Django unit tests (both unittest and doctest tests)

Copyright (c) 1999-2012, Archaeopteryx Software, Inc.

Written by Stephan R.A. Deibel and John P. Ehresman

Thanks to Cédric RICARD for the initial version of this code

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
#########################################################################

import sys
import unittest
if sys.hexversion >= 0x03070000:
    import importlib
else:
    import imp
import os

def get_project_dir_from_argv(argv):
    # Django <= 1.3 fall-back
    dir_arg_prefix = '--directory='
    if len(argv) > 1 and argv[1][:len(dir_arg_prefix)] == dir_arg_prefix:
        module_dir = argv[1][len(dir_arg_prefix):]
    else:
        module_dir = os.getcwd()
    return module_dir
    
def get_manage_dir_from_settings(settings_mod):
    # For Django 1.4+ only
    if '__init__.py' in settings_mod.__file__:
        p = os.path.dirname(settings_mod.__file__)
    else:
        p = settings_mod.__file__
    project_directory, settings_filename = os.path.split(p)
    if project_directory == os.curdir or not project_directory:
        project_directory = os.getcwd()
        
    return os.path.dirname(project_directory)
    
def init_django(argv):
    try:
        from django import VERSION
        if VERSION[0] == 1 and VERSION[1] < 4:
            django_lt_14 = True
        else:
            django_lt_14 = False
    except:
        django_lt_14 = True
        
    try:
        from django.conf import settings
        try:
            # Needed in Django 1.8+; not sure if it fails in earlier versions
            import django
            django.setup()
        except:
            pass
        from django.core.management import import_module
        module = import_module(settings.SETTINGS_MODULE)
        if django_lt_14:
            from django.core.management import setup_environ
            manage_dir = setup_environ(module, settings.SETTINGS_MODULE)
        else:
            manage_dir = get_manage_dir_from_settings(module)
    except:
        project_dir = get_project_dir_from_argv(argv)
        sys.path.insert(0, os.path.abspath(project_dir))
        sys.path.append(os.path.abspath(os.path.join(project_dir, '..')))
        import settings
        if django_lt_14:
            from django.core.management import setup_environ
            manage_dir = setup_environ(settings)
        else:
            manage_dir = get_manage_dir_from_settings(settings)
        
    return manage_dir
    
def find_py_file(test_name, manage_py):
    """ Find .py containing test name.  None returned if no file is found. """
    
    manage_dir = os.path.dirname(manage_py)
    
    part_list = test_name.split('.')
    
    base_dir = manage_dir
    for i, part in enumerate(part_list):
        if os.path.exists(os.path.join(base_dir, part+'.py')):
            return os.path.join(base_dir, part+'.py')
        if not os.path.isdir(os.path.join(base_dir, part)):
            return None
        if i == len(part_list) - 1 and os.path.exists(os.path.join(base_dir, part, '__init__.py')):
            return os.path.exists(os.path.join(base_dir, part, '__init__.py'))
        base_dir = os.path.join(base_dir, part)
    
    return None
    
def shorten_test_name(name, code_filename, manage_py):
    """ Try to shorten name by removing the leading sitename.apps and the tests
    following the app name. """
    
    manage_dir = os.path.dirname(manage_py)
    django_sitename = os.environ.get('DJANGO_SITENAME')
    
    parts = name.split('.')
    
    if parts[:2] == [django_sitename, 'apps']:
        parts = parts[2:]
        if parts[1] == 'tests':
            if os.path.basename(code_filename) == 'tests.py':
                del parts[1]
            elif (os.path.isdir(os.path.join(manage_dir, django_sitename, 'apps', *parts[:2]))
                  and len(parts) > 2):
                del parts[1]

    short_name = '.'.join(parts)
    if find_py_file(short_name, manage_py) is not None:
        return name

    return short_name

def lengthen_test_name(name, manage_py):
    """ Lengthen the name -- the inverse of shorten_test_name """
    
    if find_py_file(name, manage_py) is not None:
        return name
    
    manage_dir = os.path.dirname(manage_py)
    django_sitename = os.environ.get('DJANGO_SITENAME')
    
    part_list = name.split('.')

    if (not os.path.isdir(os.path.join(manage_dir, part_list[0]))
          and os.path.isdir(os.path.join(manage_dir, django_sitename, 'apps', part_list[0]))):
        part_list = [django_sitename, 'apps'] + part_list
        if find_py_file('.'.join(part_list), manage_py) is None:
            app_dir =  os.path.join(manage_dir, *part_list[:3])
            if os.path.isdir(app_dir) and (os.path.isfile(os.path.join(app_dir, 'tests.py'))
                                           or os.path.isfile(os.path.join(app_dir, 'tests', '__init__.py'))):
                part_list.insert(3, 'tests')
            
    if find_py_file('.'.join(part_list), manage_py) is not None:
        return '.'.join(part_list)
    
    return name
    
def get_test_name_list(argv, manage_py):
    """ Get the list of test names out of argv """
    
    test_name_list=[]
    test_file_list = []
    for arg in argv[1:]:
        if not arg.startswith('-') and arg != 'manage':
            if arg.startswith('manage.'):
                arg = arg[len('manage.'):]
                arg = lengthen_test_name(arg, manage_py)
            test_name_list.append(arg)
            testfile = find_py_file(arg, manage_py)
            test_file_list.append(testfile)
    return test_name_list, test_file_list
    
def main(argv):
    #sys.stderr.write(str(argv) + '\n')
    
    # XXX Hack to allow setting a different settings module for testing only
    if 'WING_TEST_DJANGO_SETTINGS_MODULE' in os.environ:
        os.environ['DJANGO_SETTINGS_MODULE'] = os.environ['WING_TEST_DJANGO_SETTINGS_MODULE']
        
    if sys.hexversion >= 0x03070000:
        import importlib.machinery
        import importlib.util
        
        spec = importlib.machinery.PathFinder.find_spec('wingtest_common', [os.path.dirname(__file__)])
        if spec is None:
            raise ImportError("Could not import wingtest_common")
        wingtest_common = importlib.util.module_from_spec(spec)
        if wingtest_common is None:
            raise ImportError("Could not import wingtest_common")
        spec.loader.exec_module(wingtest_common)
    else:        
        f, filename, info = imp.find_module('wingtest_common', [os.path.dirname(__file__)])
        try:
            wingtest_common = imp.load_module('wingtest_common', f, filename, info)
        finally:
            f.close()
        
    if 0:
        import wingtest_common
        
    class CDjangoXMLTestResult(wingtest_common.XmlTestResult):
        
        kSpecialImportErrorHandling = sys.hexversion >= 0x03040000
        
        def __init__(self, stream, manage_py, test_name_list, test_file_list):
            
            wingtest_common.XmlTestResult.__init__(self, stream)
            
            self._manage_py = manage_py
            self._test_name_list = test_name_list
            self._test_file_list = test_file_list
            self._test_no = -1
            
        def startTest(self, test):
            self._test_no += 1
            unittest.TestResult.startTest(self, test)
            class_filename = self._testClassFilename(test)
            code_filename, lineno = self._sourceCodeLocation(test)
            if self.kSpecialImportErrorHandling and isinstance(test, unittest.loader._FailedTest) and self._test_no <= len(self._test_name_list) - 1:
                name = self._test_name_list[self._test_no]
            elif hasattr(test, '_dt_test'):
                name = test.id()
                dt_module = None
                if test._dt_test.globs is not None:
                    dt_module = test._dt_test.globs.get('__name__')
                if dt_module is not None and name == dt_module:
                    name += '.(module docstring)'
                else:
                    name += ' docstring'
                    
                if name.startswith('django.contrib.'):
                    name = name[len('django.contrib.'):]
            else:
                name = self._testDottedName(test, remove_module=False)
                
            name = shorten_test_name(name, code_filename, self._manage_py)
            self.stream._start_test(name, self._manage_py,
                                    code_filename=code_filename, lineno=lineno)
            
        def _sourceCodeLocation(self, test):
            if self.kSpecialImportErrorHandling and isinstance(test, unittest.loader._FailedTest) and self._test_no <= len(self._test_file_list) - 1:
                return self._test_file_list[self._test_no], -1
            elif hasattr(test, '_dt_test'):
                if not test._dt_test.lineno:
                    lineno = 0
                else:
                    lineno = test._dt_test.lineno
                return test._dt_test.filename, lineno
            else:
                fn, lineno = wingtest_common.XmlTestResult._sourceCodeLocation(self, test)
                return fn, lineno - 1

        def addError(self, test, err):
            override_tb = None
            et, ev, tb = err
            if self.kSpecialImportErrorHandling and isinstance(ev, ImportError):
                codefile, lineno = self._sourceCodeLocation(test)
                try:
                    errlines = ev.args[0].splitlines()
                    for i in range(len(errlines)-1, -1, -1):
                        if codefile in errlines[i]:
                            parts = errlines[i].split(',')
                            label, lineno = parts[1].split()
                            break
                    override_tb = [(lineno, codefile, '')]
                except:
                    pass
            unittest.TestResult.addError(self, test, err)
            self.stream._write_exc_info(err, override_tb=override_tb)
            self.stream.write_tag('result', wingtest_common.ERROR)

    manage_dir = init_django(argv)
    manage_py = os.path.join(manage_dir, 'manage.py')

    xmlout = wingtest_common.CreateOutputStream(argv)
    sys.stdout = sys.stderr = xmlout

    test_name_list, test_file_list = get_test_name_list(argv, manage_py)
    wingtest_common.process_directory_arg(argv)
    
    result = CDjangoXMLTestResult(sys.stdout, manage_py, test_name_list, test_file_list)

    # Add 'test' to sys.argv since some code uses it to decide if 
    # it's being tested or just run
    sys.argv = [os.path.join(manage_dir, 'manage.py'), 'test'] + test_name_list
    #sys.stderr.write(str(sys.argv) + '\n')
    
    from django.conf import settings
    try:
        from django.test.simple import DjangoTestRunner, DjangoTestSuiteRunner
        test_base = DjangoTestRunner
    except:
        try:
            # Django <= 1.7
            from django.test.simple import DjangoTestSuiteRunner
        except:
            # Django 1.8+
            from django.test.utils import get_runner
            DjangoTestSuiteRunner = get_runner(settings)
        from unittest import TextTestRunner
        test_base = TextTestRunner

    # South (schema migration tool) does not use the 'test' command anymore
    if 'south' in settings.INSTALLED_APPS:

        try:
            # Older versions of South had this layout
            from south.management.commands.test import MigrateAndSyncCommand
        except ImportError:
            from south.management.commands import MigrateAndSyncCommand
        from django.core import management
        management.get_commands()
        
        # Point at the core syncdb command when creating tests; tests should
        # always be up to date with the most recent model structure
        if hasattr(settings, "SOUTH_TESTS_MIGRATE") and not settings.SOUTH_TESTS_MIGRATE:
            management._commands['syncdb'] = 'django.core'
        else:
            management._commands['syncdb'] = MigrateAndSyncCommand()
        
    class MyTestRunner(test_base):
        def __init__(self, testResult, **kwargs):
            super(MyTestRunner, self).__init__(**kwargs)
            self.testResult = testResult
            
        def _makeResult(self):
            return self.testResult

    class MyTestSuiteRunner(DjangoTestSuiteRunner):
        def __init__(self, testResult, **kwargs):
            super(MyTestSuiteRunner, self).__init__(**kwargs)
            self.testResult = testResult
            
        def run_suite(self, suite, **kwargs):
            return MyTestRunner(self.testResult, verbosity=self.verbosity, failfast=self.failfast).run(suite)
    
    runner = MyTestSuiteRunner(result, verbosity=0, interactive=False)
    try:
        try:
            failures = runner.run_tests(test_name_list)
        except SystemExit:
            raise
        except Exception:
            # Note that import error from test files might end up here
            if isinstance(xmlout, wingtest_common.XmlStream):
                xmlout._write_exc_info(sys.exc_info())
            else:
                exc_type, exc, tb = sys.exc_info()
                sys.excepthook(exc_type, exc, tb)
    finally:
        xmlout.finish()
        
if __name__ == '__main__':
    main(list(sys.argv))
