Python unittest.py() Examples

The following are 18 code examples of unittest.py(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module unittest , or try the search function .
Example #1
Source File: testlib.py    From clonedigger with GNU General Public License v3.0 6 votes vote down vote up
def find_tests(testdir,
               prefixes=DEFAULT_PREFIXES, suffix=".py",
               excludes=(),
               remove_suffix=True):
    """
    Return a list of all applicable test modules.
    """
    tests = []
    for name in os.listdir(testdir):
        if not suffix or name.endswith(suffix):
            for prefix in prefixes:
                if name.startswith(prefix):
                    if remove_suffix and name.endswith(suffix):
                        name = name[:-len(suffix)]
                    if name not in excludes:
                        tests.append(name)
    tests.sort()
    return tests 
Example #2
Source File: testlib.py    From clonedigger with GNU General Public License v3.0 5 votes vote down vote up
def set_description(self, descr):
        """sets the current test's description.
        This can be useful for generative tests because it allows to specify
        a description per yield
        """
        self._current_test_descr = descr

    # override default's unittest.py feature 
Example #3
Source File: test_runfiles.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def test_finding_tests_when_no_filter(self):
        # unittest.py will create a TestCase with 0 tests in it
        # since it just imports what is given
        self.assertEquals(1, len(self.all_tests) > 0)
        files_with_tests = [1 for t in self.all_tests if len(t._tests) > 0]
        self.assertNotEquals(len(self.files), len(files_with_tests)) 
Example #4
Source File: test_runfiles.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def test_finding_a_file_from_file_system(self):
        test_file = "simple_test.py"
        self.MyTestRunner.files_or_dirs = [self.file_dir[0] + test_file]
        files = self.MyTestRunner.find_import_files()
        self.assertEquals(1, len(files))
        self.assertEquals(files[0], self.file_dir[0] + test_file) 
Example #5
Source File: test_runfiles.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def test___importify(self):
        importify = self.MyTestRunner._PydevTestRunner__importify
        self.assertEquals("temp.junk.asdf", importify("temp/junk/asdf.py"))
        self.assertEquals("asdf", importify("asdf.py"))
        self.assertEquals("abc.def.hgi", importify("abc/def/hgi")) 
Example #6
Source File: test_runfiles.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def test___unixify(self):
        unixify = self.MyTestRunner._PydevTestRunner__unixify
        self.assertEquals("c:/temp/junk/asdf.py", unixify("c:SEPtempSEPjunkSEPasdf.py".replace('SEP', os.sep))) 
Example #7
Source File: test_runfiles.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def test___is_valid_py_file(self):
        isvalid = self.MyTestRunner._PydevTestRunner__is_valid_py_file
        self.assertEquals(1, isvalid("test.py"))
        self.assertEquals(0, isvalid("asdf.pyc"))
        self.assertEquals(0, isvalid("__init__.py"))
        self.assertEquals(0, isvalid("__init__.pyc"))
        self.assertEquals(1, isvalid("asdf asdf.pyw")) 
Example #8
Source File: testlib.py    From clonedigger with GNU General Public License v3.0 5 votes vote down vote up
def create_files(paths, chroot):
    """creates directories and files found in <path>

    :param path: list of relative paths to files or directories
    :param chroot: the root directory in which paths will be created

    >>> from os.path import isdir, isfile
    >>> isdir('/tmp/a')
    False
    >>> create_files(['a/b/foo.py', 'a/b/c/', 'a/b/c/d/e.py'], '/tmp')
    >>> isdir('/tmp/a')
    True
    >>> isdir('/tmp/a/b/c')
    True
    >>> isfile('/tmp/a/b/c/d/e.py')
    True 
    >>> isfile('/tmp/a/b/foo.py')
    True
    """
    dirs, files = set(), set()
    for path in paths:
        path = osp.join(chroot, path)
        filename = osp.basename(path)
        # path is a directory path
        if filename == '':
            dirs.add(path)
        # path is a filename path
        else:
            dirs.add(osp.dirname(path))
            files.add(path)
    for dirpath in dirs:
        if not osp.isdir(dirpath):
            os.makedirs(dirpath)
    for filepath in files:
        file(filepath, 'w').close() 
Example #9
Source File: testlib.py    From clonedigger with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, result=None, runcondition=None, options=None):
        """rewrite TestCase.__call__ to support generative tests
        This is mostly a copy/paste from unittest.py (i.e same
        variable names, same logic, except for the generative tests part)
        """
        if result is None:
            result = self.defaultTestResult()
        result.pdbclass = self.pdbclass
        # if self.capture is True here, it means it was explicitly specified
        # in the user's TestCase class. If not, do what was asked on cmd line
        self.capture = self.capture or getattr(result, 'capture', False)
        self._options_ = options
        self._printonly = getattr(result, 'printonly', None)
        # if result.cvg:
        #     result.cvg.start()
        testMethod = self._get_test_method()
        if runcondition and not runcondition(testMethod):
            return # test is skipped
        result.startTest(self)
        try:
            if not self.quiet_run(result, self.setUp):
                return
            # generative tests
            if is_generator(testMethod.__func__):
                success = self._proceed_generative(result, testMethod, runcondition)
            else:
                status = self._proceed(result, testMethod)
                success = (status == 0)
            if not self.quiet_run(result, self.tearDown):
                return
            if success:
                result.addSuccess(self)
        finally:
            # if result.cvg:
            #     result.cvg.stop()
            result.stopTest(self) 
Example #10
Source File: testlib.py    From clonedigger with GNU General Public License v3.0 5 votes vote down vote up
def loadTestsFromName(self, name, module=None):
        parts = name.split('.')
        if module is None or len(parts) > 2:
            # let the base class do its job here
            return [super(NonStrictTestLoader, self).loadTestsFromName(name)]
        tests = self._collect_tests(module)
        # import pprint
        # pprint.pprint(tests)
        collected = []
        if len(parts) == 1:
            pattern = parts[0]
            if callable(getattr(module, pattern, None)) and pattern not in tests:
                # consider it as a suite
                return self.loadTestsFromSuite(module, pattern)
            if pattern in tests:
                # case python unittest_foo.py MyTestTC
                klass, methodnames = tests[pattern]
                for methodname in methodnames:
                    collected = [klass(methodname) for methodname in methodnames]
            else:
                # case python unittest_foo.py something
                for klass, methodnames in list(tests.values()):
                    collected += [klass(methodname) for methodname in methodnames]
        elif len(parts) == 2:
            # case "MyClass.test_1"
            classname, pattern = parts
            klass, methodnames = tests.get(classname, (None, []))
            for methodname in methodnames:
                collected = [klass(methodname) for methodname in methodnames]
        return collected 
Example #11
Source File: test_runfiles.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def test_finding_tests_when_no_filter(self):
        # unittest.py will create a TestCase with 0 tests in it
        # since it just imports what is given
        self.assertEqual(1, len(self.all_tests) > 0)
        files_with_tests = [1 for t in self.all_tests if len(t._tests) > 0]
        self.assertNotEqual(len(self.files), len(files_with_tests)) 
Example #12
Source File: test_runfiles.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def test_finding_a_file_from_file_system(self):
        test_file = "simple_test.py"
        self.MyTestRunner.files_or_dirs = [self.file_dir[0] + test_file]
        files = self.MyTestRunner.find_import_files()
        self.assertEqual(1, len(files))
        self.assertEqual(files[0], self.file_dir[0] + test_file) 
Example #13
Source File: test_runfiles.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def test___importify(self):
        importify = self.MyTestRunner._PydevTestRunner__importify
        self.assertEqual("temp.junk.asdf", importify("temp/junk/asdf.py"))
        self.assertEqual("asdf", importify("asdf.py"))
        self.assertEqual("abc.def.hgi", importify("abc/def/hgi")) 
Example #14
Source File: test_runfiles.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def test___unixify(self):
        unixify = self.MyTestRunner._PydevTestRunner__unixify
        self.assertEqual("c:/temp/junk/asdf.py", unixify("c:SEPtempSEPjunkSEPasdf.py".replace('SEP', os.sep))) 
Example #15
Source File: test_runfiles.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def test___is_valid_py_file(self):
        isvalid = self.MyTestRunner._PydevTestRunner__is_valid_py_file
        self.assertEqual(1, isvalid("test.py"))
        self.assertEqual(0, isvalid("asdf.pyc"))
        self.assertEqual(0, isvalid("__init__.py"))
        self.assertEqual(0, isvalid("__init__.pyc"))
        self.assertEqual(1, isvalid("asdf asdf.pyw")) 
Example #16
Source File: test_runfiles.py    From PyDev.Debugger with Eclipse Public License 1.0 4 votes vote down vote up
def test_parse_cmdline(self):
        sys.argv = "pydev_runfiles.py ./".split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEqual([sys.argv[1]], configuration.files_or_dirs)
        self.assertEqual(2, configuration.verbosity)  # default value
        self.assertEqual(None, configuration.include_tests)  # default value

        sys.argv = "pydev_runfiles.py ../images c:/temp".split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEqual(sys.argv[1:3], configuration.files_or_dirs)
        self.assertEqual(2, configuration.verbosity)

        sys.argv = "pydev_runfiles.py --verbosity 3 ../junk c:/asdf ".split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEqual(sys.argv[3:], configuration.files_or_dirs)
        self.assertEqual(int(sys.argv[2]), configuration.verbosity)

        sys.argv = "pydev_runfiles.py --include_tests test_def ./".split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEqual([sys.argv[-1]], configuration.files_or_dirs)
        self.assertEqual([sys.argv[2]], configuration.include_tests)

        sys.argv = "pydev_runfiles.py --include_tests Abc.test_def,Mod.test_abc c:/junk/".split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEqual([sys.argv[-1]], configuration.files_or_dirs)
        self.assertEqual(sys.argv[2].split(','), configuration.include_tests)

        sys.argv = ('C:\\eclipse-SDK-3.2-win32\\eclipse\\plugins\\org.python.pydev.debug_1.2.2\\pysrc\\pydev_runfiles.py ' +
                    '--verbosity 1 ' +
                    'C:\\workspace_eclipse\\fronttpa\\tests\\gui_tests\\calendar_popup_control_test.py ').split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEqual([sys.argv[-1]], configuration.files_or_dirs)
        self.assertEqual(1, configuration.verbosity)

        sys.argv = "pydev_runfiles.py --verbosity 1 --include_tests Mod.test_abc c:/junk/ ./".split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEqual(sys.argv[5:], configuration.files_or_dirs)
        self.assertEqual(int(sys.argv[2]), configuration.verbosity)
        self.assertEqual([sys.argv[4]], configuration.include_tests)

        sys.argv = "pydev_runfiles.py --exclude_files=*.txt,a*.py".split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEqual(['*.txt', 'a*.py'], configuration.exclude_files)

        sys.argv = "pydev_runfiles.py --exclude_tests=*__todo,test*bar".split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEqual(['*__todo', 'test*bar'], configuration.exclude_tests) 
Example #17
Source File: test_componentBlueprint.py    From armi with Apache License 2.0 4 votes vote down vote up
def test_autoDepletable(self):
        nuclideFlags = (
            inspect.cleandoc(
                r"""
            nuclide flags:
                U234: {burn: true, xs: true}
                U235: {burn: true, xs: true}
                U238: {burn: true, xs: true}
                B10: {burn: true, xs: true}
                B11: {burn: true, xs: true}
                C: {burn: true, xs: true}
                DUMP1: {burn: true, xs: true}
            custom isotopics:
                B4C:
                    input format: number densities
                    B10: 1.0
                    B11: 1.0
                    C: 1.0
            """
            )
            + "\n"
        )
        bp = blueprints.Blueprints.load(
            nuclideFlags
            + self.componentString.format(
                material="Custom", isotopics="isotopics: B4C", flags=""
            )
        )
        cs = settings.Settings()
        a = bp.constructAssem("hex", cs, "assembly")
        expectedNuclides = ["B10", "B11", "C", "DUMP1"]
        unexpectedNuclides = ["U234", "U325", "U238"]
        for nuc in expectedNuclides:
            self.assertIn(nuc, a[0][0].getNuclides())
        for nuc in unexpectedNuclides:
            self.assertNotIn(nuc, a[0][0].getNuclides())

        c = a[0][0]

        # Since we didn't supply flags, we should get the DEPLETABLE flag added
        # automatically, since this one has depletable nuclides
        self.assertEqual(c.p.flags, Flags.DEPLETABLE)
        # More robust test, but worse unittest.py output when it fails
        self.assertTrue(c.hasFlags(Flags.DEPLETABLE))

        # repeat the process with some flags set explicitly
        bp = blueprints.Blueprints.load(
            nuclideFlags
            + self.componentString.format(
                material="Custom", isotopics="isotopics: B4C", flags="fuel test"
            )
        )
        cs = settings.Settings()
        a = bp.constructAssem("hex", cs, "assembly")
        c = a[0][0]

        # Since we supplied flags, we should NOT get the DEPLETABLE flag added
        self.assertEqual(c.p.flags, Flags.FUEL | Flags.TEST)
        # More robust test, but worse unittest.py output when it fails
        self.assertTrue(c.hasFlags(Flags.FUEL | Flags.TEST)) 
Example #18
Source File: test_runfiles.py    From filmkodi with Apache License 2.0 4 votes vote down vote up
def test_parse_cmdline(self):
        sys.argv = "pydev_runfiles.py ./".split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEquals([sys.argv[1]], configuration.files_or_dirs)
        self.assertEquals(2, configuration.verbosity)  # default value
        self.assertEquals(None, configuration.include_tests)  # default value

        sys.argv = "pydev_runfiles.py ../images c:/temp".split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEquals(sys.argv[1:3], configuration.files_or_dirs)
        self.assertEquals(2, configuration.verbosity)

        sys.argv = "pydev_runfiles.py --verbosity 3 ../junk c:/asdf ".split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEquals(sys.argv[3:], configuration.files_or_dirs)
        self.assertEquals(int(sys.argv[2]), configuration.verbosity)

        sys.argv = "pydev_runfiles.py --include_tests test_def ./".split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEquals([sys.argv[-1]], configuration.files_or_dirs)
        self.assertEquals([sys.argv[2]], configuration.include_tests)

        sys.argv = "pydev_runfiles.py --include_tests Abc.test_def,Mod.test_abc c:/junk/".split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEquals([sys.argv[-1]], configuration.files_or_dirs)
        self.assertEquals(sys.argv[2].split(','), configuration.include_tests)

        sys.argv = ('C:\\eclipse-SDK-3.2-win32\\eclipse\\plugins\\org.python.pydev.debug_1.2.2\\pysrc\\pydev_runfiles.py ' +
                    '--verbosity 1 ' +
                    'C:\\workspace_eclipse\\fronttpa\\tests\\gui_tests\\calendar_popup_control_test.py ').split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEquals([sys.argv[-1]], configuration.files_or_dirs)
        self.assertEquals(1, configuration.verbosity)

        sys.argv = "pydev_runfiles.py --verbosity 1 --include_tests Mod.test_abc c:/junk/ ./".split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEquals(sys.argv[5:], configuration.files_or_dirs)
        self.assertEquals(int(sys.argv[2]), configuration.verbosity)
        self.assertEquals([sys.argv[4]], configuration.include_tests)

        sys.argv = "pydev_runfiles.py --exclude_files=*.txt,a*.py".split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEquals(['*.txt', 'a*.py'], configuration.exclude_files)

        sys.argv = "pydev_runfiles.py --exclude_tests=*__todo,test*bar".split()
        configuration = pydev_runfiles.parse_cmdline()
        self.assertEquals(['*__todo', 'test*bar'], configuration.exclude_tests)