Python pytest.skip() Examples
The following are 30 code examples for showing how to use pytest.skip(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
pytest
, or try the search function
.
Example 1
Project: mmdetection Author: open-mmlab File: test_async.py License: Apache License 2.0 | 6 votes |
def test_simple_inference(self): if not torch.cuda.is_available(): import pytest pytest.skip('test requires GPU and torch+cuda') ori_grad_enabled = torch.is_grad_enabled() root_dir = os.path.dirname(os.path.dirname(__name__)) model_config = os.path.join( root_dir, 'configs/mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py') detector = MaskRCNNDetector(model_config) await detector.init() img_path = os.path.join(root_dir, 'demo/demo.jpg') bboxes, _ = await detector.apredict(img_path) self.assertTrue(bboxes) # asy inference detector will hack grad_enabled, # so restore here to avoid it to influence other tests torch.set_grad_enabled(ori_grad_enabled)
Example 2
Project: smbprotocol Author: jborean93 File: conftest.py License: MIT License | 6 votes |
def smb_real(): # for these tests to work the server at SMB_SERVER must support dialect # 3.1.1, without this some checks will fail as we test 3.1.1 specific # features username = os.environ.get('SMB_USER', None) password = os.environ.get('SMB_PASSWORD', None) server = os.environ.get('SMB_SERVER', None) port = os.environ.get('SMB_PORT', 445) share = os.environ.get('SMB_SHARE', 'share') if username and password and server: share = r"\\%s\%s" % (server, share) encrypted_share = "%s-encrypted" % share return username, password, server, int(port), share, encrypted_share else: pytest.skip("SMB_USER, SMB_PASSWORD, SMB_PORT, SMB_SHARE, " "environment variables were not set, integration tests " "will be skipped")
Example 3
Project: shopify_python Author: Shopify File: test_functional.py License: MIT License | 6 votes |
def setUp(self): if self._should_be_skipped_due_to_version(): pytest.skip('Test cannot run with Python %s.' % (sys.version.split(' ')[0],)) missing = [] for req in self._test_file.options['requires']: try: __import__(req) except ImportError: missing.append(req) if missing: pytest.skip('Requires %s to be present.' % (','.join(missing),)) if self._test_file.options['except_implementations']: implementations = [ item.strip() for item in self._test_file.options['except_implementations'].split(",") ] implementation = platform.python_implementation() if implementation in implementations: pytest.skip( 'Test cannot run with Python implementation %r' % (implementation, ))
Example 4
Project: py Author: pytest-dev File: test_svnauth.py License: MIT License | 6 votes |
def __init__(self, request): if not svnbin: py.test.skip("svn binary required") if not request.config.option.runslowtests: py.test.skip('use --runslowtests to run these tests') tmpdir = request.getfuncargvalue("tmpdir") repodir = tmpdir.join("repo") py.process.cmdexec('svnadmin create %s' % repodir) if sys.platform == 'win32': repodir = '/' + str(repodir).replace('\\', '/') self.repo = py.path.svnurl("file://%s" % repodir) if sys.platform == 'win32': # remove trailing slash... repodir = repodir[1:] self.repopath = py.path.local(repodir) self.temppath = tmpdir.mkdir("temppath") self.auth = SvnAuth('johnny', 'foo', cache_auth=False, interactive=False) make_repo_auth(self.repopath, {'johnny': ('foo', 'rw')}) self.port, self.pid = serve_bg(self.repopath.dirpath()) # XXX caching is too global py.path.svnurl._lsnorevcache._dict.clear() request.addfinalizer(lambda: py.process.kill(self.pid))
Example 5
Project: py Author: pytest-dev File: test_svnauth.py License: MIT License | 6 votes |
def test_switch(self, setup): import pytest try: import xdist pytest.skip('#160: fails under xdist') except ImportError: pass wc = py.path.svnwc(setup.temppath, auth=setup.auth) svnurl = 'svn://localhost:%s/%s' % (setup.port, setup.repopath.basename) wc.checkout(svnurl) wc.ensure('foo', dir=True).ensure('foo.txt').write('foo') wc.commit('added foo dir with foo.txt file') wc.ensure('bar', dir=True) wc.commit('added bar dir') bar = wc.join('bar') bar.switch(svnurl + '/foo') assert bar.join('foo.txt')
Example 6
Project: normandy Author: mozilla File: test_api.py License: Mozilla Public License 2.0 | 6 votes |
def test_console_log(conf, requests_session): r = requests_session.get(conf.getoption("server") + "/api/v1/action/") r.raise_for_status() response = r.json() # Verify we have at least one response and then grab the first record assert len(response) >= 1 # Look for any console-log actions cl_records = [record for record in response if record["name"] == "console-log"] if len(cl_records) == 0: pytest.skip("No console-log actions found") return record = cl_records[0] # Does an 'action' have all the required fields? expected_action_fields = ["name", "implementation_url", "arguments_schema"] for field in record: assert field in expected_action_fields check_action_schema_format(record)
Example 7
Project: normandy Author: mozilla File: test_api.py License: Mozilla Public License 2.0 | 6 votes |
def test_show_heartbeat(conf, requests_session): r = requests_session.get(conf.getoption("server") + "/api/v1/action/") r.raise_for_status() response = r.json() # Verify we have at least one response and then grab the first record assert len(response) >= 1 # Let's find at least one record that is a 'show-heartbeat' sh_records = [record for record in response if record["name"] == "show-heartbeat"] if len(sh_records) == 0: pytest.skip("No show-heartbeat actions found") return record = sh_records[0] expected_action_fields = ["name", "implementation_url", "arguments_schema"] for field in record: assert field in expected_action_fields check_action_schema_format(record)
Example 8
Project: normandy Author: mozilla File: test_api.py License: Mozilla Public License 2.0 | 6 votes |
def test_recipe_history(conf, requests_session): r = requests_session.get(conf.getoption("server") + "/api/v1/recipe/") r.raise_for_status() data = r.json() if len(data) == 0: pytest.skip("No recipes found.") for item in data: endpoint = f'/api/v1/recipe/{item["id"]}/history/' r = requests_session.get(conf.getoption("server") + endpoint) r.raise_for_status() history = r.json() last_date = datetime.now() for revision in history: created = datetime.strptime(revision["date_created"], "%Y-%m-%dT%H:%M:%S.%fZ") assert created < last_date last_date = created
Example 9
Project: normandy Author: mozilla File: test_recipe_read.py License: Mozilla Public License 2.0 | 6 votes |
def test_recipe_read(conf, requests_session): # Get random recipe and make sure it's valid response = requests_session.get(urljoin(conf.getoption("server"), "/api/v3/recipe/")) data = response.json() if len(data["results"]) == 0: pytest.skip("Could not find any recipes") element = randint(0, len(data["results"]) - 1) recipe_id = data["results"][element]["id"] response = requests_session.get( urljoin(conf.getoption("server"), "/api/v3/recipe/{}".format(recipe_id)) ) data = response.json() assert response.status_code != 404 assert_valid_schema(response.json())
Example 10
Project: snowflake-connector-python Author: snowflakedb File: test_put_get_user_stage.py License: Apache License 2.0 | 6 votes |
def test_get_data_user_stage(is_public_test, tmpdir, conn_cnx, db_parameters): """SNOW-20927: Tests Get failure with 404 error.""" if is_public_test or 'AWS_ACCESS_KEY_ID' not in os.environ: pytest.skip('This test requires to change the internal parameter') default_s3bucket = os.getenv('SF_AWS_USER_BUCKET', "sfc-dev1-regression/{}/reg".format( getuser())) test_data = [ { 's3location': '{}/{}'.format( default_s3bucket, db_parameters['name'] + '_stage'), 'stage_name': db_parameters['name'] + '_stage1', 'data_file_name': 'data.txt', }, ] for elem in test_data: _put_list_rm_files_in_stage(tmpdir, conn_cnx, db_parameters, elem)
Example 11
Project: mutatest Author: EvanKepner File: test_run.py License: MIT License | 5 votes |
def test_run_mutation_trials_good_binop( bos, bod, exp_trials, parallel, single_binop_file_with_good_test, change_to_tmp ): """Slow test to run detection trials on a simple mutation on a binop. Based on fixture, there is one Add operation, with 6 substitutions e.g. sub, div, mult, pow, mod, floordiv, therefore, 6 total trials are expected for a full run and 1 trial is expected when break on detected is used. Args: bos: break on survival bod: break on detection exp_trials: number of expected trials single_binop_file_with_good_test: fixture for single op with a good test """ if sys.version_info < (3, 8) and parallel: pytest.skip("Under version 3.8 will not run parallel tests.") test_cmds = f"pytest {single_binop_file_with_good_test.test_file.resolve()}".split() config = Config( n_locations=100, break_on_survival=bos, break_on_detected=bod, multi_processing=parallel ) results_summary = run.run_mutation_trials( single_binop_file_with_good_test.src_file.resolve(), test_cmds=test_cmds, config=config ) assert len(results_summary.results) == exp_trials # in all trials the status should be detected for mutant_trial in results_summary.results: assert mutant_trial.return_code == 1 assert mutant_trial.status == "DETECTED"
Example 12
Project: mutatest Author: EvanKepner File: test_run.py License: MIT License | 5 votes |
def test_run_mutation_trials_bad_binop( bos, bod, exp_trials, parallel, single_binop_file_with_bad_test, change_to_tmp ): """Slow test to run detection trials on a simple mutation on a binop. Based on fixture, there is one Add operation, with 6 substitutions e.g. sub, div, mult, pow, mod, floordiv, therefore, 6 total trials are expected for a full run and 1 trial is expected when break on detected is used. Args: bos: break on survival bod: break on detection exp_trials: number of expected trials single_binop_file_with_good_test: fixture for single op with a good test """ if sys.version_info < (3, 8) and parallel: pytest.skip("Under version 3.8 will not run parallel tests.") test_cmds = f"pytest {single_binop_file_with_bad_test.test_file.resolve()}".split() config = Config( n_locations=100, break_on_survival=bos, break_on_detected=bod, multi_processing=parallel ) results_summary = run.run_mutation_trials( single_binop_file_with_bad_test.src_file.resolve(), test_cmds=test_cmds, config=config ) assert len(results_summary.results) == exp_trials # in all trials the status should be survivors for mutant_trial in results_summary.results: assert mutant_trial.return_code == 0 assert mutant_trial.status == "SURVIVED"
Example 13
Project: cherrypy Author: cherrypy File: test_static.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def _check_unicode_filesystem(tmpdir): filename = tmpdir / ntou('☃', 'utf-8') tmpl = 'File system encoding ({encoding}) cannot support unicode filenames' msg = tmpl.format(encoding=sys.getfilesystemencoding()) try: io.open(str(filename), 'w').close() except UnicodeEncodeError: pytest.skip(msg)
Example 14
Project: cherrypy Author: cherrypy File: test_static.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_file_stream_deadlock(self): if cherrypy.server.protocol_version != 'HTTP/1.1': return self.skip() self.PROTOCOL = 'HTTP/1.1' # Make an initial request but abort early. self.persistent = True conn = self.HTTP_CONN conn.putrequest('GET', '/bigfile', skip_host=True) conn.putheader('Host', self.HOST) conn.endheaders() response = conn.response_class(conn.sock, method='GET') response.begin() self.assertEqual(response.status, 200) body = response.fp.read(65536) if body != b'x' * len(body): self.fail("Body != 'x' * %d. Got %r instead (%d bytes)." % (65536, body[:50], len(body))) response.close() conn.close() # Make a second request, which should fetch the whole file. self.persistent = False self.getPage('/bigfile') if self.body != b'x' * BIGFILE_SIZE: self.fail("Body != 'x' * %d. Got %r instead (%d bytes)." % (BIGFILE_SIZE, self.body[:50], len(body)))
Example 15
Project: cherrypy Author: cherrypy File: helper.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def skip(self, msg='skipped '): pytest.skip(msg)
Example 16
Project: cherrypy Author: cherrypy File: test_session.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def memcached_server_present(): is_memcached_present() or pytest.skip('memcached not available')
Example 17
Project: mmdetection Author: open-mmlab File: test_forward.py License: Apache License 2.0 | 5 votes |
def test_single_stage_forward_gpu(cfg_file): if not torch.cuda.is_available(): import pytest pytest.skip('test requires GPU and torch+cuda') model, train_cfg, test_cfg = _get_detector_cfg(cfg_file) model['pretrained'] = None from mmdet.models import build_detector detector = build_detector(model, train_cfg=train_cfg, test_cfg=test_cfg) input_shape = (2, 3, 224, 224) mm_inputs = _demo_mm_inputs(input_shape) imgs = mm_inputs.pop('imgs') img_metas = mm_inputs.pop('img_metas') detector = detector.cuda() imgs = imgs.cuda() # Test forward train gt_bboxes = [b.cuda() for b in mm_inputs['gt_bboxes']] gt_labels = [g.cuda() for g in mm_inputs['gt_labels']] losses = detector.forward( imgs, img_metas, gt_bboxes=gt_bboxes, gt_labels=gt_labels, return_loss=True) assert isinstance(losses, dict) # Test forward test with torch.no_grad(): img_list = [g[None, :] for g in imgs] batch_results = [] for one_img, one_meta in zip(img_list, img_metas): result = detector.forward([one_img], [[one_meta]], return_loss=False) batch_results.append(result)
Example 18
Project: mmdetection Author: open-mmlab File: test_heads.py License: Apache License 2.0 | 5 votes |
def _demodata_refine_boxes(n_roi, n_img, rng=0): """Create random test data for the ``mmdet.models.bbox_heads.bbox_head.BBoxHead.refine_boxes`` method.""" import numpy as np from mmdet.core.bbox.demodata import random_boxes from mmdet.core.bbox.demodata import ensure_rng try: import kwarray except ImportError: import pytest pytest.skip('kwarray is required for this test') scale = 512 rng = ensure_rng(rng) img_metas = [{'img_shape': (scale, scale)} for _ in range(n_img)] # Create rois in the expected format roi_boxes = random_boxes(n_roi, scale=scale, rng=rng) if n_img == 0: assert n_roi == 0, 'cannot have any rois if there are no images' img_ids = torch.empty((0, ), dtype=torch.long) roi_boxes = torch.empty((0, 4), dtype=torch.float32) else: img_ids = rng.randint(0, n_img, (n_roi, )) img_ids = torch.from_numpy(img_ids) rois = torch.cat([img_ids[:, None].float(), roi_boxes], dim=1) # Create other args labels = rng.randint(0, 2, (n_roi, )) labels = torch.from_numpy(labels).long() bbox_preds = random_boxes(n_roi, scale=scale, rng=rng) # For each image, pretend random positive boxes are gts is_label_pos = (labels.numpy() > 0).astype(np.int) lbl_per_img = kwarray.group_items(is_label_pos, img_ids.numpy()) pos_per_img = [sum(lbl_per_img.get(gid, [])) for gid in range(n_img)] # randomly generate with numpy then sort with torch _pos_is_gts = [ rng.randint(0, 2, (npos, )).astype(np.uint8) for npos in pos_per_img ] pos_is_gts = [ torch.from_numpy(p).sort(descending=True)[0] for p in _pos_is_gts ] return rois, labels, bbox_preds, pos_is_gts, img_metas
Example 19
Project: mmdetection Author: open-mmlab File: test_nms.py License: Apache License 2.0 | 5 votes |
def test_nms_device_and_dtypes_gpu(): """ CommandLine: xdoctest -m tests/test_nms.py test_nms_device_and_dtypes_gpu """ if not torch.cuda.is_available(): import pytest pytest.skip('test requires GPU and torch+cuda') iou_thr = 0.6 base_dets = np.array([[49.1, 32.4, 51.0, 35.9, 0.1], [49.3, 32.9, 51.0, 35.3, 0.05], [35.3, 11.5, 39.9, 14.5, 0.9], [35.2, 11.7, 39.7, 15.7, 0.3]]) base_expected_suppressed = np.array([[35.3, 11.5, 39.9, 14.5, 0.9], [49.1, 32.4, 51.0, 35.9, 0.1]]) for device_id in range(torch.cuda.device_count()): print(f'Run NMS on device_id = {device_id!r}') # GPU can handle float32 but not float64 dets = base_dets.astype(np.float32) expected_suppressed = base_expected_suppressed.astype(np.float32) suppressed, inds = nms(dets, iou_thr, device_id) assert dets.dtype == suppressed.dtype assert np.array_equal(suppressed, expected_suppressed) dets = torch.FloatTensor(base_dets).to(device_id) expected_suppressed = torch.FloatTensor(base_expected_suppressed).to( device_id) suppressed, inds = nms(dets, iou_thr) assert dets.dtype == suppressed.dtype assert torch.equal(suppressed, expected_suppressed)
Example 20
Project: suffix-trees Author: ptrus File: test_vectors.py License: MIT License | 5 votes |
def test_vectors(): if not os.getenv("SUFFIX_TREES_TEST_VECTORS") == "1": pytest.skip("skipping vectors test. Set SUFFIX_TREES_TEST_VECTORS=1 to run.") with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), INPUT), 'r') as f: for line in f: splitted = line.split(",") search_string = splitted[0] # Build tree on the search string. st = STree.STree(search_string) # Test cases for case in splitted[1:-1]: [s, res] = case.split(":") assert int(res) == st.find(s), "Search string: {}, Test case: {}, Expected: {}".format( search_string, s, int(res))
Example 21
Project: django-payfast Author: PiDelport File: test_integration_sandbox.py License: MIT License | 5 votes |
def require_itn_configured(): # type: () -> None """ pytest.skip() if not itn_configured. """ if not itn_configured: pytest.skip(ITN_HELP_MESSAGE)
Example 22
Project: stft Author: nils-werner File: test_utils.py License: MIT License | 5 votes |
def test_padding(signal, framelength): if signal.ndim == 2: pytest.skip("not testing 3D data here") tmp = pad(signal, framelength) out = unpad(tmp, len(signal)) assert out.shape == signal.shape
Example 23
Project: hiku Author: vmagamedov File: test_read_graphql.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_skip_field(skip): check_read( """ query Page($cond: Boolean!) { foo bar @skip(if: $cond) } """, Node([Field('foo')] + ([] if skip else [Field('bar')])), {'cond': skip}, )
Example 24
Project: hiku Author: vmagamedov File: test_read_graphql.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_skip_fragment_spread(skip): check_read( """ query Page($cond: Boolean!) { foo ...Fragment @skip(if: $cond) } fragment Fragment on Thing { bar } """, Node([Field('foo')] + ([] if skip else [Field('bar')])), {'cond': skip}, )
Example 25
Project: hiku Author: vmagamedov File: test_read_graphql.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_skip_inline_fragment(skip): check_read( """ query Page($cond: Boolean!) { foo ... on Thing @skip(if: $cond) { bar } } """, Node([Field('foo')] + ([] if skip else [Field('bar')])), {'cond': skip}, )
Example 26
Project: hiku Author: vmagamedov File: test_introspection_graphql.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def _schema(types, with_mutation=False): names = [t['name'] for t in types] assert 'Query' in names, names return { '__schema': { 'directives': [ _directive('skip'), _directive('include'), ], 'mutationType': {'name': 'Mutation'} if with_mutation else None, 'queryType': {'name': 'Query'}, 'types': SCALARS + types, } }
Example 27
Project: pwnypack Author: edibledinos File: test_asm.py License: MIT License | 5 votes |
def test_asm(test_target, syntax, source, result, target): try: output = pwny.asm(source, syntax=syntax, target=test_target) except RuntimeError: # Toolchain wasn't found. Unfortunate, but unavoidable on travis-ci atm. pytest.skip('No suitable binutils was found for %s' % target) assert output == result, 'Got %r, expected %r' % (output, result)
Example 28
Project: tangent Author: google File: test_hessian_vector_products.py License: Apache License 2.0 | 5 votes |
def tf(): try: import tensorflow as tf except ImportError: pytest.skip() # This test function broke HVPs several times # during development, so we're using it as a unit test.
Example 29
Project: custodia Author: latchset File: conftest.py License: GNU General Public License v3.0 | 5 votes |
def pytest_runtest_setup(item): skip_servertest = item.config.getoption(SKIP_SERVERTEST) skiptest = False if skip_servertest: # pytest < 4 if hasattr(item, 'get_marker'): if item.get_marker("servertest"): skiptest = True # pytest >= 4 elif item.get_closest_marker("servertest"): skiptest = True if skiptest: # args has --skip-servertests and test is marked as servertest pytest.skip("Skip integration test")
Example 30
Project: py-solc Author: ethereum File: conftest.py License: MIT License | 5 votes |
def pytest_runtest_setup(item): if (item.get_marker('requires_standard_json') is not None and not solc_supports_standard_json_interface()): pytest.skip('requires `--standard-json` support')