Ejemplo n.º 1
0
 def test_import_error(self):
     "Test for #12658 - Tests with ImportError's shouldn't fail silently"
     from django.apps import AppConfig
     from django.test.simple import get_tests
     app_config = AppConfig.create('test_runner_invalid_app')
     app_config.import_models({})
     with self.assertRaises(ImportError):
         get_tests(app_config)
Ejemplo n.º 2
0
 def test_import_error(self):
     "Test for #12658 - Tests with ImportError's shouldn't fail silently"
     from django.apps import AppConfig
     from django.test.simple import get_tests
     app_config = AppConfig.create('test_runner_invalid_app')
     app_config.import_models({})
     with self.assertRaises(ImportError):
         get_tests(app_config)
Ejemplo n.º 3
0
def my_build_suite_one(app_module, label):
    """
    指定で始まるテストファイルを実行していく。
    """
    
    suite = unittest.TestSuite()
    org_test_module=simple.TEST_MODULE
    #テストモジュールを上書きする
    labels = label.split(".")
    n = 'test.%s' % labels[2] 
    simple.TEST_MODULE=n
    test_module = get_tests(app_module)

    if test_module:
        if hasattr(test_module, 'suite'):
            suite.addTest(test_module.suite())
        else:
            suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(test_module))
        try:
            suite.addTest(doctest.DocTestSuite(test_module,
                                                   checker=doctestOutputChecker,
                                                   runner=DocTestRunner))
        except ValueError:
            pass
    
    simple.TEST_MODULE=org_test_module
    return suite
Ejemplo n.º 4
0
    def handle(self, *args, **options):
        if len(args) < 1:
            raise CommandError("need at least one unit test TestClass")
        verbosity = int(options.get("verbosity", 0))

        call_command("zap", noinput=False, verbosity=verbosity, load_initial_data=False)
        #        for app in get_apps():
        #            call_command('sqlsequencereset', app)

        for test in args:
            parts = test.split(".")
            if len(parts) != 2:
                raise ValueError(
                    "Test label '%s' should be of the form app.TestCase or app.TestCase.test_method" % test
                )
            app_module = get_app(parts[0])
            test_module = get_tests(app_module)
            TestClass = getattr(app_module, parts[1], None)
            if TestClass is None:
                if test_module:
                    TestClass = getattr(test_module, parts[1], None)

            if issubclass(TestClass, unittest.TestCase):
                for f in TestClass.fixtures:
                    if verbosity > 0:
                        print "Looking for fixture `%s`" % f
                    call_command("xloaddata", f, verbosity=verbosity)
Ejemplo n.º 5
0
    def build_suite(self, test_labels, extra_tests=None, **kwargs):
        """ Default behaviour is augmented to improve test discovery """
        sooper = super(XmlDjangoTestSuiteRunner,self)
        suite  = sooper.build_suite(test_labels, extra_tests=extra_tests, **kwargs)

        ## This section finds tests that were skipped due to
        ## duplicate app names. (code adapted from django.test.simple)
        for test_label in test_labels:
            all_apps = get_apps(test_label)
            if len(all_apps) > 1:
                leftover_apps = [ app for app in all_apps if app!=get_app(test_label) ]
                for app_module in leftover_apps:
                    # Check to see if a separate 'tests' module
                    # exists parallel to the "models" module
                    test_module = get_tests(app_module)
                    if test_module:
                        new_suite = unittest.defaultTestLoader.loadTestsFromModule(test_module)
                        if new_suite._tests:
                            suite.addTests(new_suite._tests)
                            msg       = "Discovered {N} extra tests for shadowed appname: {A}"
                            msg_kargs = dict(N=len(new_suite._tests), A=app_module.__name__)
                        else:
                            msg = "Discovered shadowed appname \"{A}\" but no tests were found"
                            msg_kargs = dict(A=app_module.__name__)
                        self.report(msg, **msg_kargs)
        return suite
Ejemplo n.º 6
0
def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
    """Test runner to support many DocTests *.txt files and TestUnits *.py
    using a setting TEST_FILES in app.tests module"""
    for app in get_apps():
        test_mod = get_tests(app)

        if not test_mod or hasattr(test_mod, 'suite'):
            continue

        suites = []

        # DocTest files
        for filename in getattr(test_mod, 'DOCTEST_FILES', []):
            try:
                suites.append(doctest.DocFileSuite(
                    filename,
                    package=test_mod,
                    encoding='utf-8',
                    ))
            except TypeError:
                suites.append(doctest.DocFileSuite(
                    filename,
                    package=test_mod,
                    ))

        # Unit Tests modules
        for module in getattr(test_mod, 'UNITTEST_MODULES', []):
            suites.append(unittest.TestLoader().loadTestsFromModule(module))

        # Sets the 'suites' attribute to test module
        if suites:
            print suites
            test_mod.suite = lambda: unittest.TestSuite(suites)

    return old_run_tests(test_labels, verbosity, interactive, extra_tests)
Ejemplo n.º 7
0
 def test_get_tests(self):
     "Check that the get_tests helper function can find tests in a directory"
     from django.apps import AppConfig
     from django.test.simple import get_tests
     app_config = AppConfig.create('test_runner.valid_app')
     app_config.import_models({})
     tests = get_tests(app_config)
     self.assertIsInstance(tests, types.ModuleType)
Ejemplo n.º 8
0
 def test_get_tests(self):
     "Check that the get_tests helper function can find tests in a directory"
     from django.apps import AppConfig
     from django.test.simple import get_tests
     app_config = AppConfig.create('test_runner.valid_app')
     app_config.import_models({})
     tests = get_tests(app_config)
     self.assertIsInstance(tests, types.ModuleType)
Ejemplo n.º 9
0
def build_suite(app_module, test_type, host):
    """
    Create a complete Django test suite for the provided application module.
    """
    suite = unittest.TestSuite()

    # Load unit and doctests in the models.py module. If module has
    # a suite() method, use it. Otherwise build the test suite ourselves.
    if hasattr(app_module, "suite"):
        suite.addTest(app_module.suite())
    else:
        suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(app_module))
        try:
            suite.addTest(doctest.DocTestSuite(app_module, checker=doctestOutputChecker, runner=DocTestRunner))
        except ValueError:
            # No doc tests in models.py
            pass

    # Check to see if a separate 'tests' module exists parallel to the
    # models module
    test_module = get_tests(app_module)
    if test_module:
        # Load unit and doctests in the tests.py module. If module has
        # a suite() method, use it. Otherwise build the test suite ourselves.
        if hasattr(test_module, "suite"):
            suite.addTest(test_module.suite())
        else:
            # Add the tests to the test suite based on test_type selected and
            # the attribute "type" of the class
            for name, obj in inspect.getmembers(test_module):
                if not inspect.isclass(obj):
                    continue
                setattr(obj, "host", host)
                if test_type == "both":
                    suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(obj))
                    continue
                if hasattr(obj, "test_type"):
                    if test_type == "funct" and getattr(obj, "test_type") == "funct":
                        suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(obj))
                        continue
                    elif getattr(obj, "test_type") == "unit" and test_type == "unit":
                        suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(obj))
                        continue
                else:
                    if test_type == "unit":
                        suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(obj))
                        continue
            # suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(
            #     test_module))
            try:
                suite.addTest(doctest.DocTestSuite(test_module, checker=doctestOutputChecker, runner=DocTestRunner))
            except ValueError:
                # No doc tests in tests.py
                pass
    return suite
Ejemplo n.º 10
0
Archivo: test.py Proyecto: OspreyX/flow
def build_suite(app_module):
    test_module = get_tests(app_module)
    if test_module:
        # Load unit and doctests in the tests.py module. If module has
        # a suite() method, use it. Otherwise build the test suite ourselves.
        if hasattr(test_module, 'suite'):
            suite = test_module.suite()
        else:
            suite = TestCaseSuite()
            suite.addTest(defaultTestLoader.loadTestsFromModule(test_module))
    return suite
Ejemplo n.º 11
0
def build_suite(app_module):
    test_module = get_tests(app_module)
    if test_module:
        # Load unit and doctests in the tests.py module. If module has
        # a suite() method, use it. Otherwise build the test suite ourselves.
        if hasattr(test_module, 'suite'):
            suite = test_module.suite()
        else:
            suite = TestCaseSuite()
            suite.addTest(defaultTestLoader.loadTestsFromModule(test_module))
    return suite
Ejemplo n.º 12
0
def build_suite(app_module):
    """
    Create a complete Django test suite for the provided application module.
    """
    suite = unittest.TestSuite()

    # Load unit and doctests in the models.py module. If module has
    # a suite() method, use it. Otherwise build the test suite ourselves.
    if hasattr(app_module, 'suite'):
        test = app_module.suite()
        if len(test._tests) > 0:
            suite.addTests(test._tests)
    else:
        test = unittest.TestLoader().loadTestsFromModule(app_module)
        if len(test._tests) > 0:
            suite.addTests(test._tests)
        try:
            test = doctest.DocTestSuite(app_module,
                                        checker=doctestOutputChecker,
                                        runner=DocTestRunner)
            if len(test._tests) > 0:
                suite.addTests(test._tests)
        except ValueError:
            # No doc tests in models.py
            pass

    # Check to see if a separate 'tests' module exists parallel to the
    # models module
    test_module = get_tests(app_module)
    if test_module:
        # Load unit and doctests in the tests.py module. If module has
        # a suite() method, use it. Otherwise build the test suite ourselves.
        if hasattr(test_module, 'suite'):
            test = test_module.suite()
            if len(test._tests) > 0:
                suite.addTests(test._tests)
        else:
            test = unittest.TestLoader().loadTestsFromModule(test_module)
            if len(test._tests) > 0:
                suite.addTests(test._tests)
            try:
                test = doctest.DocTestSuite(test_module,
                                            checker=doctestOutputChecker,
                                            runner=DocTestRunner)
                if len(test._tests) > 0:
                    suite.addTests(test._tests)
            except ValueError:
                # No doc tests in tests.py
                pass
    return suite
Ejemplo n.º 13
0
def build_suite(app_module):
    """
    Create a complete Django test suite for the provided application module.
    """
    suite = unittest.TestSuite()

    # Load unit and doctests in the models.py module. If module has
    # a suite() method, use it. Otherwise build the test suite ourselves.
    if hasattr(app_module, 'suite'):
        test = app_module.suite()
        if len(test._tests) > 0:
            suite.addTests(test._tests)
    else:
        test = unittest.TestLoader().loadTestsFromModule(app_module)
        if len(test._tests) > 0:
            suite.addTests(test._tests)
        try:
            test = doctest.DocTestSuite(app_module,
                checker=doctestOutputChecker, runner=DocTestRunner)
            if len(test._tests) > 0:
                suite.addTests(test._tests)
        except ValueError:
            # No doc tests in models.py
            pass

    # Check to see if a separate 'tests' module exists parallel to the
    # models module
    test_module = get_tests(app_module)
    if test_module:
        # Load unit and doctests in the tests.py module. If module has
        # a suite() method, use it. Otherwise build the test suite ourselves.
        if hasattr(test_module, 'suite'):
            test = test_module.suite()
            if len(test._tests) > 0:
                suite.addTests(test._tests)
        else:
            test = unittest.defaultTestLoader.loadTestsFromModule(test_module)
            if len(test._tests) > 0:
                suite.addTests(test._tests)
            try:
                test = doctest.DocTestSuite(test_module,
                    checker=doctestOutputChecker, runner=DocTestRunner)
                if len(test._tests) > 0:
                    suite.addTests(test._tests)
            except ValueError:
                # No doc tests in tests.py
                pass
    return suite
Ejemplo n.º 14
0
def build_suite(app_module):
    """
    Create a complete Django test suite for the provided application module.

    This overrides Django's original `django.test.simple.build_suite()` because
    we need to pass the `REPORT_ONLY_FIRST_FAILURE` option flag to
    `DocTestSuite` instances.
    """
    suite = TestSuite()

    _add_tests_for_module(suite, app_module)

    # Check to see if a separate 'tests' module exists parallel to the
    # models module
    test_module = get_tests(app_module)
    if test_module:
        _add_tests_for_module(suite, test_module)

    return suite
Ejemplo n.º 15
0
 def build_suite(self, test_labels, extra_tests=None, **kwargs):
     new_labels = []
     for test_label in test_labels:
         parts = test_label.split('|')
         test_labels_exclude = None
         if len(parts) == 2:
             test_label = parts[0]
             test_labels_exclude = parts[1].split(',')
         
         parts = test_label.split('.')
         
         if len(parts) > 3 or len(parts) < 1:
             new_labels.append(test_label)
             continue
         
         app_module = get_app(parts[0])
         test_module = get_tests(app_module)
         
         classes = None
         
         if len(parts) == 1:
             classes = _expand_regex_classes(test_module, '')
             new_labels.extend([".".join((parts[0], klass)) for klass in classes])
         elif len(parts) == 2:
             classes = _expand_regex_classes(test_module, parts[1])
             new_labels.extend([".".join((parts[0], klass)) for klass in classes])
         else:
             classes = _expand_regex_classes(test_module, parts[1])
             for klass in classes:
                 methods = _expand_regex_method(test_module, klass, parts[2])
                 new_labels.extend([".".join((parts[0], klass, method)) for method in methods])
         
         if test_labels_exclude is not None:
             for test_label_exclude in test_labels_exclude:
                 try:
                     new_labels.remove(".".join((parts[0], test_label_exclude)))
                 except ValueError:
                     raise ValueError("Test '%s' to exclude not found." % test_label_exclude)
     
     return super(EOxServerTestRunner, self).build_suite(new_labels, extra_tests, **kwargs)
Ejemplo n.º 16
0
def my_build_suite(app_module):
    
    suite = unittest.TestSuite()
    org_test_module=simple.TEST_MODULE
    for n in my_test_modules:
        #テストモジュールを上書きする
        simple.TEST_MODULE=n
        test_module = get_tests(app_module)

        if test_module:
            if hasattr(test_module, 'suite'):
                suite.addTest(test_module.suite())
            else:
                suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(test_module))
                try:
                    suite.addTest(doctest.DocTestSuite(test_module,
                                                       checker=doctestOutputChecker,
                                                       runner=DocTestRunner))
                except ValueError:
                    pass
    
    simple.TEST_MODULE=org_test_module
    return suite
Ejemplo n.º 17
0
def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
    """Test runner to support many DocTests *.txt files and TestUnits *.py
    using a setting TEST_FILES in app.tests module"""
    for app in get_apps():
        test_mod = get_tests(app)

        if not test_mod or hasattr(test_mod, 'suite'):
            continue

        suites = []

        # DocTest files
        for filename in getattr(test_mod, 'DOCTEST_FILES', []):
            try:
                suites.append(
                    doctest.DocFileSuite(
                        filename,
                        package=test_mod,
                        encoding='utf-8',
                    ))
            except TypeError:
                suites.append(
                    doctest.DocFileSuite(
                        filename,
                        package=test_mod,
                    ))

        # Unit Tests modules
        for module in getattr(test_mod, 'UNITTEST_MODULES', []):
            suites.append(unittest.TestLoader().loadTestsFromModule(module))

        # Sets the 'suites' attribute to test module
        if suites:
            print suites
            test_mod.suite = lambda: unittest.TestSuite(suites)

    return old_run_tests(test_labels, verbosity, interactive, extra_tests)
Ejemplo n.º 18
0
def my_build_suite_auto(app_module, label):
    """
    test/test_で始まるテストファイルを実行していく。
    """
    
    suite = unittest.TestSuite()
    org_test_module=simple.TEST_MODULE
    find_dir = './%s/test/' % label
    file_list = os.listdir(find_dir)
    re_compile = re.compile('^test_.*?\.py$')
    for file in file_list:
        if re_compile.search(file):
            file_data = file.split('.')
            try:
                n = file_data[0]
            except IndexError:
                print "Error!! no module name %s" % file
            else:
                #テストモジュールを上書きする
                n = 'test.%s' % n 
                simple.TEST_MODULE=n
                test_module = get_tests(app_module)
        
                if test_module:
                    if hasattr(test_module, 'suite'):
                        suite.addTest(test_module.suite())
                    else:
                        suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(test_module))
                        try:
                            suite.addTest(doctest.DocTestSuite(test_module,
                                                               checker=doctestOutputChecker,
                                                               runner=DocTestRunner))
                        except ValueError:
                            pass
    
    simple.TEST_MODULE=org_test_module
    return suite
Ejemplo n.º 19
0
    def find_tests_and_apps(self, label):
        """Construct a test suite of all test methods with the specified name.
        Returns an instantiated test suite corresponding to the label provided.
        """

        tests = []
        from unittest import TestLoader

        loader = TestLoader()

        from django.db.models import get_app, get_apps

        for app_models_module in get_apps():
            app_name = app_models_module.__name__.rpartition(".")[0]
            if app_name == label:
                from django.test.simple import build_suite

                tests.append(build_suite(app_models_module))

            from django.test.simple import get_tests

            app_tests_module = get_tests(app_models_module)

            for sub_module in [m for m in app_models_module, app_tests_module if m is not None]:

                # print "Checking for %s in %s" % (label, sub_module)

                for name in dir(sub_module):
                    obj = getattr(sub_module, name)
                    import types

                    if isinstance(obj, (type, types.ClassType)) and issubclass(obj, unittest.TestCase):

                        test_names = loader.getTestCaseNames(obj)
                        # print "Checking for %s in %s.%s" % (label, obj, test_names)
                        if label in test_names:
                            tests.append(loader.loadTestsFromName(label, obj))

                try:
                    module = sub_module
                    from django.test import _doctest as doctest
                    from django.test.testcases import DocTestRunner

                    doctests = doctest.DocTestSuite(module, checker=self.doctestOutputChecker, runner=DocTestRunner)
                    # Now iterate over the suite, looking for doctests whose name
                    # matches the pattern that was given
                    for test in doctests:
                        if test._dt_test.name in (
                            "%s.%s" % (module.__name__, ".".join(parts[1:])),
                            "%s.__test__.%s" % (module.__name__, ".".join(parts[1:])),
                        ):
                            tests.append(test)
                except TypeError as e:
                    raise Exception("%s appears not to be a module: %s" % (module, e))
                except ValueError:
                    # No doctests found.
                    pass

        # If no tests were found, then we were given a bad test label.
        if not tests:
            raise ValueError(("Test label '%s' does not refer to a " + "test method or app") % label)

        # Construct a suite out of the tests that matched.
        return unittest.TestSuite(tests)
Ejemplo n.º 20
0
 def test_get_tests(self):
     "Check that the get_tests helper function can find tests in a directory"
     module = import_module(TEST_APP_OK)
     tests = get_tests(module)
     self.assertIsInstance(tests, type(module))
Ejemplo n.º 21
0
 def test_get_tests(self):
     "Check that the get_tests helper function can find tests in a directory"
     from django.test.simple import get_tests
     module = import_module(TEST_APP_OK)
     tests = get_tests(module)
     self.assertIsInstance(tests, type(module))
Ejemplo n.º 22
0
def my_build_test(label):
    """Construct a test case with the specified label. Label should be of the
    form model.TestClass or model.TestClass.test_method. Returns an
    instantiated test or test suite corresponding to the label provided.
    """
    parts = label.split('.')
    if len(parts) < 2 or len(parts) > 3:
        raise ValueError("Test label '%s' should be of the form app.TestCase or app.TestCase.test_method" % label)

    #
    # First, look for TestCase instances with a name that matches
    #
    app_module = get_app(parts[0])
    TestClass = getattr(app_module, parts[1], None)
    
    #テストモジュールを上書きする
    n = label
    simple.TEST_MODULE=n
    test_module = get_tests(app_module)

    # Couldn't find the test class in models.py; look in tests.py
    if TestClass is None:
        if test_module:
            TestClass = getattr(test_module, parts[1], None)

    try:
        if issubclass(TestClass, unittest.TestCase):
            if len(parts) == 2: # label is app.TestClass
                try:
                    return unittest.TestLoader().loadTestsFromTestCase(TestClass)
                except TypeError:
                    raise ValueError("Test label '%s' does not refer to a test class" % label)
            else: # label is app.TestClass.test_method
                return TestClass(parts[2])
    except TypeError:
        # TestClass isn't a TestClass - it must be a method or normal class
        pass

    #
    # If there isn't a TestCase, look for a doctest that matches
    #
    tests = []
    for module in app_module, test_module:
        try:
            doctests = doctest.DocTestSuite(module,
                                            checker=doctestOutputChecker,
                                            runner=DocTestRunner)
            # Now iterate over the suite, looking for doctests whose name
            # matches the pattern that was given
            for test in doctests:
                if test._dt_test.name in (
                        '%s.%s' % (module.__name__, '.'.join(parts[1:])),
                        '%s.__test__.%s' % (module.__name__, '.'.join(parts[1:]))):
                    tests.append(test)
        except ValueError:
            # No doctests found.
            pass

    # If no tests were found, then we were given a bad test label.
    if not tests:
        raise ValueError("Test label '%s' does not refer to a test" % label)

    # Construct a suite out of the tests that matched.
    return unittest.TestSuite(tests)
Ejemplo n.º 23
0
def build_test(label):
    """
    Construct a test case with the specified label. Label should be of the
    form model.TestClass or model.TestClass.test_method. Returns an
    instantiated test or test suite corresponding to the label provided.

    """
    app_name = extract_app_name(label)
    if not app_name:
        raise Exception('App name could not be determined from label %s' % label)

    remainder = label[len(app_name)+1:]
    if not remainder:
        " this is an app, not a specific test case "
        pass

    parts = [app_name] + remainder.split('.')
    if len(parts) < 2 or len(parts) > 3:
        raise ValueError("Test label '%s' should be of the form app.TestCase "
                         "or app.TestCase.test_method" % label)

    #
    # First, look for TestCase instances with a name that matches
    #
    app_module = get_app(parts[0])
    test_module = get_tests(app_module)
    TestClass = getattr(app_module, parts[1], None)

    # Couldn't find the test class in models.py; look in tests.py
    if TestClass is None:
        if test_module:
            TestClass = getattr(test_module, parts[1], None)

    try:
        if issubclass(TestClass, (unittest.TestCase, real_unittest.TestCase)):
            if len(parts) == 2: # label is app.TestClass
                try:
                    return unittest.TestLoader() \
                        .loadTestsFromTestCase(TestClass)
                except TypeError:
                    raise ValueError(
                        "Test label '%s' does not refer to a test class"
                        % label)
            else: # label is app.TestClass.test_method
                return TestClass(parts[2])
    except TypeError:
        # TestClass isn't a TestClass - it must be a method or normal class
        pass

    #
    # If there isn't a TestCase, look for a doctest that matches
    #
    tests = []
    for module in app_module, test_module:
        try:
            doctests = make_doctest(module)
            # Now iterate over the suite, looking for doctests whose name
            # matches the pattern that was given
            for test in doctests:
                if test._dt_test.name in (
                        '%s.%s' % (module.__name__, '.'.join(parts[1:])),
                        '%s.__test__.%s' % (
                            module.__name__, '.'.join(parts[1:]))):
                    tests.append(test)
        except ValueError:
            # No doctests found.
            pass

    # If no tests were found, then we were given a bad test label.
    if not tests:
        raise ValueError("Test label '%s' does not refer to a test" % label)

    # Construct a suite out of the tests that matched.
    return unittest.TestSuite(tests)