Here are the examples of the python api pytest.skip taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
177 Examples
5
Example 1
Project: sqlobject Source File: test_sqlite.py
def test_memorydb():
if not supports("memorydb"):
pytest.skip("memorydb isn't supported")
connection = getConnection()
if connection.dbName != "sqlite":
pytest.skip("These tests require SQLite")
if not connection._memory:
pytest.skip("The connection isn't memorydb")
setupClass(SOTestSO1)
connection.close() # create a new connection to an in-memory database
SOTestSO1.setConnection(connection)
SOTestSO1.createTable()
5
Example 2
def pytest_runtest_setup(item):
if 'unimplemented' in item.keywords: #and not item.config.getoption("--runslow"):
pytest.skip('unimplemented functionality')
if 'unfinished' in item.keywords:
pytest.skip('unfinished functionality')
try:
runslow = item.config.getoption("--runslow")
except ValueError:
runslow = False
if 'slow' in item.keywords and not runslow:
pytest.skip("need --runslow option to run")
logging.basicConfig(level=logging.DEBUG)
5
Example 3
def pytest_runtest_setup(item):
if 'meta' in item.keywords and item.config.getoption('--skip-meta'):
pytest.skip('skipping meta test (--skip-meta given)')
if 'slow' in item.keywords and item.config.getoption('--skip-slow'):
pytest.skip('skipping slow test (--skip-slow given)')
if 'real' in item.keywords:
if item.config.getoption('--skip-real'):
pytest.skip('skipping real life test (--skip-real given)')
if (not os.getenv('PYDLE_TESTS_REAL_HOST') or
not os.getenv('PYDLE_TESTS_REAL_PORT')):
pytest.skip('skipping real life test (no real server given)')
5
Example 4
def pytest_runtest_setup(item):
if 'filter' not in item.keywords and item.config.getoption("--filter"):
pytest.skip("only running tests with 'filter' mark")
if 'slow' in item.keywords and not item.config.getoption("--slow"):
pytest.skip("need --slow option to run")
if 'veryslow' in item.keywords and not item.config.getoption("--veryslow"):
pytest.skip("need --veryslow option to run")
5
Example 5
def pytest_runtest_setup(item):
abinit_marker = item.get_marker("abinit")
vasp_marker = item.get_marker("vasp")
qe_marker = item.get_marker("qe")
if abinit_marker is not None:
if not item.config.getoption("-A"):
pytest.skip("test runs only with ABINIT")
if vasp_marker is not None:
if not item.config.getoption("-V"):
pytest.skip("test runs only with VASP")
if qe_marker is not None:
if not item.config.getoption("-Q"):
pytest.skip("test runs only with Quantum ESPRESSO")
5
Example 6
Project: pydpiper Source File: test_pbs_queueing.py
def test_create_job_multiproc(self, setupopts):
"""This test requires specifying --proc=24 on command line
Verifies defaults and file creation when multiple nodes are needed"""
allOptions = setupopts.returnAllOptions()
roq = runOnQueueingSystem(allOptions)
if roq.queue is None:
pytest.skip("specify --queue=pbs to continue with this test")
if roq.ppn != 8:
pytest.skip("specify --ppn=8 to continue with this test")
if roq.numexec != 1:
pytest.skip("specify --num-executors=1 to continue with this test")
if roq.proc != 24:
pytest.skip("specify --proc==24 to continue with this test")
roq.createPbsScripts()
correctNodesPpn = False
jobFileString = open(roq.jobFileName).read()
if "nodes=3:ppn=8" in jobFileString:
correctNodesPpn = True
assert correctNodesPpn == True
3
Example 7
Project: sqlobject Source File: test_SQLMultipleJoin.py
def test_multiple_join_transaction():
if not supports('transactions'):
pytest.skip("Transactions aren't supported")
createAllTables()
trans = Race._connection.transaction()
try:
namek = Race(name='namekuseijin', connection=trans)
RFighter(name='Gokou (Kakaruto)', race=namek, power=10,
connection=trans)
assert namek.fightersAsSResult.count() == 1
assert namek.fightersAsSResult[0]._connection == trans
finally:
trans.commit(True)
Race._connection.autoCommit = True
3
Example 8
Project: pyudev Source File: test_pypi.py
def _get_required_files():
if not os.path.isdir(os.path.join(SOURCE_DIRECTORY, '.git')):
pytest.skip('Not in git clone')
git = py.path.local.sysfind('git')
if not git:
pytest.skip('git not available')
ls_files = subprocess.Popen(['git', 'ls-files'], cwd=SOURCE_DIRECTORY,
stdout=subprocess.PIPE)
output = ls_files.communicate()[0].decode('utf-8')
for filename in output.splitlines():
if not any(re.search(p, filename) for p in REQUIRED_BLACKLIST):
yield filename
3
Example 9
def test_iter_lines_timeout(self):
with self._connect() as rem:
try:
for i, (out, err) in enumerate(rem["ping"]["-i", 0.5, "127.0.0.1"].popen().iter_lines(timeout=2)):
print("out:", out)
print("err:", err)
except NotImplementedError:
try:
pytest.skip(sys.exc_info()[1])
except AttributeError:
return
except ProcessTimedOut:
assert i > 3
else:
pytest.fail("Expected a timeout")
3
Example 10
Project: wal-e Source File: test_cmdline_version.py
def test_version_print():
# Load up the contents of the VERSION file out-of-band
from wal_e import cmd
place = path.join(path.dirname(cmd.__file__), 'VERSION')
with open(place, 'rb') as f:
expected = f.read()
# Try loading it via command line invocation
try:
proc = subprocess.Popen(['wal-e', 'version'], stdout=subprocess.PIPE)
except EnvironmentError as e:
if e.errno == errno.ENOENT:
pytest.skip('wal-e must be in $PATH to test version output')
result = proc.communicate()[0]
# Make sure the two versions match and the command exits
# successfully.
assert proc.returncode == 0
assert result == expected
3
Example 11
def test_date(self):
if get_sql_server_version(self.conn) < 2008:
pytest.skip("DATE field type isn't supported by SQL Server versions prior to 2008.")
if self.conn.tds_version < 7.3:
pytest.skip("DATE field type isn't supported by TDS protocol older than 7.3.")
testval = date(2013, 1, 2)
colval = self.insert_and_select('stamp_date', testval, 's')
typeeq(testval, colval)
eq_(testval, colval)
3
Example 12
def setup_method(self, method):
skip_without_rsync()
basedir_old = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', 's3ql.old'))
if not os.path.exists(os.path.join(basedir_old, 'bin', 'mkfs.s3ql')):
pytest.skip('no previous S3QL version found')
super().setup_method(method)
self.ref_dir = tempfile.mkdtemp(prefix='s3ql-ref-')
self.bak_dir = tempfile.mkdtemp(prefix='s3ql-bak-')
self.basedir_old = basedir_old
3
Example 13
Project: patool Source File: __init__.py
def needs_codec (program, codec):
"""Decorator skipping test if given program codec is not available."""
def check_prog (f):
def newfunc (*args, **kwargs):
if not patoolib.util.find_program(program):
raise pytest.skip("program `%s' not available" % program)
if not has_codec(program, codec):
raise pytest.skip("codec `%s' for program `%s' not available" % (codec, program))
return f(*args, **kwargs)
setattr(newfunc, fnameattr, getattr(f, fnameattr))
return newfunc
return check_prog
3
Example 14
def test_delete_share(self, smart_setup):
smart = smart_setup['smart']
try:
action = smart.Reports.delete_share(
TestReports.reports[0].id,
TestReports.share.id,
)
assert action.message == 'SUCCESS'
except IndexError:
pytest.skip('no reports found in test account')
3
Example 15
def test_speed(browser, splinter_webdriver):
"""Test browser's driver set_speed and get_speed."""
if splinter_webdriver == "zope.testbrowser":
pytest.skip("zope testbrowser doesn't need the speed")
browser.driver.set_speed(2)
assert browser.driver.get_speed() == 2
3
Example 16
Project: qutebrowser Source File: test_qtutils.py
def test_seek_unsupported(self, pyqiodev):
"""Test seeking with unsupported whence arguments."""
# pylint: disable=no-member,useless-suppression
if hasattr(os, 'SEEK_HOLE'):
whence = os.SEEK_HOLE
elif hasattr(os, 'SEEK_DATA'):
whence = os.SEEK_DATA
else:
pytest.skip("Needs os.SEEK_HOLE or os.SEEK_DATA available.")
pyqiodev.open(QIODevice.ReadOnly)
with pytest.raises(io.UnsupportedOperation):
pyqiodev.seek(0, whence)
3
Example 17
def testDefault(self, capsys, depfile):
if depfile.whichdb in ('dbm', 'dbm.ndbm'): # pragma: no cover
pytest.skip('%s not supported for this operation' % depfile.whichdb)
# cmd_main(["help", "task"])
depfile._set('tid', 'my_dep', 'xxx')
depfile.close()
cmd_dump = DumpDB()
cmd_dump.execute({'dep_file': depfile.name}, [])
out, err = capsys.readouterr()
assert 'tid' in out
assert 'my_dep' in out
assert 'xxx' in out
3
Example 18
Project: tchannel-python Source File: util.py
@contextmanager
def get_thrift_service_module(root, tornado=False):
if not thrift:
pytest.skip('Thrift is not installed.')
thrift_file = get_thrift_file(root)
with root.as_cwd():
options = 'py:new_style,utf8strings,dynamic'
if tornado:
options += ',tornado'
thrift('-out', '.', '--gen', options, str(thrift_file))
yield root.join('service', 'Service.py').pyimport()
3
Example 19
Project: pymetabiosis Source File: test_numpy_convert.py
def test_scalar_converter():
try:
numpy = import_module("numpy")
except ImportError:
pytest.skip("numpy isn't installed on the cpython side")
assert numpy.bool_(True) is True
assert numpy.bool_(False) is False
assert numpy.int8(10) == 10
assert numpy.int16(-10) == -10
assert numpy.int32(int(2**31-1)).__int__() == int(2**31-1)
assert numpy.int64(42) == 42
assert numpy.float16(10.0) == 10.0
assert numpy.float32(-10) == -10.0
assert numpy.float64(42.0) == 42.0
if hasattr(numpy, "float128"):
assert numpy.float128(-42.0) == -42.0
3
Example 20
Project: dosage Source File: __init__.py
def _need_func(testfunc, name, description):
"""Decorator skipping test if given testfunc returns False."""
def check_func(func):
def newfunc(*args, **kwargs):
if not testfunc(name):
raise pytest.skip("%s %r is not available" % (description, name))
return func(*args, **kwargs)
setattr(newfunc, fnameattr, getattr(func, fnameattr))
return newfunc
return check_func
3
Example 21
def test_package(package_data):
assert package_data['url'].endswith(".tar.gz")
r = requests.head(package_data['url'], allow_redirects=True)
validate_response(r)
if "X-Checksum-Sha1" not in r.headers:
return pytest.skip("X-Checksum-Sha1 is not provided")
assert package_data['sha1'] == r.headers.get("X-Checksum-Sha1")
3
Example 22
Project: s3ql Source File: t6_upgrade.py
def setup_method(self, method, name):
super().setup_method(method)
try:
(backend_login, backend_pw,
self.storage_url) = get_remote_test_info(name)
except NoTestSection as exc:
pytest.skip(exc.reason)
self.backend_login = backend_login
self.backend_passphrase = backend_pw
3
Example 23
def setup_module(module):
packages = 'stevedore', 'virtualenvwrapper', 'pbr', 'novaclient'
for pkg in packages:
try:
__import__(pkg)
tmpl = "Integration tests cannot run when {pkg} is installed"
pytest.skip(tmpl.format(**locals()))
except ImportError:
pass
try:
urllib.request.urlopen('https://pypi.python.org/pypi')
except Exception as exc:
pytest.skip(str(exc))
3
Example 24
Project: PyHDB Source File: test_lob.py
def test_nclob___unicode___method_for_nonascii_chars():
"""Test that the magic __unicode__ method returns a proper text_type"""
if not PY2:
pytest.skip('test only makes sense in PY2')
data = u'朱の子ましけ'
nclob = lobs.NClob(data)
uni_nclob = unicode(nclob)
assert type(uni_nclob) == text_type
assert uni_nclob == data
3
Example 25
Project: PyHDB Source File: test_lob.py
def test_read_lob__str__method_python2():
"""Read/parse a LOB with given payload (data) and check ___str__ method"""
if PY3:
pytest.skip("See test_read_lob__str__method_python3")
payload = io.BytesIO(BLOB_HEADER + BLOB_DATA)
lob = lobs.from_payload(type_codes.BLOB, payload, None)
len = lob._lob_header.byte_length
assert str(lob._lob_header) == "<ReadLobHeader type: 1, options 2 (data_included), charlength: %d, bytelength: " \
"%d, locator_id: '\\x00\\x00\\x00\\x00\\xb2\\xb9\\x04\\x00', chunklength: 1024>" % \
(len, len)
3
Example 26
Project: cryptography Source File: test_x963_vectors.py
def _skip_hashfn_unsupported(backend, hashfn):
if not backend.hash_supported(hashfn):
pytest.skip(
"Hash {0} is not supported by this backend {1}".format(
hashfn.name, backend
)
)
3
Example 27
Project: pytest Source File: doctest.py
def _check_all_skipped(test):
"""raises pytest.skip() if all examples in the given DocTest have the SKIP
option set.
"""
import doctest
all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples)
if all_skipped:
pytest.skip('all tests skipped by +SKIP option')
3
Example 28
Project: PySCIPOpt Source File: test_heur.py
def test_heur_memory():
if is_optimized_mode():
pytest.skip()
def inner():
s = Model()
heuristic = MyHeur()
s.includeHeur(heuristic, "PyHeur", "custom heuristic implemented in python", "Y", timingmask=SCIP_HEURTIMING.BEFORENODE)
return weakref.proxy(heuristic)
heur_prox = inner()
gc.collect() # necessary?
with pytest.raises(ReferenceError):
heur_prox.name
assert is_memory_freed()
3
Example 29
Project: pytest-qt Source File: test_wait_signal.py
def test_degenerate_error_msg(self, qtbot, signaller):
"""
Tests that the TimeoutError message is degenerate when using PySide signals for which no name is provided
by the user. This degenerate messages doesn't contain the signals' names, and includes a hint to the user how
to fix the situation.
"""
if qt_api.pytest_qt_api != 'pyside':
pytest.skip("test only makes sense for PySide, whose signals don't contain a name!")
with pytest.raises(TimeoutError) as excinfo:
with qtbot.waitSignals(signals=[signaller.signal, signaller.signal_args, signaller.signal_args],
timeout=200, check_params_cbs=None, order="none",
raising=True):
signaller.signal.emit()
ex_msg = TestWaitSignalsTimeoutErrorMessage.get_exception_message(excinfo)
assert ex_msg == ("Received 1 of the 3 expected signals. "
"To improve this error message, provide the names of the signals "
"in the waitSignals() call.")
3
Example 30
def test_f(self, capfd, racket_file):
"""(display "42")"""
pytest.skip("re-enable when -f works again")
assert entry_point(['arg0', '-f', racket_file]) == 0
out, err = capfd.readouterr()
assert out == "42"
3
Example 31
Project: qutebrowser Source File: test_invocations.py
def test_no_loglines(request, quteproc_new):
"""Test qute:log with --loglines=0."""
if request.config.webengine:
pytest.skip("qute:log is not implemented with QtWebEngine yet")
quteproc_new.start(args=['--temp-basedir', '--loglines=0'] +
_base_args(request.config))
quteproc_new.open_path('qute:log')
assert quteproc_new.get_content() == 'Log output was disabled.'
3
Example 32
def pytest_runtest_setup(item):
if not hasattr(item, 'obj'):
return
marker = getattr(item.obj, 'not_on_travis', None)
if marker and is_on_travis_ci():
pytest.skip('Test must not run on Travis CI')
3
Example 33
def setup(self):
if hasattr(self.config, "_flake8mtimes"):
flake8mtimes = self.config._flake8mtimes
else:
flake8mtimes = {}
self._flake8mtime = self.fspath.mtime()
old = flake8mtimes.get(str(self.fspath), (0, []))
if old == [self._flake8mtime, self.flake8ignore]:
pytest.skip("file(s) previously passed FLAKE8 checks")
3
Example 34
Project: web3.py Source File: test_admin_setSolc.py
def test_admin_setSolc(web3, skip_if_testrpc):
skip_if_testrpc(web3)
try:
solc_path = subprocess.check_output(['which', 'solc']).strip()
except subprocess.CalledProcessError:
pytest.skip('solc binary not found')
solc_version = subprocess.check_output(['solc', '--version']).strip()
actual = web3.admin.setSolc(solc_path)
assert force_text(solc_version) in actual
assert force_text(solc_path) in actual
3
Example 35
Project: abjad Source File: test_sequencetools_rotate_sequence.py
def test_sequencetools_rotate_sequence_04():
r'''Rotates named pitch segment.
'''
pytest.skip('FIXME')
named_pitch_segment_1 = pitchtools.PitchSegment("c'' d'' e'' f''")
named_pitch_segment_2 = sequencetools.rotate_sequence(named_pitch_segment_1, -1)
named_pitch_segment_3 = pitchtools.PitchSegment("d'' e'' f'' c''")
assert named_pitch_segment_2 == named_pitch_segment_3
assert isinstance(named_pitch_segment_1, pitchtools.PitchSegment)
assert isinstance(named_pitch_segment_2, pitchtools.PitchSegment)
assert isinstance(named_pitch_segment_3, pitchtools.PitchSegment)
3
Example 36
Project: ricloud Source File: test_api.py
@toggle_responses
def test_2fa_required(self):
"""What happens when 2FA is enabled?"""
register_2fa_responses()
api = ICloudApi(user=settings.get('test', 'user'), key=settings.get('test', 'key'))
try:
api.login(apple_id=settings.get('test', 'apple_id'), password=settings.get('test', 'password'))
raise pytest.skip('2FA is not enabled for this account.')
except TwoFactorAuthenticationRequired:
pass
# The trusted devices fields should now be populated
assert len(api.trusted_devices) > 0
3
Example 37
def setup(self):
if not getattr(self.config, 'cache', None):
return False
self.cache = True
self._pylamamtimes = self.fspath.mtime()
pylamamtimes = self.config._pylamamtimes
old = pylamamtimes.get(str(self.fspath), 0)
if old == self._pylamamtimes:
pytest.skip("file(s) previously passed Pylama checks")
3
Example 38
Project: doit Source File: test_dependency.py
def test_corrupted_file_unrecognized_excep(self, monkeypatch, pdepfile):
if pdepfile.db_class is not DbmDB:
pytest.skip('test doesnt apply to non DBM DB')
if pdepfile.whichdb is None: # pragma: no cover
pytest.skip('dumbdbm too dumb to detect db corruption')
# create some corrupted files
for name_ext in pdepfile.name_ext:
full_name = pdepfile.name + name_ext
fd = open(full_name, 'w')
fd.write("""{"x": y}""")
fd.close()
monkeypatch.setattr(DbmDB, 'DBM_CONTENT_ERROR_MSG', 'xxx')
pytest.raises(DatabaseException, Dependency,
pdepfile.db_class, pdepfile.name)
3
Example 39
Project: PySCIPOpt Source File: test_memory.py
def test_freed():
if is_optimized_mode():
pytest.skip()
m = Model()
del m
assert is_memory_freed()
3
Example 40
Project: python-gpiozero Source File: test_real_pins.py
def test_duty_cycles(pins):
test_pin, input_pin = pins
if test_pin.__class__.__name__ == 'NativePin':
pytest.skip("native pin doesn't support PWM")
test_pin.function = 'output'
test_pin.frequency = 100
for duty_cycle in (0.0, 0.1, 0.5, 1.0):
test_pin.state = duty_cycle
assert test_pin.state == duty_cycle
total = sum(input_pin.state for i in range(20000))
assert isclose(total / 20000, duty_cycle, rel_tol=0.1, abs_tol=0.1)
3
Example 41
def limit_time (seconds, skip=False):
"""Limit test time to the given number of seconds, else fail or skip."""
def run_limited (func):
def new_func (*args, **kwargs):
try:
with _limit_time(seconds):
return func(*args, **kwargs)
except LinkCheckerInterrupt as msg:
if skip:
pytest.skip("time limit of %d seconds exceeded" % seconds)
assert False, msg
new_func.func_name = func.func_name
return new_func
return run_limited
3
Example 42
Project: python-rasterstats Source File: test_zonal.py
def test_geodataframe_zonal():
polygons = os.path.join(DATA, 'polygons.shp')
try:
import geopandas as gpd
df = gpd.read_file(polygons)
if not hasattr(df, '__geo_interface__'):
pytest.skip("This version of geopandas doesn't support df.__geo_interface__")
except ImportError:
pytest.skip("Can't import geopands")
expected = zonal_stats(polygons, raster)
assert zonal_stats(df, raster) == expected
3
Example 43
Project: pytest-django Source File: test_database.py
def test_mydb(self, mydb):
if not connections_support_transactions():
pytest.skip('transactions required for this test')
# Check the fixture had access to the db
item = Item.objects.get(name='spam')
assert item
3
Example 44
def setUp(self):
if self.use_gzip:
try:
from twisted.web.server import GzipEncoderFactory
except ImportError:
pytest.skip("Gzip support is not available in old Twisted")
3
Example 45
Project: PGPy Source File: test_05_actions.py
def test_encrypt_message(self, pub, message, sessionkey):
if pub.key_algorithm not in {PubKeyAlgorithm.RSAEncryptOrSign, PubKeyAlgorithm.ECDSA}:
pytest.skip('Asymmetric encryption only implemented for RSA/ECDSA currently')
return
if len(self.encmessage) == 1:
message = self.encmessage.pop(0)
with self.assert_warnings():
enc = pub.encrypt(message, sessionkey=sessionkey, cipher=SymmetricKeyAlgorithm.AES128)
self.encmessage.append(enc)
3
Example 46
Project: python-rasterstats Source File: test_io.py
def test_geodataframe():
try:
import geopandas as gpd
df = gpd.read_file(polygons)
if not hasattr(df, '__geo_interface__'):
pytest.skip("This version of geopandas doesn't support df.__geo_interface__")
except ImportError:
pytest.skip("Can't import geopands")
assert list(read_features(df))
3
Example 47
Project: vdirsyncer Source File: __init__.py
def test_case_sensitive_uids(self, s, get_item):
if s.storage_name == 'filesystem':
pytest.skip('Behavior depends on the filesystem.')
s.upload(get_item(uid='A' * 42))
s.upload(get_item(uid='a' * 42))
items = list(href for href, etag in s.list())
assert len(items) == 2
assert len(set(items)) == 2
3
Example 48
def test_f(self, empty_json):
pytest.skip("re-enable when -f works again")
argv = ['arg0', "-f", empty_json]
config, names, args, retval = parse_args(argv)
assert retval == 0
assert names['file'] == empty_json+".f"
assert config['mode'] == option_helper._eval
assert names['exprs'] == '(load "%s")' % empty_json
assert args == []
3
Example 49
def test_destroyed(qtbot):
"""Test that waitSignal works with the destroyed signal (#82).
For some reason, this crashes PySide although it seems perfectly fine code.
"""
if qt_api.pytest_qt_api == 'pyside':
pytest.skip('test crashes PySide')
import sip
class Obj(qt_api.QtCore.QObject):
pass
obj = Obj()
with qtbot.waitSignal(obj.destroyed):
obj.deleteLater()
assert sip.isdeleted(obj)
3
Example 50
Project: PGPy Source File: test_05_actions.py
def test_decrypt_encmessage(self, sec, message):
if sec.key_algorithm not in {PubKeyAlgorithm.RSAEncryptOrSign, PubKeyAlgorithm.ECDSA}:
pytest.skip('Asymmetric encryption only implemented for RSA and ECDH currently')
return
encmessage = self.encmessage[0]
with self.assert_warnings():
decmsg = sec.decrypt(encmessage)
assert decmsg.message == message.message