def needs_aws(test_item): """ Use as a decorator before test classes or methods to only run them if AWS usable. """ test_item = _mark_test('aws', test_item) try: # noinspection PyUnresolvedReferences from boto import config except ImportError: return unittest.skip("Install toil with the 'aws' extra to include this test.")(test_item) except: raise else: dot_aws_credentials_path = os.path.expanduser('~/.aws/credentials') hv_uuid_path = '/sys/hypervisor/uuid' boto_credentials = config.get('Credentials', 'aws_access_key_id') if boto_credentials: return test_item if (os.path.exists(dot_aws_credentials_path) or (os.path.exists(hv_uuid_path) and file_begins_with(hv_uuid_path, 'ec2'))): # Assume that EC2 machines like the Jenkins slave that we run CI on will have IAM roles return test_item else: return unittest.skip("Configure ~/.aws/credentials with AWS credentials to include " "this test.")(test_item)
def needs_aws(test_item): """ Use as a decorator before test classes or methods to only run them if AWS usable. """ test_item = _mark_test('aws', test_item) try: # noinspection PyUnresolvedReferences import boto except ImportError: return unittest.skip("Skipping test. Install toil with the 'aws' extra to include this " "test.")(test_item) except: raise else: dot_boto_path = os.path.expanduser('~/.boto') dot_aws_credentials_path = os.path.expanduser('~/.aws/credentials') hv_uuid_path = '/sys/hypervisor/uuid' if (os.path.exists(dot_boto_path) or os.path.exists(dot_aws_credentials_path) # Assume that EC2 machines like the Jenkins slave that we run CI on will have IAM roles or os.path.exists(hv_uuid_path) and file_begins_with(hv_uuid_path,'ec2')): return test_item else: return unittest.skip("Skipping test. Create ~/.boto or ~/.aws/credentials to include " "this test.")(test_item)
def wrapped(_class, simple=False, skip=None, require=None, flows=None): if type(_class) == FunctionType: _class = make_test_case_class_from_function( _class, simple=simple, base_class=self.TestCase, ) if flows: for method_name in loader.load_test_names_from_test_case(_class): setattr(_class, method_name, _flows(*flows)(getattr(_class, method_name))) if skip: unittest.skip(skip)(_class) if hasattr(_class, 'REQUIRE'): raise RuntimeError('"REQUIRE" attribute can not be pre set') if require: setattr(_class, 'REQUIRE', require) self.__context.add_test_case(_class) logger.debug( 'Register test case "{}" on {}'.format( _class.__name__, repr(self), ), ) return _class
def decorate_it(f): if hide_skipped_tests: ret_val = unittest.skip(msg_or_f) ret_val.__name__ = '_pretty_skipped_function' return ret_val else: return unittest.skip(msg_or_f)(f)
def bzbug(bz_id): """Decorator that skips the test if the bugzilla's bug is open""" try: mybz = bugzilla.RHBugzilla() mybz.connect(BUGZILLA_URL) except (TypeError, ValueError): logging.warning("Invalid Bugzilla ID {0}".format(bz_id)) return lambda func: func attempts = 0 mybug = None while attempts < 3 and mybug is None: try: mybug = mybz.getbugsimple(bz_id) except ExpatError: attempts += 1 if not mybug is None: if (mybug.status == 'NEW') or (mybug.status == 'ASSIGNED'): logging.debug(mybug) return unittest.skip("Test skipped due to %s" % mybug) else: return lambda func: func else: return unittest.skip( "Test skipped due to not being able to fetch bug #%s info" % bz_id)
def requires_resource(resource): if resource == "gui" and not _is_gui_available(): return unittest.skip("resource 'gui' is not available") if is_resource_enabled(resource): return _id else: return unittest.skip("resource {0!r} is not enabled".format(resource))
def skipUnlessPG92(test): if not connection.vendor == 'postgresql': return unittest.skip('PostgreSQL required')(test) PG_VERSION = connection.pg_version if PG_VERSION < 90200: return unittest.skip('PostgreSQL >= 9.2 required')(test) return test
def patch_wagtail_settings(): # fix fixture paths to be absolute paths from wagtail import tests from wagtail.wagtailimages.tests import test_models fixture_path = os.path.join( os.path.dirname(tests.__file__), 'fixtures', 'test.json') test_models.TestUsageCount.fixtures = [fixture_path] test_models.TestGetUsage.fixtures = [fixture_path] test_models.TestGetWillowImage.fixtures = [fixture_path] from wagtail.wagtailimages.tests import tests tests.TestMissingImage.fixtures = [fixture_path] from wagtail.wagtailimages.tests import test_rich_text test_rich_text.TestImageEmbedHandler.fixtures = [fixture_path] # skip these test - they rely on media URL matching filename from wagtail.wagtailimages.tests.tests import TestMissingImage TestMissingImage.test_image_tag_with_missing_image = \ unittest.skip('Unsupported')( TestMissingImage.test_image_tag_with_missing_image) TestMissingImage.test_rich_text_with_missing_image = \ unittest.skip('Unsupported')( TestMissingImage.test_rich_text_with_missing_image) # filter these warnings import warnings warnings.simplefilter('default', DeprecationWarning) warnings.simplefilter('default', PendingDeprecationWarning)
def test_start_with_two_args(self): if not self.open_argument.startswith('/'): unittest.skip("Only relevant for base class") path = os.path.join( self.app_dir, 'dist/argv.txt') if os.path.exists(path): os.unlink(path) self.maxDiff = None path = os.path.join( self.app_dir, 'dist/BasicApp.app') p = subprocess.Popen(["/usr/bin/open", '-a', path, "--args", "one", "two", "three"]) exit = p.wait() self.assertEqual(exit, 0) path = os.path.join( self.app_dir, 'dist/argv.txt') for x in range(70): # Argv emulation can take up-to 60 seconds time.sleep(1) if os.path.exists(path): break self.assertTrue(os.path.isfile(path)) fp = open(path, 'r') data = fp.read().strip() fp.close() self.assertEqual(data.strip(), repr([os.path.join(self.app_dir, 'dist/BasicApp.app/Contents/Resources/main.py'), "one", "two", "three"]))
def test_connect_kat(self): """Testing connection to KickAssTorrent""" if any('kat' == providers['provider_type'] for providers in self.ts['providers']): self.ts.connect_provider('kat') self.ts.test() else: unittest.skip("KickAssTorrent is not setup".encode('utf8'))
def test_connect_t411(self): """Testing connection to T411""" if any('t411' == providers['provider_type'] for providers in self.ts['providers']): self.ts.connect_provider('t411') self.ts.test() else: unittest.skip("T411 is not setup".encode('utf8'))
def test_compile(self): # type: () -> None """Exercise the code generator so code coverage can be measured.""" base_dir = os.path.dirname( os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) src_dir = os.path.join( base_dir, 'src', ) idl_dir = os.path.join(src_dir, 'mongo', 'idl') args = idl.compiler.CompilerArgs() args.output_suffix = "_codecoverage_gen" args.import_directories = [src_dir] unittest_idl_file = os.path.join(idl_dir, 'unittest.idl') if not os.path.exists(unittest_idl_file): unittest.skip("Skipping IDL Generator testing since %s could not be found." % (unittest_idl_file)) return args.input_file = os.path.join(idl_dir, 'unittest_import.idl') self.assertTrue(idl.compiler.compile_idl(args)) args.input_file = unittest_idl_file self.assertTrue(idl.compiler.compile_idl(args))
def skipUnlessTrue(descriptor): if not hasattr(config, descriptor): return unittest.skip("%s not defined in config.py, skipping" % descriptor) if getattr(config, descriptor) == 0: return unittest.skip("%s set to False in config.py, skipping" % descriptor) else: return lambda func: func
def requiresSphinx(): """ A decorator: a test requires Sphinx """ if sphinxIsAvailable: return lambda func: func elif sphinxVersion is not None: return unittest.skip('Sphinx is too old. {} required'.format(_SPHINX_VERSION)) else: return unittest.skip('Sphinx not found')
def __init__(cls, name, bases, dct): super(SkipTestsMeta, cls).__init__(name, bases, dct) if cls.__name__ == "DatastoreInputReaderBaseTest": unittest.skip("Skip tests when testing from the base class.")(cls) else: # Since there is no unittest.unskip(), do it manually. cls.__unittest_skip__ = False cls.__unittest_skip_why__ = None
def __init__(self, *args, **kwargs): super(OptimizedStaticFilesStorageTestsMixin, self).__init__(*args, **kwargs) if not self.has_environment(): skip_message = "No {environment} present.".format(environment=self.require_environment) self.testCollectStatic = unittest.skip(skip_message)(self.testCollectStatic) self.testCollectStaticBuildProfile = unittest.skip(skip_message)(self.testCollectStaticBuildProfile) self.testCollectStaticStandalone = unittest.skip(skip_message)(self.testCollectStaticStandalone) self.testCollectStaticStandaloneBuildProfile = unittest.skip(skip_message)(self.testCollectStaticStandaloneBuildProfile)
def test_chown(self) : if not is_privileged : LogFile.write("skipping %s...\n" % inspect.stack()[0][3]) unittest.skip("rpc-server not running as privileged user") return LogFile.write("testing %s...\n" % inspect.stack()[0][3]) res = proxy.hpss_chown("%s/%s" % (hpss_test_dir, hpss_test_file) ,{}, 63232, 63232) LogFile.write("res=%s\n\n" % res) self.assertEqual(proxy.check_error(res)[1], "")
def skip_unless_galaxy(min_release=None): """ Decorate tests with this to skip the test if Galaxy is not configured. """ if min_release is not None: galaxy_release = os.environ.get('GALAXY_VERSION', None) if galaxy_release is not None and galaxy_release != 'dev': if not galaxy_release.startswith('release_'): raise ValueError("The value of GALAXY_VERSION environment variable should start with 'release_'") if not min_release.startswith('release_'): raise Exception("min_release should start with 'release_'") if galaxy_release[8:] < min_release[8:]: return unittest.skip(OLD_GALAXY_RELEASE % (galaxy_release, min_release)) if 'BIOBLEND_GALAXY_URL' not in os.environ: return unittest.skip(NO_GALAXY_MESSAGE) if 'BIOBLEND_GALAXY_API_KEY' not in os.environ and 'BIOBLEND_GALAXY_MASTER_API_KEY' in os.environ: galaxy_url = os.environ['BIOBLEND_GALAXY_URL'] galaxy_master_api_key = os.environ['BIOBLEND_GALAXY_MASTER_API_KEY'] gi = bioblend.galaxy.GalaxyInstance(galaxy_url, galaxy_master_api_key) if 'BIOBLEND_GALAXY_USER_EMAIL' in os.environ: galaxy_user_email = os.environ['BIOBLEND_GALAXY_USER_EMAIL'] else: galaxy_user_email = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(5)) + "@localhost.localdomain" galaxy_user_id = None for user in gi.users.get_users(): if user["email"] == galaxy_user_email: galaxy_user_id = user["id"] break if galaxy_user_id is None: try: config = gi.config.get_config() except Exception: # If older Galaxy for instance just assume use_remote_user is False. config = {} if config.get("use_remote_user", False): new_user = gi.users.create_remote_user(galaxy_user_email) else: galaxy_user = galaxy_user_email.split("@", 1)[0] galaxy_password = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(20)) # Create a new user and get a new API key for her new_user = gi.users.create_local_user(galaxy_user, galaxy_user_email, galaxy_password) galaxy_user_id = new_user["id"] api_key = gi.users.create_user_apikey(galaxy_user_id) os.environ["BIOBLEND_GALAXY_API_KEY"] = api_key if 'BIOBLEND_GALAXY_API_KEY' not in os.environ: return unittest.skip(NO_GALAXY_MESSAGE) return lambda f: f
def test_getdatabase_postgres_nohostname_noport_setdefault(self): """Check get_database set default hostname and port for MySQL""" try: db = AccessionID(dbname='taxadb', dbtype='postgres', password="******", username="******") self.assertEqual(int(db.get('port')), 5432) self.assertEqual(db.get('hostname'), 'localhost') except SystemExit as err: unittest.skip("Can't test function: %s" % str(err))
def test_positive_update_my_account_3(self): """ @Feature: My Account - Positive Update @Test: Update Email Address in My Account @Steps: 1. Update current User with all variations of Email Address in [1] @Assert: Current User is updated @Status: Manual """ unittest.skip(NOT_IMPLEMENTED)
def test_positive_update_my_account_4(self): """ @Feature: My Account - Positive Update @Test: Update Language in My Account @Steps: 1. Update current User with all different Language options @Assert: Current User is updated @Status: Manual """ unittest.skip(NOT_IMPLEMENTED)
def test_positive_update_my_account_5(self): """ @Feature: My Account - Positive Update @Test: Update Password/Verify fields in My Account @Steps: 1. Update Password/Verify fields with all variations in [1] @Assert: User is updated @Status: Manual """ unittest.skip(NOT_IMPLEMENTED)
def test_negative_update_my_account_2(self): """ @Feature: My Account - Negative Update @Test: Update My Account with invalid Surname @Steps: 1. Update Current user with all variations of Surname in [2] @Assert: User is not updated. Appropriate error shown. @Status: Manual """ unittest.skip(NOT_IMPLEMENTED)
def eval_skipif(self): if hasattr(self.__class__, SkipIfDecorator.MARK_NAME): skipif_mark = getattr(self.__class__, SkipIfDecorator.MARK_NAME) if skipif_mark.check_condition(self): unittest.skip(skipif_mark.reason)(self.__class__) method = getattr(self, self._testMethodName) if hasattr(method, SkipIfDecorator.MARK_NAME): skipif_mark = getattr(method, SkipIfDecorator.MARK_NAME) if skipif_mark.check_condition(self): setattr(self, self._testMethodName, unittest.skip(skipif_mark.reason)(method))
def test_vm_create_on_multi_host_natural_algorithm(self): und_sys = self.vtm.underlay_system if len(und_sys.hosts) < 2: unittest.skip("Need more than one host") return vm = self.vtm.create_vm(name='vm1') self.vms.append(vm) vm2 = self.vtm.create_vm(name='vm2') self.vms.append(vm2) self.assertNotEqual(vm.get_hypervisor_name(), vm2.get_hypervisor_name())
def test_template_04_pimages(self): templateList = api.Users(userTest).Appliances.Getall() templateList = templateList.appliances.appliance if len(templateList) == 0: unittest.skip("No Template list for userTest.") else: templateID = str(templateList[0].dbId) template = Template_Cmd() template.set_globals(api,login,password) t = template.do_pimages("--account " + userTest + " --id " + templateID) self.assertEquals(t,0)
def init(self, config_content=None): """ load plugin config and initialise the plugin """ if config_content: self.conf.loadFromString(config_content) else: if os.path.isfile(CHATLOGGER_CONFIG_FILE): self.conf.load(CHATLOGGER_CONFIG_FILE) else: unittest.skip("default config file '%s' does not exists" % CHATLOGGER_CONFIG_FILE) return self.p.onLoadConfig() self.p.onStartup()
def test_negative_update_my_account_5(self): """ @Feature: My Account - Negative Update @Test: Update My Account with non-matching values in Password and verify fields @Steps: 1. Update Current user with non-matching values in Password and verify fields @Assert: User is not updated. Appropriate error shown. @Status: Manual """ unittest.skip(NOT_IMPLEMENTED)
def skip_unless_galaxy(min_release=None): """ Decorate tests with this to skip the test if Galaxy is not configured. """ if min_release is not None: galaxy_release = os.environ.get('GALAXY_VERSION', None) if galaxy_release is not None and galaxy_release.startswith('release_') and galaxy_release < min_release: return unittest.skip(OLD_GALAXY_RELEASE % (galaxy_release, min_release)) for prop in ['BIOBLEND_GALAXY_URL', 'BIOBLEND_GALAXY_API_KEY']: if prop not in os.environ: return unittest.skip(NO_GALAXY_MESSAGE) return lambda f: f
def test_org_24_create(self): orgs = api.Orgs(orgNumber).Getall() exist = False for item in orgs.orgs.org: if item.name == orgCreate: exist = True if exist: unittest.skip("Organization already created.") else: org = Org_Cmd() org.set_globals(api,login,password) t = org.do_create("--org " + orgCreate) self.assertEquals(t,0)
def wrap(func): return unittest.skip(reason)(func)
def requires_internet(test): # Decorator msg = 'requires internet' return test if HAS_INTERNET else unittest.skip(msg)(test)
# # ESPResSo is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import unittest as ut import importlib_wrapper try: import MDAnalysis except ImportError: sample = importlib_wrapper.MagicMock() skipIfMissingFeatures = ut.skip( "Python module MDAnalysis not available, skipping test!") else: sample, skipIfMissingFeatures = importlib_wrapper.configure_and_import( "@SAMPLES_DIR@/MDAnalysisIntegration.py") @skipIfMissingFeatures class Sample(ut.TestCase): system = sample.system if __name__ == "__main__": ut.main()
def skipIfNoSecurity(testfunc): try: import zope.security except ImportError: return unittest.skip("zope.security not installed")(testfunc) return testfunc
def skipIfNoTransducer(test_item): try: torch.ops.torchaudio.rnnt_loss return test_item except RuntimeError: return unittest.skip("torchaudio C++ extension is not compiled with RNN transducer loss")
def test_ip_leases_nm(self): unittest.skip( "Cannot be tested offline due to calls required to nmcli." "This is tested in integration tests.")
def skipImage(reason, *args): image = testinfra.DEFAULT_IMAGE if image in args: return unittest.skip("{0}: {1}".format(image, reason)) return lambda func: func
def skip_unless_watchman_available(): try: autoreload.WatchmanReloader.check_availability() except WatchmanUnavailable as e: return skip('Watchman unavailable: %s' % e) return lambda func: func
def maybe_skip(skip, test_case, test): if skip is not None: reason = skip(test) if reason is not None: test_case = unittest.skip(reason)(test_case) return test_case
def sql_test(f): try: import psycopg2 return unittest.skipIf(not sql_version, "Database is not running.")(f) except: return unittest.skip("Psycopg2 is required for sql tests.")(f)
def require_faiss(test_case): """Decorator marking a test that requires faiss.""" if not _faiss_available: return unittest.skip("test requires `faiss`")(test_case) else: return test_case
def test_message_normalization(self): self.assertEqual(True, False) unittest.skip("Not finished yet")
def require_torch_gpu(test_case): """Decorator marking a test that requires CUDA and PyTorch. """ if torch_device != "cuda": return unittest.skip("test requires CUDA")(test_case) else: return test_case
def requires_usable_pip(f): deco = unittest.skip(ensurepip._MISSING_SSL_MESSAGE) return deco(f)
def skip_if_not_mysql_or_sqlite(test_fn): if any( i.rsplit('.', 1)[-1] not in ('mysql', 'sqlite3') for i in _db_engines()): return skip('requires either mysql or sqlite')(test_fn) return test_fn
# and there is no way for general descriptors. elif is_tensor_method_or_property(func): module = "Tensor" else: module = func.__module__ if module: name = 'test_{}_{}'.format(module.replace('.', '_'), func.__name__) else: name = 'test_{}'.format(func.__name__) test_method.__name__ = name setattr(cls, name, test_method) generate_tensor_like_override_tests(TestTorchFunctionOverride) TestTorchFunctionOverride.test_torch_functional_histogramdd = unittest.skip( "histogramdd is missing __torch_function__ support")( TestTorchFunctionOverride.test_torch_functional_histogramdd) class Wrapper: "Basic data container that knows how to unwrap itself" def __init__(self, data): self.__dict__["_data"] = data self.__dict__["used_attrs"] = set() self.__dict__["used_calls"] = set() def __getattr__(self, name): if name in self.__dict__: return self.__dict__[name] self.used_attrs.add(name)
def testIntegration(self) : if skipTest(self.test) : return skip('test disabled') output = surfaceRealize(self.data, self.meta) assertEqual(self, output, self.expected)
class AsyncTest(CacheClientTestMixIn, unittest.TestCase): # Hard to guarantee LRU logic with an async writing queue is_lru = False # Capacity is a tuple, and lazy-init makes it not stable, so can't test that meaningful_capacity = False def setUpClient(self): from chorde.clients.inproc import InprocCacheClient from chorde.clients.async import AsyncWriteCacheClient return AsyncWriteCacheClient(InprocCacheClient(100), 100, 1) def _sync(self, client): from chorde.clients.async import Defer ev = threading.Event() client.put('__sync_key', Defer(ev.set), 120) ev.wait(1) def testDeferreds(self): from chorde.clients.async import Defer done = [] ev = threading.Event() def sleepit(): done.append(None) ev.set() return done self.client.put(1, Defer(sleepit), 120) self.assertTrue(self.client.contains(1)) self.assertTrue(ev.wait(1)) self.assertTrue(self.client.contains(1)) self.assertEquals(self.client.get(1), [None]) self.assertEquals(done, [None]) def testFutures(self): from chorde.clients.async import Defer, Future frv = Future() def sleepit(): return 1 d = Defer(sleepit) d.future = frv self.client.put(2, d, 120) self.assertTrue(self.client.contains(2)) self.assertEquals(frv.result(1), 1) self.assertTrue(self.client.contains(2)) self.assertEquals(self.client.get(2), 1) self.assertTrue(frv.done()) def testChainFutures(self): from chorde.clients.async import Defer, Future ev = threading.Event() ev2 = threading.Event() def sleepit(): ev.wait() return 2 def sleepit2(): ev2.wait() return 3 d1 = Defer(sleepit) d2 = Defer(sleepit2) d1.future = Future() d2.future = Future() self.addCleanup(ev.set) self.addCleanup(ev2.set) self.client.put(1, sleepit, 120) # Delay the pool self.client.put(3, d1, 120) self.client.put(3, d2, 120) self.assertTrue(self.client.contains(3)) ev.set() self.assertEquals(d1.future.result(1), 2) self.assertEquals(d2.future.result(1), 2) self.assertTrue(self.client.contains(3)) self.assertEquals(self.client.get(3), 2) def testReentrantChainFutures(self): from chorde.clients.async import Defer, Future ev = threading.Event() ev2 = threading.Event() ev3 = threading.Event() def sleepit(): ev3.set() ev.wait() return 2 def sleepit2(): return 3 d1 = Defer(sleepit) d2 = Defer(sleepit2) d1.future = Future() d2.future = Future() self.addCleanup(ev.set) self.addCleanup(ev2.set) client = self.client def putit(): # Delay reentrant call until d1 was queued ev2.wait() client.put(4, d2, 120) return 4 d3 = Defer(putit) d3.future = Future() self.client.put(3, d3, 120) self.client.put(4, d1, 120) ev2.set() # Unblock reentrant call now self.assertTrue(self.client.contains(3)) self.assertEquals(d3.future.result(1), 4) ev3.wait(1) # Avoid catching 4 in the blind spot between queuing and execution self.assertTrue(self.client.contains(4)) ev.set() # Unblock d1 self.assertEquals(d1.future.result(1), 2) self.assertEquals(d2.future.result(1), 2) self.assertTrue(self.client.contains(4)) self.assertEquals(self.client.get(4), 2) def testStepFutures(self): from chorde.clients.async import Defer, Future ev = threading.Event() ev2 = threading.Event() def sleepit(): ev2.set() ev.wait() return 2 d1 = Defer(sleepit) d1.future = Future() self.addCleanup(ev.set) self.client.put(1, Defer(sleepit), 120) # Delay the pool self.client.put(4, d1, 120) self.client.put(4, 7, 120) self.assertTrue(self.client.contains(4)) self.assertEquals(d1.future.result(1), 7) self.assertTrue(self.client.contains(4)) self.assertEquals(self.client.get(4), 7) # Purge is asynchronous and purges the writing queue first, # so guaranteeing sync semantics isn't really efficient testPurge = unittest.expectedFailure(CacheClientTestMixIn.testPurge) # Testing limits cannot be done deterministically because of the # concurrent worker, so don't bother testLimit = unittest.skip("non-deterministic")(CacheClientTestMixIn.testLimit)
def deepTest(reason): if reason: return lambda x: x return unittest.skip( "Not deep scanning, enable deepscan by adding 'deep' argument")
def travis_test(test_item): test_item = _mark_test('travis', test_item) if os.environ.get('TRAVIS') != 'true': return unittest.skip("Set TRAVIS='true' to include this test.")( test_item) return test_item
def requires_mpl15(test): # Decorator msg = 'requires mpl V 1.5+' return test if mpl.__version__ >= '1.5' else unittest.skip(msg)(test)
def needs_gridengine(test_item): """Use as a decorator before test classes or methods to run only if GridEngine is installed.""" test_item = _mark_test('gridengine', test_item) if which('qhost'): return test_item return unittest.skip("Install GridEngine to include this test.")(test_item)
def requires_mpltest(test): # Decorator msg = 'requires matplotlib.testing.decorators' return test if HAS_MPL_TEST else unittest.skip(msg)(test)
def skip_if_mysql(fn): if connection.vendor == "mysql": return unittest.skip("MySQL does not support tested feature")(fn) return fn
def needs_torque(test_item): """Use as a decorator before test classes or methods to run only ifPBS/Torque is installed.""" test_item = _mark_test('torque', test_item) if which('pbsnodes'): return test_item return unittest.skip("Install PBS/Torque to include this test.")(test_item)
import unittest import warnings import numpy import cupy from cupy import testing import cupyx.scipy.linalg if cupyx.scipy._scipy_available: import scipy.linalg # TODO: After the feature is released # requires_scipy_linalg_backend = testing.with_requires('scipy>=1.x.x') requires_scipy_linalg_backend = unittest.skip( 'scipy.linalg backend feature has not been released') @testing.gpu @testing.parameterize(*testing.product({ 'shape': [(1, 1), (2, 2), (3, 3), (5, 5), (1, 5), (5, 1), (2, 5), (5, 2)], })) @testing.fix_random() @testing.with_requires('scipy') class TestLUFactor(unittest.TestCase): @testing.for_dtypes('fdFD') def test_lu_factor(self, dtype): if self.shape[0] != self.shape[1]: self.skipTest( 'skip non-square tests since scipy.lu_factor requires square') a_cpu = testing.shaped_random(self.shape, numpy, dtype=dtype) a_gpu = cupy.asarray(a_cpu) result_cpu = scipy.linalg.lu_factor(a_cpu)
class AuctionLotAwardResourceTestMixin(object): test_create_auction_award_lot = unittest.skip('option not available')( snitch(create_auction_award_lot)) test_patch_auction_award_lot = snitch(patch_auction_award_lot) test_patch_auction_award_unsuccessful_lot = snitch( patch_auction_award_unsuccessful_lot)
def needs_parasol(test_item): """Use as decorator so tests are only run if Parasol is installed.""" test_item = _mark_test('parasol', test_item) if which('parasol'): return test_item return unittest.skip("Install Parasol to include this test.")(test_item)
def wrapped(): '''create propper decorator --- either skipping one or "empty" one''' if not any(map(condition, locate_ns_item(ROLES, thing))): return unittest.skip("no suitable items found in ROLES.%s" % thing) return lambda function: function
def skipUnlessToken(): global HAS_TEST_TOKEN if not HAS_TEST_TOKEN: return unittest.skip("No auth token")