我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用unittest.skipUnless()。
def test_skipping_decorators(self): op_table = ((unittest.skipUnless, False, True), (unittest.skipIf, True, False)) for deco, do_skip, dont_skip in op_table: class Foo(unittest.TestCase): @deco(do_skip, "testing") def test_skip(self): pass @deco(dont_skip, "testing") def test_dont_skip(self): pass test_do_skip = Foo("test_skip") test_dont_skip = Foo("test_dont_skip") suite = unittest.TestSuite([test_do_skip, test_dont_skip]) events = [] result = LoggingResult(events) suite.run(result) self.assertEqual(len(result.skipped), 1) expected = ['startTest', 'addSkip', 'stopTest', 'startTest', 'addSuccess', 'stopTest'] self.assertEqual(events, expected) self.assertEqual(result.testsRun, 2) self.assertEqual(result.skipped, [(test_do_skip, "testing")]) self.assertTrue(result.wasSuccessful())
def skip_unless(condition, reason): # pragma: no cover """Skip tests unless a condition holds. This implements the basic functionality of unittest.skipUnless which is only available on Python 2.7+. :param bool condition: If ``False``, the test will be skipped :param str reason: the reason for skipping the test :rtype: callable :returns: decorator that hides tests unless condition is ``True`` """ if hasattr(unittest, "skipUnless"): return unittest.skipUnless(condition, reason) elif condition: return lambda cls: cls else: return lambda cls: None
def test_2(self, mock): node_data = { FUNCTION: PROTEIN, NAMESPACE: 'HGNC', NAME: 'YFG', VARIANTS: [ { KIND: HGVS, IDENTIFIER: 'p.Glu600Arg' } ] } self.help_test_round_trip(node_data) # FIXME @kono need proper deletion cascades # @unittest.skipUnless('PYBEL_TEST_EXPERIMENTAL' in os.environ, 'Experimental features not ready for Travis')
def test_ref2path_4(self): start = "/home/user/notes" cur = "sub" ref = "/img/index.rst" (p1, ext) = uri2path(ref2uri(ref, cur, start), cur, start) p2 = ref2path(ref, cur, start) self.assertEqual(p1, p2) #@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") #def test_ref2uri_11(self): # ref = "file://C:\pagefile.sys" # uri = "file://labnote.ext.abs/C:/pagefile.sys" # uri_ = ref2uri(ref) # self.assertEqual(uri, uri_) #@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") #def test_ref2uri_12(self): # ref = "sub\index.rst" # uri = "file://labnote.int.rel/sub/index.rst" # uri_ = ref2uri(ref) # self.assertEqual(uri, uri_)
def service_exists(**kwargs): """Decorator function to check whether a service exists Usage: @unittest.skipUnless(base.service_exists(service_type="metering"), "Metering service does not exist") class TestMeter(base.BaseFunctionalTest): ... :param kwargs: The kwargs needed to filter an endpoint. :returns: True if the service exists, otherwise False. """ try: conn = connection.from_config(cloud_name=TEST_CLOUD) conn.session.get_endpoint(**kwargs) return True except _exceptions.EndpointNotFound: return False
def _skipUnless(condition, reason): if hasattr(unittest, 'skipUnless'): return unittest.skipUnless(condition, reason) elif not condition: return _skip else: return _id
def live_only(): return unittest.skipUnless( os.environ.get(ENV_LIVE_TEST, False), 'This is a live only test. A live test will bypass all vcrpy components.')
def record_only(): return unittest.skipUnless( not os.environ.get(ENV_LIVE_TEST, False), 'This test is excluded from being run live. To force a recording, please remove the recording file.')
def _make_tarball(self, target_name): # creating something to tar tmpdir = self.mkdtemp() self.write_file([tmpdir, 'file1'], 'xxx') self.write_file([tmpdir, 'file2'], 'xxx') os.mkdir(os.path.join(tmpdir, 'sub')) self.write_file([tmpdir, 'sub', 'file3'], 'xxx') tmpdir2 = self.mkdtemp() unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0], "source and target should be on same drive") base_name = os.path.join(tmpdir2, target_name) # working with relative paths to avoid tar warnings old_dir = os.getcwd() os.chdir(tmpdir) try: make_tarball(splitdrive(base_name)[1], '.') finally: os.chdir(old_dir) # check if the compressed tarball was created tarball = base_name + '.tar.gz' self.assertTrue(os.path.exists(tarball)) # trying an uncompressed one base_name = os.path.join(tmpdir2, target_name) old_dir = os.getcwd() os.chdir(tmpdir) try: make_tarball(splitdrive(base_name)[1], '.', compress=None) finally: os.chdir(old_dir) tarball = base_name + '.tar' self.assertTrue(os.path.exists(tarball))
def need_symbol(name): return unittest.skipUnless(name in ctypes_symbols, '{!r} is required'.format(name))
def requires_tcl(*version): return unittest.skipUnless(tcl_version >= version, 'requires Tcl version >= ' + '.'.join(map(str, version)))
def skipUnless(condition, reason): return lambda f: condition and f or None
def requireSklearn(target): return skipUnless(sklearn_available, 'requires scikit-learn')(target)
def requirePython3(target): return skipUnless(PYTHON3, 'requires Python 3.x')(target)
def requireEmbedded(target): return skipUnless(embedded_available, 'requires embedded_jubatus')(target)
def run_unittest(*classes): """Run tests from unittest.TestCase-derived classes.""" valid_types = (unittest.TestSuite, unittest.TestCase) suite = unittest.TestSuite() for cls in classes: if isinstance(cls, str): if cls in sys.modules: suite.addTest(unittest.findTestCases(sys.modules[cls])) else: raise ValueError("str arguments must be keys in sys.modules") elif isinstance(cls, valid_types): suite.addTest(cls) else: suite.addTest(unittest.makeSuite(cls)) def case_pred(test): if match_tests is None: return True for name in test.id().split("."): if fnmatch.fnmatchcase(name, match_tests): return True return False _filter_suite(suite, case_pred) _run_suite(suite) # We don't have sysconfig on Py2.6: # #======================================================================= # # Check for the presence of docstrings. # # HAVE_DOCSTRINGS = (check_impl_detail(cpython=False) or # sys.platform == 'win32' or # sysconfig.get_config_var('WITH_DOC_STRINGS')) # # requires_docstrings = unittest.skipUnless(HAVE_DOCSTRINGS, # "test requires docstrings") # # # #======================================================================= # doctest driver.
def skip_unless__testcapi(func): msg = "Requires the CPython C Extension API ({!r} module)".format(NAME) return unittest.skipUnless(PATH, msg)(func)
def test_make_tarball(self): # creating something to tar tmpdir = self.mkdtemp() self.write_file([tmpdir, 'file1'], 'xxx') self.write_file([tmpdir, 'file2'], 'xxx') os.mkdir(os.path.join(tmpdir, 'sub')) self.write_file([tmpdir, 'sub', 'file3'], 'xxx') tmpdir2 = self.mkdtemp() # force shutil to create the directory os.rmdir(tmpdir2) unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0], "source and target should be on same drive") base_name = os.path.join(tmpdir2, 'archive') # working with relative paths to avoid tar warnings old_dir = os.getcwd() os.chdir(tmpdir) try: _make_tarball(splitdrive(base_name)[1], '.') finally: os.chdir(old_dir) # check if the compressed tarball was created tarball = base_name + '.tar.gz' self.assertTrue(os.path.exists(tarball)) # trying an uncompressed one base_name = os.path.join(tmpdir2, 'archive') old_dir = os.getcwd() os.chdir(tmpdir) try: _make_tarball(splitdrive(base_name)[1], '.', compress=None) finally: os.chdir(old_dir) tarball = base_name + '.tar' self.assertTrue(os.path.exists(tarball))
def skipUnlessImported(module, obj): import importlib try: m = importlib.import_module(module) except ImportError: m = None return unittest.skipUnless( obj in dir(m), "Skipping test because {} could not be imported from {}".format( obj, module))
def test_unicode(self): if not test_support.have_unicode: # Python 2.5 has no unittest.skipUnless self.skipTest('no unicode support') endcases = [u'', u'<\\u>', u'<\\%c>' % 0x1234, u'<\n>', u'<\\>'] for proto in pickletester.protocols: for u in endcases: p = self.dumps(u, proto) u2 = self.loads(p) self.assertEqual(u2, u) # The ability to pickle recursive objects was added in 2.7.11 to fix # a crash in CPickle (issue #892902).
def requires_curses_func(name): return unittest.skipUnless(hasattr(curses, name), 'requires curses.%s' % name)
def needs_helpers_speedup(test_class): if bezier is None: has_speedup = False # pragma: NO COVER else: has_speedup = bezier._HAS_HELPERS_SPEEDUP decorator = unittest.skipUnless( has_speedup, 'No helpers speedup available') return decorator(test_class)
def needs_curve_speedup(test_class): if bezier is None: has_speedup = False # pragma: NO COVER else: has_speedup = bezier._HAS_CURVE_SPEEDUP decorator = unittest.skipUnless( has_speedup, 'No curve speedup available') return decorator(test_class)
def needs_surface_speedup(test_class): if bezier is None: has_speedup = False # pragma: NO COVER else: has_speedup = bezier._HAS_SURFACE_SPEEDUP decorator = unittest.skipUnless( has_speedup, 'No surface speedup available') return decorator(test_class) # pylint: disable=invalid-name
def needs_curve_intersection_speedup(test_class): if bezier is None: has_speedup = False # pragma: NO COVER else: has_speedup = bezier._HAS_CURVE_INTERSECTION_SPEEDUP decorator = unittest.skipUnless( has_speedup, 'No curve intersection speedup available') return decorator(test_class) # pylint: enable=invalid-name # pylint: disable=invalid-name
def needs_surface_intersection_speedup(test_class): if bezier is None: has_speedup = False # pragma: NO COVER else: has_speedup = bezier._HAS_SURFACE_INTERSECTION_SPEEDUP decorator = unittest.skipUnless( has_speedup, 'No surface intersection speedup available') return decorator(test_class) # pylint: enable=invalid-name
def setUpClass(cls): # Symlink the darwin analyzer into Cuckoo's analyzer directory source = path.join(ANALYZER_ROOT, "analyzer", "darwin") destination = path.join(cuckoo_root(), "analyzer", "darwin") # setUpClass() is called even when @unittest.skipUnless skips # all the tests, so we verify it again... if path.exists(cuckoo_root()): if not path.exists(destination): symlink(source, destination) # Initialize Cuckoo Host cls.launch_cuckoo()
def skipUnless(condition, reason): if condition: return lambda item: item else: return skip(reason)
def test_make_tarball(self): # creating something to tar tmpdir = self.mkdtemp() write_file((tmpdir, 'file1'), 'xxx') write_file((tmpdir, 'file2'), 'xxx') os.mkdir(os.path.join(tmpdir, 'sub')) write_file((tmpdir, 'sub', 'file3'), 'xxx') tmpdir2 = self.mkdtemp() # force shutil to create the directory os.rmdir(tmpdir2) unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0], "source and target should be on same drive") base_name = os.path.join(tmpdir2, 'archive') # working with relative paths to avoid tar warnings old_dir = os.getcwd() os.chdir(tmpdir) try: _make_tarball(splitdrive(base_name)[1], '.') finally: os.chdir(old_dir) # check if the compressed tarball was created tarball = base_name + '.tar.gz' self.assertTrue(os.path.exists(tarball)) # trying an uncompressed one base_name = os.path.join(tmpdir2, 'archive') old_dir = os.getcwd() os.chdir(tmpdir) try: _make_tarball(splitdrive(base_name)[1], '.', compress=None) finally: os.chdir(old_dir) tarball = base_name + '.tar' self.assertTrue(os.path.exists(tarball))
def skip_if_not_supported(y): msg = "strftime() is limited to [1; 9999] with Visual Studio" # Check that it doesn't crash for year > 9999 try: time.strftime('%Y', (y,) + (0,) * 8) except ValueError: cond = False else: cond = True return unittest.skipUnless(cond, msg)