Esempio n. 1
0
 def __init__(self,
              config=None,
              importer=None,
              workingDir=None,
              selector=JUnitSelector):
     """Initialize a test loader
     """
     TestLoader.__init__(self, config, importer, workingDir, selector)
     log.debug("JUnitTestLoader.__init__(): config = %s", config)
     if hasattr(config.options, 'compiled_root'):
         self.compiledTestsRoot = config.options.compiled_root
         if os.name == "nt":
             self.compiledTestsRoot = self.compiledTestsRoot.replace(
                 "/", "\\")
     log.debug("Compiled root is %s, os is %s", self.compiledTestsRoot,
               os.name)
     # Each element of config.options.attr is a comma-separated list of
     # enabled of disabled test tags
     target_expression = ''
     for expression in config.options.eval_attr:
         if target_expression:
             target_expression = target_expression + '&'
         target_expression = target_expression + '(' + expression + ')'
     self.tags = process_expression(target_expression)
     if not self.tags:
         self.tags = 'checkin&!interactive'
         log.debug("JUnitTestLoader.__init__(): Set default test tasgs")
     log.debug("JUnitTestLoader.__init__(): self.tags: %s", self.tags)
 def test_next_batch_with_classes(self):
     r = multiprocess.MultiProcessTestRunner()
     l = TestLoader()
     tests = list(r.nextBatch(ContextSuite(
                 tests=[l.makeTest(T_fixt), l.makeTest(T)])))
     print(tests)
     self.assertEqual(len(tests), 3)
Esempio n. 3
0
    def _collect_tests_from_dir(self):
        """ Uses nose's collect plugin"""
        # from pprint import pprint
        # APP_ENGINE_TESTS_DIR = "/home/marcial/repos/flask_docker/src_panic_app/panic/tests/noses/test_appengine"
        from nose.config import Config
        conf = Config()
        from nose.loader import TestLoader
        loader = TestLoader()
        from nose.plugins.collect import CollectOnly, TestSuiteFactory, TestSuite
        collect = CollectOnly()
        collect.conf = conf
        collect.prepareTestLoader(loader)

        tests = loader.loadTestsFromDir(self.dir)

        suite = TestSuite()
        suite.addTests(tests)
        # from nose.core import TextTestRunner
        # TextTestRunner().run(suite)

        # ....:for test in suite._tests[0]._tests[0]:
        # ....:     print test.id()
        found = []
        self.traverse_recursive(suite, found)
        return found
 def setUp(self):
     self.runner = gmultiprocess.GeventedMultiProcessTestRunner(
         #stream=_WritelnDecorator(sys.stdout),
         verbosity=10,
         loaderClass=TestLoader,
         config=Config())
     self.loader = TestLoader()
Esempio n. 5
0
    def test_load_nested_generator(self):
        from nose.config import Config
        from nose.loader import TestLoader

        where = os.path.abspath(
            os.path.join(os.path.dirname(__file__), 'support', 'issue006'))
        l = TestLoader()
        testmod = next(iter(l.loadTestsFromName(where)))
        print(testmod)
        testmod.setUp()

        testcase = next(iter(testmod))
        expect = [['tests.Test1.test_nested_generator'],
                  [
                      'tests.Test1.test_nested_generator_mult(1,)',
                      'tests.Test1.test_nested_generator_mult(2,)',
                      'tests.Test1.test_nested_generator_mult(3,)'
                  ],
                  [
                      'tests.Test1.test_normal_generator(1,)',
                      'tests.Test1.test_normal_generator(2,)'
                  ]]
        for test in testcase:
            tests = list(map(str, test))
            print(tests)
            self.assertEqual(tests, expect.pop(0))
Esempio n. 6
0
 def run_test(self):
     rf = os.path.join(self.run_dir, 'RunFinished')
     self.run_finished = os.path.exists(rf)
     tl = TestLoader()
     tl.config.plugins = PluginManager(plugins=self.plugins)
     suite = tl.loadTestsFromDir(self.run_dir)
     nose.run(argv=self.args, suite=suite)
    def test_next_batch_can_split_set(self):

        mod_with_fixt2 = imp.new_module('mod_with_fixt2')
        sys.modules['mod_with_fixt2'] = mod_with_fixt2

        def setup():
            pass

        class Test(T):
            pass

        class Test_fixt(T_fixt):
            pass

        mod_with_fixt2.Test = Test
        mod_with_fixt2.Test_fixt = Test_fixt
        mod_with_fixt2.setup = setup
        mod_with_fixt2._multiprocess_can_split_ = True
        Test.__module__ = 'mod_with_fixt2'
        Test_fixt.__module__ = 'mod_with_fixt2'

        r = multiprocess.MultiProcessTestRunner()
        l = TestLoader()
        tests = list(r.nextBatch(l.loadTestsFromModule(mod_with_fixt2)))
        print(tests)
        self.assertEqual(len(tests), 3)
Esempio n. 8
0
    def test_load_in_def_order(self):
        from nose.loader import TestLoader

        where = os.path.abspath(
            os.path.join(os.path.dirname(__file__), 'support', 'bug105'))

        l = TestLoader()
        testmod = l.loadTestsFromDir(where).next()
        print
        testmod
        testmod.setUp()

        def fix(t):
            s = str(t)
            if ': ' in s:
                return s[s.index(': ') + 2:]
            return s

        tests = map(fix, testmod)
        print
        tests
        self.assertEqual(tests, [
            'tests.test_z', 'tests.test_a', 'tests.test_dz', 'tests.test_mdz',
            'tests.test_b'
        ])
Esempio n. 9
0
    def test_next_batch_can_split_set(self):

        mod_with_fixt2 = imp.new_module('mod_with_fixt2')
        sys.modules['mod_with_fixt2'] = mod_with_fixt2

        def setup():
            pass

        class Test(T):
            pass

        class Test_fixt(T_fixt):
            pass

        mod_with_fixt2.Test = Test
        mod_with_fixt2.Test_fixt = Test_fixt
        mod_with_fixt2.setup = setup
        mod_with_fixt2._multiprocess_can_split_ = True
        Test.__module__ = 'mod_with_fixt2'
        Test_fixt.__module__ = 'mod_with_fixt2'

        r = multiprocess.MultiProcessTestRunner()
        l = TestLoader()
        tests = list(r.nextBatch(l.loadTestsFromModule(mod_with_fixt2)))
        print tests
        self.assertEqual(len(tests), 3)
Esempio n. 10
0
 def test_next_batch_with_classes(self):
     r = multiprocess.MultiProcessTestRunner()
     l = TestLoader()
     tests = list(
         r.nextBatch(ContextSuite(
             tests=[l.makeTest(T_fixt), l.makeTest(T)])))
     print tests
     self.assertEqual(len(tests), 3)
Esempio n. 11
0
 def test_next_batch_with_generator_method(self):
     class Tg:
         def test_gen(self):
             for i in range(0, 3):
                 yield self.check, i
         def check(self, val):
             pass
     r = multiprocess.MultiProcessTestRunner()
     l = TestLoader()
     tests = list(r.nextBatch(l.makeTest(Tg)))
     print tests
     print [r.address(t) for t in tests]
Esempio n. 12
0
    def test_generator_yield_value(self):
        from nose.loader import TestLoader

        def test():
            pass
        def gen():
            yield test

        loader = TestLoader()
        suite = loader.loadTestsFromGenerator(gen, module=None)
        testcase = next(iter(suite))
        self.assertEqual(testcase.test.test, test)
Esempio n. 13
0
def run_nose():
    tl = TestLoader()
    ts = tl.loadTestsFromDir(tl.workingDir)
    rlst = TextTestRunner(stream=sys.stderr, descriptions=1, verbosity=2)
    tests = []
    for test in ts : 
        tests += test

    for test in tests :
        if type(test) == Test :
            test.runTest(rlst)
    #import pdb;pdb.set_trace()
    return rlst 
Esempio n. 14
0
    def test_generator_yield_value(self):
        from nose.loader import TestLoader

        def test():
            pass

        def gen():
            yield test

        loader = TestLoader()
        suite = loader.loadTestsFromGenerator(gen, module=None)
        testcase = iter(suite).next()
        self.assertEqual(testcase.test.test, test)
Esempio n. 15
0
    def test_next_batch_with_generator_method(self):
        class Tg:
            def test_gen(self):
                for i in range(0, 3):
                    yield self.check, i

            def check(self, val):
                pass

        r = multiprocess.MultiProcessTestRunner()
        l = TestLoader()
        tests = list(r.nextBatch(l.makeTest(Tg)))
        print tests
        print[r.address(t) for t in tests]
        self.assertEqual(len(tests), 1)
Esempio n. 16
0
    def test_multiprocess_unsafe(self):
        mod_unsafe = imp.new_module('mod_unsafe')
        sys.modules['mod_unsafe'] = mod_unsafe

        class Test(T):
            pass

        mod_unsafe._multiprocess_ = False
        mod_unsafe.Test = Test
        Test.__module__ = 'mod_unsafe'

        r = multiprocess.MultiProcessTestRunner()
        l = TestLoader()
        tests = list(r.nextBatch(l.loadTestsFromModule(mod_unsafe)))
        print tests
        self.assertEqual(len(tests), 2)
Esempio n. 17
0
def run_my_tests():
    all_tests = ()
    #for path in paths:
    all_tests = itertools.chain(all_tests,
                                TestLoader().loadTestsFromDir(paths))
    suite = LazySuite(all_tests)
    run(suite=suite)
Esempio n. 18
0
 def loadTestsFromFile(self, filename):
     """
     We'll exploit the knowledge of the selector implementation details:
     since the selector 'wants' only root build.xml file for JUnit-based
     tests, we can safely check initials and then fall back to inherited
     behavior or collect output for all tests.
     """
     log.debug("JUnitTestLoader.loadTestsFromFile(%s)", filename)
     if not filename.startswith(self.compiledTestsRoot):
         log.debug("JUnitTestLoader.loadTestsFromFile(): fall back to predefined behavior")
         log.debug("JUnitTestLoader.loadTestsFromFile(): compiledTestsRoot is %s", self.compiledTestsRoot)
         return TestLoader.loadTestsFromFile(self, filename)
     commandLine = self.prepareCommandLine()
     try:
         testOutput = self.executeTests(commandLine)
     except Exception as e:
         log.debug("Building JUnit test suite failed with message: %s",
                   str(e))
         return self.suiteClass(Failure(Exception,"Couldn't build compiled test suite."))
     log.debug("JUnitTestLoader.loadTestsFromFile(): got ant output:\n%s",
               testOutput)
     singleTestOutput, singleTestExceptions = self.filterTestOutput(testOutput)
     log.debug("JUnitTestLoader.loadTestsFromFile(): JUnit filtered output:")
     for line in singleTestOutput:
         log.debug("%s\n", line)
     log.debug("JUnitTestLoader.loadTestsFromFile(): %s",
               "JUnit filtered output finished.")
     loadedTests = self.makeTestCases(singleTestOutput,
                                      singleTestExceptions)
     log.debug("JUnitTestLoader.loadTestsFromFile(): loaded tests %s",
               loadedTests)
     log.debug("JUnitTestLoader.loadTestsFromFile(): suite class is %s",
               repr(self.suiteClass))
     return self.suiteClass(loadedTests)
Esempio n. 19
0
def run_my_tests():
    all_tests = ()
    for path in paths:
        all_tests = itertools.chain(all_tests, TestLoader().loadTestsFromDir(path))
    suite = LazySuite(all_tests)

    nose.run(suite=suite, argv=["--with-coverage", "--cover-html", "--cover-package=pyredux"])
 def setUp(self):
     self.runner = gmultiprocess.GeventedMultiProcessTestRunner(
         #stream=_WritelnDecorator(sys.stdout),
         verbosity=10,
         loaderClass=TestLoader,
         config=Config()
     )
     self.loader = TestLoader()
Esempio n. 21
0
def run_my_tests():
    all_tests = ()
    all_tests = itertools.chain(all_tests, TestLoader().loadTestsFromDir('.'))
    suite = LazySuite(all_tests)
    run(suite=suite,
        argv=[
            'run_all.py', '--cover-branches', '--with-coverage', '--cover-html'
        ])
Esempio n. 22
0
    def test_next_batch_with_module_fixt(self):
        mod_with_fixt = imp.new_module('mod_with_fixt')
        sys.modules['mod_with_fixt'] = mod_with_fixt

        def teardown():
            pass

        class Test(T):
            pass

        mod_with_fixt.Test = Test
        mod_with_fixt.teardown = teardown
        Test.__module__ = 'mod_with_fixt'

        r = multiprocess.MultiProcessTestRunner()
        l = TestLoader()
        tests = list(r.nextBatch(l.loadTestsFromModule(mod_with_fixt)))
        print tests
        self.assertEqual(len(tests), 1)
    def test_next_batch_with_module_fixt(self):
        mod_with_fixt = imp.new_module('mod_with_fixt')
        sys.modules['mod_with_fixt'] = mod_with_fixt

        def teardown():
            pass

        class Test(T):
            pass

        mod_with_fixt.Test = Test
        mod_with_fixt.teardown = teardown
        Test.__module__ = 'mod_with_fixt'

        r = multiprocess.MultiProcessTestRunner()
        l = TestLoader()
        tests = list(r.nextBatch(l.loadTestsFromModule(mod_with_fixt)))
        print(tests)
        self.assertEqual(len(tests), 1)
Esempio n. 24
0
    def find_tests(self, *names):
        """
        Use nosetests to find the tests using the default naming rules.

        :param names: one or more names where a name can be a file, directory, module, or any object within a module
        """
        from nose.loader import Config, TestLoader

        suite = TestLoader(Config(includeExe=True),
                           selector=K2TestSelector()).loadTestsFromNames(names)
        return self._test_cases_from_suite(suite)
Esempio n. 25
0
    def test_next_batch_with_module(self):
        mod_no_fixt = imp.new_module('mod_no_fixt')
        sys.modules['mod_no_fixt'] = mod_no_fixt

        class Test2(T):
            pass

        class Test_fixt(T_fixt):
            pass

        mod_no_fixt.Test = Test2
        Test2.__module__ = 'mod_no_fixt'
        mod_no_fixt.Test_fixt = Test_fixt
        Test_fixt.__module__ = 'mod_no_fixt'

        r = multiprocess.MultiProcessTestRunner()
        l = TestLoader()
        tests = list(r.nextBatch(l.loadTestsFromModule(mod_no_fixt)))
        print tests
        self.assertEqual(len(tests), 3)
Esempio n. 26
0
    def test_next_batch_with_module(self):
        mod_no_fixt = imp.new_module('mod_no_fixt')
        sys.modules['mod_no_fixt'] = mod_no_fixt

        class Test2(T):
            pass

        class Test_fixt(T_fixt):
            pass

        mod_no_fixt.Test = Test2
        Test2.__module__ = 'mod_no_fixt'
        mod_no_fixt.Test_fixt = Test_fixt
        Test_fixt.__module__ = 'mod_no_fixt'

        r = multiprocess.MultiProcessTestRunner()
        l = TestLoader()
        tests = list(r.nextBatch(l.loadTestsFromModule(mod_no_fixt)))
        print(tests)
        self.assertEqual(len(tests), 3)
    def xmltest(self):
        """
        Runs each specified tests by using python unittest to execute
        and reports results through stdout and junit xml format.

        :return:
        """
        p = parameterized(self.clean_names(self.tests_to_run()))
        test_main = p(test_individual)
        suite = TestLoader().loadTestsFromGenerator(test_main, __name__)
        testRunner = xmlrunner.XMLTestRunner(output='test-reports')
        testRunner.run(suite)
Esempio n. 28
0
def test_units():
    import coverage
    import nose
    from nose.loader import TestLoader

    _remove_coverage()
    cov = coverage.coverage(branch=True, source=['chatmotor'])
    cov.start()
    nose.run(suite=TestLoader().loadTestsFromName("tests/unit"))
    cov.stop()
    cov.save()
    local('coverage report -m')
Esempio n. 29
0
    def test_load_in_def_order(self):
        from nose.loader import TestLoader

        where = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                             'support', 'bug105'))

        l = TestLoader()
        testmod = next(l.loadTestsFromDir(where))
        print(testmod)
        testmod.setUp()

        def fix(t):
            s = str(t)
            if ': ' in s:
                return s[s.index(': ')+2:]
            return s
        
        tests = list(map(fix, testmod))
        print(tests)
        self.assertEqual(tests, ['tests.test_z', 'tests.test_a',
                                 'tests.test_dz', 'tests.test_mdz',
                                 'tests.test_b'])
Esempio n. 30
0
 def __init__(self, config = None, importer = None,
              workingDir = None, selector = JUnitSelector):
     """Initialize a test loader
     """
     TestLoader.__init__(self, config, importer, workingDir, selector)
     log.debug("JUnitTestLoader.__init__(): config = %s", config)
     if hasattr(config.options, 'compiled_root'):
         self.compiledTestsRoot = config.options.compiled_root
         if os.name == "nt":
             self.compiledTestsRoot = self.compiledTestsRoot.replace("/", "\\")
     log.debug("Compiled root is %s, os is %s", self.compiledTestsRoot, os.name)
     # Each element of config.options.attr is a comma-separated list of
     # enabled of disabled test tags
     target_expression = ''
     for expression in config.options.eval_attr:
         if target_expression:
             target_expression = target_expression + '&'
         target_expression = target_expression + '(' + expression + ')'
     self.tags = process_expression(target_expression)
     if not self.tags:
         self.tags = 'checkin&!interactive'
         log.debug("JUnitTestLoader.__init__(): Set default test tasgs")
     log.debug("JUnitTestLoader.__init__(): self.tags: %s", self.tags)
Esempio n. 31
0
def run_test():
    try:
        loader = TestLoader()

        run(argv=[
            "--nocapture", "--nologcapture", "--where=/root/tests",
            "--with-coverage", "--cover-erase",
            "--cover-package=/root/src/train", "--cover-xml",
            "--cover-xml-file=/root/tests/results/coverage.xml",
            "--with-xunit", "--xunit-file=/root/tests/results/nosetests.xml"
        ],
            testLoader=loader)
    except (KeyboardInterrupt):
        sys.exit(0)
Esempio n. 32
0
 def __init__(self, config = None, importer = None,
              workingDir = None, selector = Selector):
     """Initialize a test loader
     """
     TestLoader.__init__(self, config, importer, workingDir, selector)
     log.debug("CTestTestLoader.__init__(): config = %s", config)
     if hasattr(config.options, 'compiled_root'):
         self.compiledTestsRoot = config.options.compiled_root
     log.debug("Compiled root is %s", self.compiledTestsRoot)
     # Each element of config.options.attr is a comma-separated list of
     # enabled of disabled test tags
     target_expression = ''
     for expression in config.options.eval_attr:
         if target_expression:
             target_expression = target_expression + '&'
         target_expression = target_expression + '(' + expression + ')'
     self.tags = process_expression(target_expression)
     Selector.tags = self.tags
     log.debug("CTestTestLoader.__init__(): set tags for Selector")
     if not self.tags:
         self.tags = 'shareable&!interactive'
         log.debug("CTestTestLoader.__init__(): Set default test tasgs")
     log.debug("CTestTestLoader.__init__(): self.tags: %s", self.tags)
Esempio n. 33
0
    def loadTestsFromName(self, name, module=None):
        """This is needs when using multithread pluggin to re-create the
        class as generate in loadTestsFromTestCase"""
        driver = None
        prefix = None
        for d in self.drivers:
            if name.startswith(d.name):
                prefix = "%s_" % d.name
                name = name[len(prefix):]
                driver = d
                continue
        if not driver or not module:
            return
        parts = name.split(".")
        class_name = parts[0]
        method_name = None
        if len(parts) >= 2:
            method_name = parts[1]
        test_case_class = getattr(module, class_name)
        assert isinstance(test_case_class, object)

        class A(test_case_class):
            pass

        new_class = A
        new_class.driver = driver
        new_class.__name__ = "%s%s" % (prefix, class_name)
        new_class.__module__ = test_case_class.__module__
        if method_name:
            yield new_class(method_name)
        else:
            loader = TestLoader()
            test_case_names = loader.getTestCaseNames(new_class)
            if not test_case_names and hasattr(new_class, 'runTest'):
                test_case_names = ['runTest']
            yield loader.suiteClass(map(new_class, test_case_names))
Esempio n. 34
0
class Tests(TestCase):

    def setUp(self):
        from nose_fixes.plugin import Plugin
        plugin = Plugin()
        plugin.test_suite_func = 'test_suite'
        self.l = TestLoader()
        plugin.prepareTestLoader(self.l)
        
    def test_suite(self):

        suite = object()
        def test_suite():
            # return a suite
            return suite
        
        mod = new_module('with_test_suite')
        mod.test_suite = test_suite

        self.assertTrue(self.l.loadTestsFromModule(mod) is suite)

    def test_no_suite(self):
        def test_sweet():
            # a tester of sweets ;-)
            assert True!=False
        
        mod = new_module('without_test_suite')
        mod.test_sweet = test_sweet

        suite = self.l.loadTestsFromModule(mod)

        tests = [t for t in suite]
        self.assertEqual(len(tests), 1)
        test = tests[0]
        self.assertTrue(isinstance(test, Test))
        self.assertEqual(repr(test), 'Test(without_test_suite.test_sweet)')
Esempio n. 35
0
    def test_load_nested_generator(self):
        from nose.config import Config
        from nose.loader import TestLoader

        where = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                             'support', 'issue006'))
        l = TestLoader()
        testmod = iter(l.loadTestsFromName(where)).next()
        print testmod
        testmod.setUp()

        testcase = iter(testmod).next()
        expect = [
            ['tests.Test1.test_nested_generator'],
            ['tests.Test1.test_nested_generator_mult(1,)',
             'tests.Test1.test_nested_generator_mult(2,)',
             'tests.Test1.test_nested_generator_mult(3,)'],
            ['tests.Test1.test_normal_generator(1,)',
             'tests.Test1.test_normal_generator(2,)']
            ]
        for test in testcase:
            tests = map(str, test)
            print tests
            self.assertEqual(tests, expect.pop(0))
Esempio n. 36
0
    def load_tests(self, dotted_name_of_tests):
        """Returns a TestSuite of all tests in the named scope.

        The dotted name may specify a package, module, class, or method.
        All tests within the named scope will be recursively collected into
        a single TestSuite, which is returned.
        """
        module, clazz, method = find_python_objects(dotted_name_of_tests)
        error_msg_prefix = ("Parameter '" + self.pname_run + "=" +
                            dotted_name_of_tests + "': ")
        self._verify_python_objects(
            module, clazz, method, unittest.defaultTestLoader.testMethodPrefix,
            error_msg_prefix)
        '''LOG.info(inspect.stack()[0][3] + ": module= " + module.__name__
                 + ", class= "
                 + ("None" if clazz is None else clazz.__name__)
                 + ", method= "
                 + ("None" if method is None else method.__name__))'''
        testsuite = None
        if clazz is None:
            # Use nose TestLoader b/c unittest.loadTestsFromModule didn't work
            testsuite = TestLoader().loadTestsFromModule(module)
            #testsuite = unittest.defaultTestLoader.loadTestsFromModule(module)
            if testsuite.countTestCases() < 1:
                raise ValueError(error_msg_prefix + "No tests in module")
        else:
            if method is None:
                testsuite = unittest.defaultTestLoader.loadTestsFromTestCase(
                    clazz)
                '''LOG.info("Loaded from class '" + clazz.__name__ + "'= "
                         + str(testsuite.countTestCases()))
                if testsuite.countTestCases() < 1:
                    raise ValueError(error_msg_prefix + "No tests in class")'''
            else:
                testsuite = unittest.TestSuite(tests=[clazz(method.__name__)])
        return testsuite
Esempio n. 37
0
    def loadTestsFromName(self, name, module=None):
        """This is needs when using multithread pluggin to re-create the
        class as generate in loadTestsFromTestCase"""
        driver = None
        prefix = None
        for d in self.drivers:
            if name.startswith(d.name):
                prefix = "%s_" % d.name
                name = name[len(prefix):]
                driver = d
                continue
        if not driver or not module:
            return
        parts = name.split(".")
        class_name = parts[0]
        method_name = None
        if len(parts) >= 2:
            method_name = parts[1]
        test_case_class = getattr(module, class_name)
        assert isinstance(test_case_class, object)

        class A(test_case_class):
            pass

        new_class = A
        new_class.driver = driver
        new_class.__name__ = "%s%s" % (prefix, class_name)
        new_class.__module__ = test_case_class.__module__
        if method_name:
            yield new_class(method_name)
        else:
            loader = TestLoader()
            test_case_names = loader.getTestCaseNames(new_class)
            if not test_case_names and hasattr(new_class, 'runTest'):
                test_case_names = ['runTest']
            yield loader.suiteClass(map(new_class, test_case_names))
Esempio n. 38
0
    def run(self, test_name, test_module):
        target = "%s:%s" % (test_module, test_name)
        test_suite = TestLoader().loadTestsFromName(target)
        report = StringIO()
        runner = TextTestRunner(report)
        result = runner.run(test_suite)

        ret = {"pass": result.wasSuccessful()}

        for failure in result.failures:
            ret.update({"stack": failure[1]})
            ret.update({"log": report.getvalue()})

        for error in result.errors:
            ret.update({"error": error[1]})

        return ret
Esempio n. 39
0
 def loadTestsFromFile(self, filename):
     """
     We'll exploit the knowledge of the selector implementation details:
     since the selector 'wants' only root build.xml file for JUnit-based
     tests, we can safely check initials and then fall back to inherited
     behavior or collect output for all tests.
     """
     log.debug("JUnitTestLoader.loadTestsFromFile(%s)", filename)
     if not filename.startswith(self.compiledTestsRoot):
         log.debug(
             "JUnitTestLoader.loadTestsFromFile(): fall back to predefined behavior"
         )
         log.debug(
             "JUnitTestLoader.loadTestsFromFile(): compiledTestsRoot is %s",
             self.compiledTestsRoot)
         return TestLoader.loadTestsFromFile(self, filename)
     commandLine = self.prepareCommandLine()
     try:
         testOutput = self.executeTests(commandLine)
     except Exception as e:
         log.debug("Building JUnit test suite failed with message: %s",
                   str(e))
         return self.suiteClass(
             Failure(Exception, "Couldn't build compiled test suite."))
     log.debug("JUnitTestLoader.loadTestsFromFile(): got ant output:\n%s",
               testOutput)
     singleTestOutput, singleTestExceptions = self.filterTestOutput(
         testOutput)
     log.debug(
         "JUnitTestLoader.loadTestsFromFile(): JUnit filtered output:")
     for line in singleTestOutput:
         log.debug("%s\n", line)
     log.debug("JUnitTestLoader.loadTestsFromFile(): %s",
               "JUnit filtered output finished.")
     loadedTests = self.makeTestCases(singleTestOutput,
                                      singleTestExceptions)
     log.debug("JUnitTestLoader.loadTestsFromFile(): loaded tests %s",
               loadedTests)
     log.debug("JUnitTestLoader.loadTestsFromFile(): suite class is %s",
               repr(self.suiteClass))
     return self.suiteClass(loadedTests)
Esempio n. 40
0
 def loadTestsFromFile(self, filename):
     log.debug("CTestTestLoader.loadTestsFromFile(%s)", filename)
     doesStartWith = False
     try:
         doesStartWith = pathStartsWith(filename, self.compiledTestsRoot)
     except:
         doesStartWith = False
     if not doesStartWith:
         log.debug("CTestTestLoader.loadTestsFromFile(): fall back to predefined behavior")
         return TestLoader.loadTestsFromFile(self, filename)
     tests = list()
     tagset = set(self.tags.split(','))
     testRunnerInfo = getItemByFileName(filename)
     log.debug("testRunnerInfo now is: %s", repr(testRunnerInfo))
     if testRunnerInfo:
         tests = testRunnerInfo.tests
     log.debug("CTestTestLoader.loadTestsFromFile(): have tests: '%s'" % tests)
     loadedTests = self.makeTestCases(filename, tests, testRunnerInfo.env)
     log.debug("CTestTestLoader.loadTestsFromFile(%s): loaded tests %s",
               filename, loadedTests)
     log.debug("CTestTestLoader.loadTestsFromFile(): suite class is %s",
                repr(self.suiteClass))
     return self.suiteClass(loadedTests)
Esempio n. 41
0
 def __init__(self, *args, **kwargs):
     super(WTRLoader, self).__init__(*args, **kwargs)
     self.logger = logging.getLogger(__file__)
     self.test_loader = TestLoader()
Esempio n. 42
0
def create_test_suite():
    this_dir = os.path.dirname(os.path.abspath(__file__))

    return LazySuite(TestLoader().loadTestsFromDir(this_dir))
class TestMultiProcessTestRunner(unittest.TestCase):

    def setUp(self):
        self.runner = gmultiprocess.GeventedMultiProcessTestRunner(
            #stream=_WritelnDecorator(sys.stdout),
            verbosity=10,
            loaderClass=TestLoader,
            config=Config()
        )
        self.loader = TestLoader()

    def test_next_batch_with_classes(self):
        tests = list(self.runner.get_test_batch(
            ContextSuite(
                tests=[
                    self.loader.makeTest(T_fixt),
                    self.loader.makeTest(T)
                ]
            )
        ))
        print tests
        self.assertEqual(len(tests), 3)

    def test_next_batch_with_module_fixt(self):
        mod_with_fixt = imp.new_module('mod_with_fixt')
        sys.modules['mod_with_fixt'] = mod_with_fixt

        def teardown():
            pass

        class Test(T):
            pass

        mod_with_fixt.Test = Test
        mod_with_fixt.teardown = teardown
        Test.__module__ = 'mod_with_fixt'

        tests = list(self.runner.get_test_batch(
            self.loader.loadTestsFromModule(mod_with_fixt)
        ))
        print tests
        self.assertEqual(len(tests), 1)

    def test_next_batch_with_module(self):
        mod_no_fixt = imp.new_module('mod_no_fixt')
        sys.modules['mod_no_fixt'] = mod_no_fixt

        class Test2(T):
            pass

        class Test_fixt(T_fixt):
            pass

        mod_no_fixt.Test = Test2
        Test2.__module__ = 'mod_no_fixt'
        mod_no_fixt.Test_fixt = Test_fixt
        Test_fixt.__module__ = 'mod_no_fixt'

        tests = list(self.runner.get_test_batch(
            self.loader.loadTestsFromModule(mod_no_fixt)
        ))
        print tests
        self.assertEqual(len(tests), 3)

    def test_next_batch_with_generator_method(self):
        class Tg:
            def test_gen(self):
                for i in range(0, 3):
                    yield self.check, i
            def check(self, val):
                pass
        tests = list(self.runner.get_test_batch(self.loader.makeTest(Tg)))
        print tests
        print [gmultiprocess.get_test_case_address(t) for t in tests]
Esempio n. 44
0
 def setUp(self):
     from nose_fixes.plugin import Plugin
     plugin = Plugin()
     plugin.test_suite_func = 'test_suite'
     self.l = TestLoader()
     plugin.prepareTestLoader(self.l)
Esempio n. 45
0
 def run_tests(self, test_class):
     res = TestResult()
     loader = TestLoader()
     suite = loader.loadTestsFromTestClass(test_class)
     suite(res)
     return res
Esempio n. 46
0
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from nose.loader import TestLoader
from nose import run
from nose.suite import LazySuite

TESTS = {'generic': ['test_database'], 'versioned': ['test_v2_0']}

all_tests = TestLoader().loadTestsFromNames(TESTS["generic"] +
                                            TESTS["versioned"])
latest_tests = TestLoader().loadTestsFromNames(TESTS["generic"] +
                                               [TESTS["versioned"][-1]])


def runner(tests):
    def _run():
        suite = LazySuite(tests)
        run(suite=suite)

    return _run


run_all = runner(all_tests)
run_latest = runner(latest_tests)
Esempio n. 47
0
def run_exit():
    testLoader = TestLoader(importer=OdooImporter())
    return main(testLoader=testLoader)
class TestMultiProcessTestRunner(unittest.TestCase):
    def setUp(self):
        self.runner = gmultiprocess.GeventedMultiProcessTestRunner(
            #stream=_WritelnDecorator(sys.stdout),
            verbosity=10,
            loaderClass=TestLoader,
            config=Config())
        self.loader = TestLoader()

    def test_next_batch_with_classes(self):
        tests = list(
            self.runner.get_test_batch(
                ContextSuite(tests=[
                    self.loader.makeTest(T_fixt),
                    self.loader.makeTest(T)
                ])))
        print tests
        self.assertEqual(len(tests), 3)

    def test_next_batch_with_module_fixt(self):
        mod_with_fixt = imp.new_module('mod_with_fixt')
        sys.modules['mod_with_fixt'] = mod_with_fixt

        def teardown():
            pass

        class Test(T):
            pass

        mod_with_fixt.Test = Test
        mod_with_fixt.teardown = teardown
        Test.__module__ = 'mod_with_fixt'

        tests = list(
            self.runner.get_test_batch(
                self.loader.loadTestsFromModule(mod_with_fixt)))
        print tests
        self.assertEqual(len(tests), 1)

    def test_next_batch_with_module(self):
        mod_no_fixt = imp.new_module('mod_no_fixt')
        sys.modules['mod_no_fixt'] = mod_no_fixt

        class Test2(T):
            pass

        class Test_fixt(T_fixt):
            pass

        mod_no_fixt.Test = Test2
        Test2.__module__ = 'mod_no_fixt'
        mod_no_fixt.Test_fixt = Test_fixt
        Test_fixt.__module__ = 'mod_no_fixt'

        tests = list(
            self.runner.get_test_batch(
                self.loader.loadTestsFromModule(mod_no_fixt)))
        print tests
        self.assertEqual(len(tests), 3)

    def test_next_batch_with_generator_method(self):
        class Tg:
            def test_gen(self):
                for i in range(0, 3):
                    yield self.check, i

            def check(self, val):
                pass

        tests = list(self.runner.get_test_batch(self.loader.makeTest(Tg)))
        print tests
        print[gmultiprocess.get_test_case_address(t) for t in tests]
        self.assertEqual(len(tests), 1)

    def test_next_batch_can_split_set(self):

        mod_with_fixt2 = imp.new_module('mod_with_fixt2')
        sys.modules['mod_with_fixt2'] = mod_with_fixt2

        def setup():
            pass

        class Test(T):
            pass

        class Test_fixt(T_fixt):
            pass

        mod_with_fixt2.Test = Test
        mod_with_fixt2.Test_fixt = Test_fixt
        mod_with_fixt2.setup = setup
        mod_with_fixt2._multiprocess_can_split_ = True
        Test.__module__ = 'mod_with_fixt2'
        Test_fixt.__module__ = 'mod_with_fixt2'

        tests = list(
            self.runner.get_test_batch(
                self.loader.loadTestsFromModule(mod_with_fixt2)))
        print tests
        self.assertEqual(len(tests), 3)

    def test_runner_collect_tests(self):

        test = ContextSuite(tests=[
            self.loader.makeTest(T_fixt),
            self.loader.makeTest(T),
            case.Test(TC('runTest'))
        ])

        kw = dict(tasks_queue=[], tasks_list=[], to_teardown=[], result=None)

        self.runner.collect_tasks(test, **kw)

        # Tasks Queue

        should_be_tasks = ['T_fixt', 'T.test_a', 'T.test_b', 'TC.runTest']
        tasks = [addr.split(':')[-1] for addr, args in kw['tasks_queue']]
        self.assertEqual(tasks, should_be_tasks)

        # Tasks List

        should_be_tasks = [
            'T_fixt',
            'T.test_a()',  # args is a tuple. appended as string to base addr
            'T.test_b()',  # args is a tuple. appended as string to base addr
            'TC.runTest'
        ]
        tasks = [addr.split(':')[-1] for addr in kw['tasks_list']]
        self.assertEqual(tasks, should_be_tasks)