我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用unittest.skipIf()。
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 testSecondInterrupt(self): # Can't use skipIf decorator because the signal handler may have # been changed after defining this method. if signal.getsignal(signal.SIGINT) == signal.SIG_IGN: self.skipTest("test requires SIGINT to not be ignored") result = unittest.TestResult() unittest.installHandler() unittest.registerResult(result) def test(result): pid = os.getpid() os.kill(pid, signal.SIGINT) result.breakCaught = True self.assertTrue(result.shouldStop) os.kill(pid, signal.SIGINT) self.fail("Second KeyboardInterrupt not raised") try: test(result) except KeyboardInterrupt: pass else: self.fail("Second KeyboardInterrupt not raised") self.assertTrue(result.breakCaught)
def testHandlerReplacedButCalled(self): # Can't use skipIf decorator because the signal handler may have # been changed after defining this method. if signal.getsignal(signal.SIGINT) == signal.SIG_IGN: self.skipTest("test requires SIGINT to not be ignored") # If our handler has been replaced (is no longer installed) but is # called by the *new* handler, then it isn't safe to delay the # SIGINT and we should immediately delegate to the default handler unittest.installHandler() handler = signal.getsignal(signal.SIGINT) def new_handler(frame, signum): handler(frame, signum) signal.signal(signal.SIGINT, new_handler) try: pid = os.getpid() os.kill(pid, signal.SIGINT) except KeyboardInterrupt: pass else: self.fail("replaced but delegated handler doesn't raise interrupt")
def skipIfCustomUser(test_func): """ Skip a test if a custom user model is in use. """ warnings.warn( "django.contrib.auth.tests.utils.skipIfCustomUser is deprecated.", RemovedInDjango20Warning, stacklevel=2) return skipIf(settings.AUTH_USER_MODEL != 'auth.User', 'Custom user model in use')(test_func)
def skip(reason, condition=None): """ Mark a test case or method for skipping. @param reason: message @type reason: str @param condition: skip only if the specified condition is True @type condition: bool/expression """ if isinstance(reason, types.FunctionType): raise TypeError('skip: no reason specified') if condition is None: return unittest.skip(reason) else: return unittest.skipIf(condition, reason)
def test_compute_rollover_daily_attime(self): currentTime = 0 atTime = datetime.time(12, 0, 0) rh = logging.handlers.TimedRotatingFileHandler( self.fn, when='MIDNIGHT', interval=1, backupCount=0, utc=True, atTime=atTime) try: actual = rh.computeRollover(currentTime) self.assertEqual(actual, currentTime + 12 * 60 * 60) actual = rh.computeRollover(currentTime + 13 * 60 * 60) self.assertEqual(actual, currentTime + 36 * 60 * 60) finally: rh.close() #@unittest.skipIf(True, 'Temporarily skipped while failures investigated.')
def test_camelCase(self): self.assertEqual(scrape.camelCase("SPELL"), "Spell") self.assertEqual(scrape.camelCase("HERO_POWER"), "Hero Power") self.assertEqual(scrape.camelCase(""), None) self.assertEqual(scrape.camelCase(None), None) # @unittest.skipIf(SKIP_INTERNET_TESTS, "requires internet (and is slow)")
def skipIf(condition, reason): def skipper(func): def skip(*args, **kwargs): return if condition: return skip return func return skipper
def __getattr__(self, name): """Proxy all unknown attributes to the original method. This is important for some of the decorators in the `unittest` module, such as `unittest.skipIf`. """ return getattr(self.orig_method, name)
def skipIf(cond, msg): def skipIf_(f): @wraps(f) def skipIf__(self): if cond: with warnings.catch_warnings(): warnings.simplefilter('always', UserWarning) warnings.warn(msg) return else: return f(self) return skipIf__ return skipIf_
def skip(msg): return skipIf(True, msg)
def require_jinja2(test_func): """ Decorator to enable a Jinja2 template engine in addition to the regular Django template engine for a test or skip it if Jinja2 isn't available. """ test_func = skipIf(jinja2 is None, "this test requires jinja2")(test_func) test_func = override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }, { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'APP_DIRS': True, 'OPTIONS': {'keep_trailing_newline': True}, }])(test_func) return test_func
def root_required(method): decorator = unittest.skipIf(os.getuid() != 0, 'root required') return decorator(method)
def with_requires(*requirements): """Run a test case only when given requirements are satisfied. .. admonition:: Example This test case runs only when `numpy>=1.10` is installed. >>> from cupy import testing ... class Test(unittest.TestCase): ... @testing.with_requires('numpy>=1.10') ... def test_for_numpy_1_10(self): ... pass Args: requirements: A list of string representing requirement condition to run a given test case. """ ws = pkg_resources.WorkingSet() try: ws.require(*requirements) skip = False except pkg_resources.ResolutionError: skip = True msg = 'requires: {}'.format(','.join(requirements)) return unittest.skipIf(skip, msg)
def multi_gpu(gpu_num): """Decorator to indicate number of GPUs required to run the test. Tests can be annotated with this decorator (e.g., ``@multi_gpu(2)``) to declare number of GPUs required to run. When running tests, if ``CUPY_TEST_GPU_LIMIT`` environment variable is set to value greater than or equals to 0, test cases that require GPUs more than the limit will be skipped. """ check_available() return unittest.skipIf( 0 <= _gpu_limit and _gpu_limit < gpu_num, reason='{} GPUs required'.format(gpu_num))
def test_with_rw_repo(self, rw_repo): assert not rw_repo.config_reader("repository").getboolean("core", "bare") assert osp.isdir(osp.join(rw_repo.working_tree_dir, 'lib')) #@skipIf(HIDE_WINDOWS_FREEZE_ERRORS, "FIXME: Freezes! sometimes...")
def skipIf(condition, why, _skip=lambda test_method: None, _keep=lambda test_method: test_method): if condition: return _skip return _keep
def skip_if_windows(reason): """Decorator to skip tests that should not be run on windows. Example usage: @skip_if_windows("Not valid") def test_some_non_windows_stuff(self): self.assertEqual(...) """ def decorator(func): return unittest.skipIf( platform.system() not in ['Darwin', 'Linux'], reason)(func) return decorator
def test_likes(self): for i in range(10): x = map(str, list(range(i))) shuffle(x) self.assertEqual(aula2.likes(x), gabarito_aula2.likes(x) @unittest.skipIf('remove_duplicates' not in vars(aula2), 'Função "remove_duplicates" não foi encontrada') def test_remove_duplicates(self): for _ in range(40): t = [randint(0,5) for _ in range(randint(0, 30))] self.assertEqual(aula2.remove_duplicates(t), remove_duplicates(t)) @unittest.skipIf('different_evenness' not in vars(aula2), 'Função "different_evenness" não foi encontrada') def test_different_evenness(self): for _ in range(40): testlen=randint(3,50) oddeven=randint(0,1) testmat=[randint(0,25)*2+oddeven for x in range(testlen)] solution=randint(1,testlen) testmat[solution-1]+=1 testmat=(" ").join(map(str,testmat)) self.assertEqual(different_evenness(testmat), solution) if __name__ == '__main__': unittest.main(verbosity=2)
def test_discover_system_effect(self): converter = self.mod_converter pedalboard_path = self.here / Path('teste.pedalboard') print(converter.get_pedalboard_info(pedalboard_path)) pedalboard = converter.convert(pedalboard_path) print(pedalboard.json) #@unittest.skipIf('TRAVIS' in os.environ, 'Mod-ui not configured in Travis build')
def test_02getsystemglobal(self): resp = fgt.get('system','global', vdom="global") fortiversion = resp['version'] self.assertEqual(resp['status'], 'success') #should put a test on version to disable if less than 5.6 don't work decoration #@unittest.skipIf(Version(fgt.get_version()) < Version('5.6'), # "not supported with fortios before 5.6")