def setUp(self):
     self.runner = gmultiprocess.GeventedMultiProcessTestRunner(
         #stream=_WritelnDecorator(sys.stdout),
         verbosity=10,
         loaderClass=TestLoader,
         config=Config())
     self.loader = TestLoader()
Пример #2
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'
        ])
Пример #3
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))
Пример #4
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"])
Пример #5
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)
Пример #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)
Пример #7
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)
Пример #8
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'
        ])
Пример #9
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)
Пример #10
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')
    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)
Пример #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 = iter(suite).next()
        self.assertEqual(testcase.test.test, test)
Пример #13
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)
Пример #14
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
Пример #15
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)
Пример #16
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)
Пример #17
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))
Пример #18
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
Пример #19
0
    def run():
        import argparse

        parser = argparse.ArgumentParser(description='Run TestBenches.')
        parser.add_argument('--max_configs', type=int)
        parser.add_argument('--run_desert', action='store_true')
        parser.add_argument('model_file')
        parser.add_argument('nose_options', nargs=argparse.REMAINDER)
        command_line_args = parser.parse_args()

        project = Dispatch("Mga.MgaProject")
        mga_file = command_line_args.model_file
        if mga_file.endswith('.xme'):
            project = Dispatch("Mga.MgaProject")
            parser = Dispatch("Mga.MgaParser")
            resolver = Dispatch("Mga.MgaResolver")
            resolver.IsInteractive = False
            parser.Resolver = resolver
            mga_file = os.path.splitext(
                command_line_args.model_file)[0] + ".mga"
            project.Create("MGA=" + os.path.abspath(mga_file), "CyPhyML")
            parser.ParseProject(project, command_line_args.model_file)
        else:
            # n.b. without abspath, things break (e.g. CyPhy2CAD)
            project.OpenEx(
                "MGA=" + os.path.abspath(command_line_args.model_file),
                "CyPhyML", None)

        project.BeginTransactionInNewTerr()
        try:
            if command_line_args.run_desert:
                desert = Dispatch("MGA.Interpreter.DesignSpaceHelper")
                desert.Initialize(project)
                filter = project.CreateFilter()
                filter.Kind = "DesignContainer"
                # FIXME wont work right for TBs that point to non-root design sace
                designContainers = [
                    tb for tb in project.AllFCOs(filter)
                    if not tb.IsLibObject and tb.ParentFolder is not None
                ]
                for designContainer in designContainers:
                    desert.InvokeEx(project, designContainer,
                                    Dispatch("MGA.MgaFCOs"), 128)

            def add_fail(masterContext, configName, message):
                def fail(self):
                    raise ValueError(message)

                fail.__name__ = str('test_' + masterContext.Name + "__" +
                                    configName)
                setattr(TestBenchTest, fail.__name__, fail)

            def add_test(masterContext, mi_config, config):
                def testTestBench(self):
                    self._testTestBench(masterContext, master, mi_config)

                # testTestBench.__name__ = str('test_' + masterContext.Name + "_" + masterContext.ID + "__" + config.Name)
                testTestBench.__name__ = str('test_' + masterContext.Name +
                                             "__" + config.Name)
                setattr(TestBenchTest, testTestBench.__name__, testTestBench)

            master = Dispatch(
                "CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI")
            master.Initialize(project)

            modelKinds = set(
                ("TestBench", "CADTestBench", "KinematicTestBench",
                 "BlastTestBench", "BallisticTestBench", "CarTestBench",
                 "CFDTestBench", "ParametricExploration"))
            # masterContexts = [tb for tb in itertools.chain(*(project.AllFCOs(filter) for filter in filters)) if not tb.IsLibObject]
            masterContexts = list(
                crawlForKinds(project.RootFolder,
                              ("ParametricExplorationFolder", "Testing"),
                              modelKinds))
            print repr([t.Name for t in masterContexts])
            for masterContext in masterContexts:
                configs = None
                if masterContext.Meta.Name == "ParametricExploration":
                    tbs = [
                        tb for tb in masterContext.ChildFCOs
                        if tb.MetaBase.Name == 'TestBenchRef'
                        and tb.Referred is not None
                    ]
                    if not tbs:
                        configs = [masterContext]
                    else:
                        testBench = tbs[0].Referred
                else:
                    testBench = masterContext

                if not configs:
                    suts = [
                        sut for sut in testBench.ChildFCOs
                        if sut.MetaRole.Name == 'TopLevelSystemUnderTest'
                    ]
                    if len(suts) == 0:
                        add_fail(
                            masterContext, 'invalid',
                            'Error: TestBench "{}" has no TopLevelSystemUnderTest'
                            .format(testBench.Name))
                        continue
                    if len(suts) > 1:
                        add_fail(
                            masterContext, 'invalid',
                            'Error: TestBench "{}" has more than one TopLevelSystemUnderTest'
                            .format(testBench.Name))
                        continue
                    sut = suts[0]
                    if sut.Referred.MetaBase.Name == 'ComponentAssembly':
                        configs = [sut.Referred]
                    else:
                        configurations = [
                            config for config in sut.Referred.ChildFCOs
                            if config.MetaBase.Name == 'Configurations'
                        ]
                        if not configurations:
                            add_fail(
                                masterContext, 'invalid',
                                'Error: design has no Configurations models. Try using the --run_desert option'
                            )
                            continue
                        configurations = configurations[0]
                        cwcs = [
                            cwc for cwc in configurations.ChildFCOs
                            if cwc.MetaBase.Name == 'CWC' and cwc.Name
                        ]
                        if not cwcs:
                            raise ValueError(
                                'Error: could not find CWCs for "{}"'.format(
                                    testBench.Name))
                        configs = list(cwcs)
                        # FIXME cfg2 > cfg10
                        configs.sort(key=operator.attrgetter('Name'))
                        configs = configs[slice(0,
                                                command_line_args.max_configs)]

                for config in configs:
                    mi_config = Dispatch(
                        "CyPhyMasterInterpreter.ConfigurationSelectionLight")

                    # GME id, or guid, or abs path or path to Test bench or SoT or PET
                    mi_config.ContextId = masterContext.ID

                    mi_config.SetSelectedConfigurationIds([config.ID])

                    # mi_config.KeepTemporaryModels = True
                    mi_config.PostToJobManager = False

                    add_test(masterContext, mi_config, config)
        finally:
            project.CommitTransaction()

        config = Config(files=all_config_files(),
                        plugins=BuiltinPluginManager())
        config.configure(argv=['nose'] + command_line_args.nose_options)
        loader = TestLoader(config=config)

        tests = [loader.loadTestsFromTestClass(TestBenchTest)]

        try:
            nose.core.TestProgram(suite=tests,
                                  argv=['nose'] +
                                  command_line_args.nose_options,
                                  exit=True,
                                  testLoader=loader,
                                  config=config)
        finally:
            # project.Save(project.ProjectConnStr + "_debug.mga", True)
            project.Close(True)
Пример #20
0
 def run_tests(self, test_class):
     res = TestResult()
     loader = TestLoader()
     suite = loader.loadTestsFromTestClass(test_class)
     suite(res)
     return res
Пример #21
0
def run_exit():
    testLoader = TestLoader(importer=OdooImporter())
    return main(testLoader=testLoader)
Пример #22
0
 def __init__(self, *args, **kwargs):
     super(WTRLoader, self).__init__(*args, **kwargs)
     self.logger = logging.getLogger(__file__)
     self.test_loader = TestLoader()
Пример #23
0
def create_test_suite():
    this_dir = os.path.dirname(os.path.abspath(__file__))

    return LazySuite(TestLoader().loadTestsFromDir(this_dir))
Пример #24
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)
Пример #25
0
from simple_tests import SimpleTests
from nose.loader import TestLoader
from teamcity.unittestpy import TeamcityTestRunner

if __name__ == '__main__':
    test_loader = TestLoader().loadTestsFromTestClass(SimpleTests)
    TeamcityTestRunner().run(test_loader)