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

Copyright (c) 1999-2019, 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, runargv):
    
    # Find any --settings on the command line
    settings_prefix = '--settings='
    for a in runargv:
        if a.startswith(settings_prefix):
            name = a[len(settings_prefix):]
            if name != '':
                os.environ['DJANGO_SETTINGS_MODULE'] = name

    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.join(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 len(parts) > 1 and 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
        py_file = find_py_file('.'.join(part_list), manage_py)
        if py_file is None or os.path.basename(py_file) == '__init__.py':
            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)
            code_filename, lineno = self._sourceCodeLocation(test)
            if self.kSpecialImportErrorHandling and isinstance(test, unittest.loader._FailedTest):
                if self._test_no <= len(self._test_name_list) - 1:
                    name = self._test_name_list[self._test_no]
                else:
                    name = test._testMethodName
            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):
                if self._test_no <= len(self._test_file_list) - 1:
                    return self._test_file_list[self._test_no], -1
                else:
                    pathname, lineno = wingtest_common.FindSourceLocationFromLoaderFailedTest(test)
                    if pathname is not None:
                        return pathname, lineno
            
            if 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
            orig_cls_name = None
            orig_exc_msg = None
            et, ev, tb = err
            if self.kSpecialImportErrorHandling and isinstance(ev, ImportError):
                codefile, lineno = self._sourceCodeLocation(test)
                first_line, orig_cls_name, orig_exc_msg, tb_item_list = wingtest_common.ParseUnittestLoaderFailedTest(test)
                override_tb = [(pathname, lineno, code_line) for 
                               pathname, lineno, co_name, code_line in tb_item_list]
                #for tb_item in tb_item_list:
                    
                #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 = [(codefile, lineno, '')]
                #except:
                    #pass
            unittest.TestResult.addError(self, test, err)
            self.stream._write_exc_info(err, override_tb=override_tb, override_cls_name=orig_cls_name, override_msg=orig_exc_msg)
            self.stream.write_tag('result', wingtest_common.ERROR)

    runargv = wingtest_common.SetupSysArgv(argv, get_only=True)
    manage_dir = wingtest_common.process_directory_arg(argv)
    manage_dir_from_django = init_django(argv, runargv)
    # Django seems to return the site dir, which isn't generally where
    # manage.py is; it's in the parent of the site dir
    if manage_dir is None or not os.path.isfile(os.path.join(manage_dir, 'manage.py')):
        manage_dir = manage_dir_from_django
    manage_py = os.path.join(manage_dir, 'manage.py')

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

    #wingtest_common.process_directory_arg(argv)
    test_name_list, test_file_list = get_test_name_list(argv, manage_py)
    
    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'] + runargv + test_name_list
    #sys.stderr.write(str(sys.argv) + '\n')
    
    # Django assumes you run tests from the directory where manage.py is located; added 6/21/24
    # to deal with cases where Initial Directory is set in the Project
    os.chdir(manage_dir)
    
    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:
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__
        xmlout.finish()
        
if __name__ == '__main__':
    main(list(sys.argv))
