Python pytest.importorskip() Examples
The following are 30 code examples for showing how to use pytest.importorskip(). 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: qutebrowser Author: qutebrowser File: fixtures.py License: GNU General Public License v3.0 | 6 votes |
def webpage(qnam): """Get a new QWebPage object.""" QtWebKitWidgets = pytest.importorskip('PyQt5.QtWebKitWidgets') class WebPageStub(QtWebKitWidgets.QWebPage): """QWebPage with default error pages disabled.""" def supportsExtension(self, _ext): """No extensions needed.""" return False page = WebPageStub() page.networkAccessManager().deleteLater() page.setNetworkAccessManager(qnam) from qutebrowser.browser.webkit import webkitsettings webkitsettings._init_user_agent() return page
Example 2
Project: recruit Author: Frank-qlu File: test_converter.py License: Apache License 2.0 | 6 votes |
def test_option_no_warning(self): pytest.importorskip("matplotlib.pyplot") ctx = cf.option_context("plotting.matplotlib.register_converters", False) plt = pytest.importorskip("matplotlib.pyplot") s = Series(range(12), index=date_range('2017', periods=12)) _, ax = plt.subplots() converter._WARN = True # Test without registering first, no warning with ctx: with tm.assert_produces_warning(None) as w: ax.plot(s.index, s.values) assert len(w) == 0 # Now test with registering converter._WARN = True register_matplotlib_converters() with ctx: with tm.assert_produces_warning(None) as w: ax.plot(s.index, s.values) assert len(w) == 0
Example 3
Project: recruit Author: Frank-qlu File: test_rank.py License: Apache License 2.0 | 6 votes |
def test_rank_methods_series(self): pytest.importorskip('scipy.stats.special') rankdata = pytest.importorskip('scipy.stats.rankdata') import scipy xs = np.random.randn(9) xs = np.concatenate([xs[i:] for i in range(0, 9, 2)]) # add duplicates np.random.shuffle(xs) index = [chr(ord('a') + i) for i in range(len(xs))] for vals in [xs, xs + 1e6, xs * 1e-6]: ts = Series(vals, index=index) for m in ['average', 'min', 'max', 'first', 'dense']: result = ts.rank(method=m) sprank = rankdata(vals, m if m != 'first' else 'ordinal') expected = Series(sprank, index=index) if LooseVersion(scipy.__version__) >= LooseVersion('0.17.0'): expected = expected.astype('float64') tm.assert_series_equal(result, expected)
Example 4
Project: recruit Author: Frank-qlu File: test_rank.py License: Apache License 2.0 | 6 votes |
def test_rank_methods_frame(self): pytest.importorskip('scipy.stats.special') rankdata = pytest.importorskip('scipy.stats.rankdata') import scipy xs = np.random.randint(0, 21, (100, 26)) xs = (xs - 10.0) / 10.0 cols = [chr(ord('z') - i) for i in range(xs.shape[1])] for vals in [xs, xs + 1e6, xs * 1e-6]: df = DataFrame(vals, columns=cols) for ax in [0, 1]: for m in ['average', 'min', 'max', 'first', 'dense']: result = df.rank(axis=ax, method=m) sprank = np.apply_along_axis( rankdata, ax, vals, m if m != 'first' else 'ordinal') sprank = sprank.astype(np.float64) expected = DataFrame(sprank, columns=cols) if (LooseVersion(scipy.__version__) >= LooseVersion('0.17.0')): expected = expected.astype('float64') tm.assert_frame_equal(result, expected)
Example 5
Project: recruit Author: Frank-qlu File: test_network.py License: Apache License 2.0 | 6 votes |
def test_parse_public_s3_bucket(self, tips_df): pytest.importorskip('s3fs') # more of an integration test due to the not-public contents portion # can probably mock this though. for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]: df = read_csv('s3://pandas-test/tips.csv' + ext, compression=comp) assert isinstance(df, DataFrame) assert not df.empty tm.assert_frame_equal(df, tips_df) # Read public file from bucket with not-public contents df = read_csv('s3://cant_get_it/tips.csv') assert isinstance(df, DataFrame) assert not df.empty tm.assert_frame_equal(df, tips_df)
Example 6
Project: recruit Author: Frank-qlu File: test_python_parser_only.py License: Apache License 2.0 | 6 votes |
def test_decompression_regex_sep(python_parser_only, csv1, compression, klass): # see gh-6607 parser = python_parser_only with open(csv1, "rb") as f: data = f.read() data = data.replace(b",", b"::") expected = parser.read_csv(csv1) module = pytest.importorskip(compression) klass = getattr(module, klass) with tm.ensure_clean() as path: tmp = klass(path, mode="wb") tmp.write(data) tmp.close() result = parser.read_csv(path, sep="::", compression=compression) tm.assert_frame_equal(result, expected)
Example 7
Project: recruit Author: Frank-qlu File: test_common.py License: Apache License 2.0 | 6 votes |
def test_read_expands_user_home_dir(self, reader, module, error_class, fn_ext, monkeypatch): pytest.importorskip(module) path = os.path.join('~', 'does_not_exist.' + fn_ext) monkeypatch.setattr(icom, '_expand_user', lambda x: os.path.join('foo', x)) msg1 = (r"File (b')?.+does_not_exist\.{}'? does not exist" .format(fn_ext)) msg2 = (r"\[Errno 2\] No such file or directory:" r" '.+does_not_exist\.{}'").format(fn_ext) msg3 = "Unexpected character found when decoding 'false'" msg4 = "path_or_buf needs to be a string file path or file-like" msg5 = (r"\[Errno 2\] File .+does_not_exist\.{} does not exist:" r" '.+does_not_exist\.{}'").format(fn_ext, fn_ext) with pytest.raises(error_class, match=r"({}|{}|{}|{}|{})".format( msg1, msg2, msg3, msg4, msg5)): reader(path)
Example 8
Project: recruit Author: Frank-qlu File: test_common.py License: Apache License 2.0 | 6 votes |
def test_write_fspath_hdf5(self): # Same test as write_fspath_all, except HDF5 files aren't # necessarily byte-for-byte identical for a given dataframe, so we'll # have to read and compare equality pytest.importorskip('tables') df = pd.DataFrame({"A": [1, 2]}) p1 = tm.ensure_clean('string') p2 = tm.ensure_clean('fspath') with p1 as string, p2 as fspath: mypath = CustomFSPath(fspath) df.to_hdf(mypath, key='bar') df.to_hdf(string, key='bar') result = pd.read_hdf(fspath, key='bar') expected = pd.read_hdf(string, key='bar') tm.assert_frame_equal(result, expected)
Example 9
Project: pygbm Author: ogrisel File: test_plotting.py License: MIT License | 6 votes |
def test_plot_estimator_and_lightgbm(tmpdir): pytest.importorskip('graphviz') lightgbm = pytest.importorskip('lightgbm') from pygbm.plotting import plot_tree n_classes = 3 X, y = make_classification(n_samples=150, n_classes=n_classes, n_features=5, n_informative=3, n_redundant=0, random_state=0) n_trees = 3 est_pygbm = GradientBoostingClassifier(max_iter=n_trees, n_iter_no_change=None) est_pygbm.fit(X, y) est_lightgbm = lightgbm.LGBMClassifier(n_estimators=n_trees) est_lightgbm.fit(X, y) n_total_trees = n_trees * n_classes for i in range(n_total_trees): filename = tmpdir.join('plot_mixed_predictors.pdf') plot_tree(est_pygbm, est_lightgbm=est_lightgbm, tree_index=i, view=False, filename=filename) assert filename.exists()
Example 10
Project: filesystem_spec Author: intake File: conftest.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def ftp_writable(tmpdir): """ Fixture providing a writable FTP filesystem. """ pytest.importorskip("pyftpdlib") from fsspec.implementations.ftp import FTPFileSystem FTPFileSystem.clear_instance_cache() # remove lingering connections CachingFileSystem.clear_instance_cache() d = str(tmpdir) with open(os.path.join(d, "out"), "wb") as f: f.write(b"hello" * 10000) P = subprocess.Popen( [sys.executable, "-m", "pyftpdlib", "-d", d, "-u", "user", "-P", "pass", "-w"] ) try: time.sleep(1) yield "localhost", 2121, "user", "pass" finally: P.terminate() P.wait() try: shutil.rmtree(tmpdir) except Exception: pass
Example 11
Project: python-netsurv Author: sofia-netsurv File: pytester.py License: MIT License | 6 votes |
def spawn(self, cmd, expect_timeout=10.0): """Run a command using pexpect. The pexpect child is returned. """ pexpect = pytest.importorskip("pexpect", "3.0") if hasattr(sys, "pypy_version_info") and "64" in platform.machine(): pytest.skip("pypy-64 bit not supported") if sys.platform.startswith("freebsd"): pytest.xfail("pexpect does not work reliably on freebsd") logfile = self.tmpdir.join("spawn.out").open("wb") # Do not load user config. env = os.environ.copy() env.update(self._env_run_update) child = pexpect.spawn(cmd, logfile=logfile, env=env) self.request.addfinalizer(logfile.close) child.timeout = expect_timeout return child
Example 12
Project: python-netsurv Author: sofia-netsurv File: pytester.py License: MIT License | 6 votes |
def spawn(self, cmd, expect_timeout=10.0): """Run a command using pexpect. The pexpect child is returned. """ pexpect = pytest.importorskip("pexpect", "3.0") if hasattr(sys, "pypy_version_info") and "64" in platform.machine(): pytest.skip("pypy-64 bit not supported") if sys.platform.startswith("freebsd"): pytest.xfail("pexpect does not work reliably on freebsd") logfile = self.tmpdir.join("spawn.out").open("wb") # Do not load user config. env = os.environ.copy() env.update(self._env_run_update) child = pexpect.spawn(cmd, logfile=logfile, env=env) self.request.addfinalizer(logfile.close) child.timeout = expect_timeout return child
Example 13
Project: sentry-python Author: getsentry File: test_basic.py License: BSD 2-Clause "Simplified" License | 6 votes |
def test_rest_framework_basic( sentry_init, client, capture_events, capture_exceptions, ct, body, route ): pytest.importorskip("rest_framework") sentry_init(integrations=[DjangoIntegration()], send_default_pii=True) exceptions = capture_exceptions() events = capture_events() if ct == "application/json": client.post( reverse(route), data=json.dumps(body), content_type="application/json" ) elif ct == "application/x-www-form-urlencoded": client.post(reverse(route), data=body) else: assert False (error,) = exceptions assert isinstance(error, ZeroDivisionError) (event,) = events assert event["exception"]["values"][0]["mechanism"]["type"] == "django" assert event["request"]["data"] == body assert event["request"]["headers"]["Content-Type"] == ct
Example 14
Project: vnpy_crypto Author: birforce File: test_resample.py License: MIT License | 6 votes |
def test_resample_dtype_coerceion(self): pytest.importorskip('scipy.interpolate') # GH 16361 df = {"a": [1, 3, 1, 4]} df = DataFrame(df, index=pd.date_range("2017-01-01", "2017-01-04")) expected = (df.astype("float64") .resample("H") .mean() ["a"] .interpolate("cubic") ) result = df.resample("H")["a"].mean().interpolate("cubic") tm.assert_series_equal(result, expected) result = df.resample("H").mean()["a"].interpolate("cubic") tm.assert_series_equal(result, expected)
Example 15
Project: aospy Author: spencerahill File: test_tutorial.py License: Apache License 2.0 | 5 votes |
def test_tutorial_notebook(): pytest.importorskip('nbformat') pytest.importorskip('nbconvert') pytest.importorskip('matplotlib') import nbformat from nbconvert.preprocessors import ExecutePreprocessor rootdir = os.path.join(aospy.__path__[0], 'examples') with open(os.path.join(rootdir, 'tutorial.ipynb')) as nb_file: notebook = nbformat.read(nb_file, as_version=nbformat.NO_CONVERT) kernel_name = 'python' + str(sys.version[0]) ep = ExecutePreprocessor(kernel_name=kernel_name) with warnings.catch_warnings(record=True): ep.preprocess(notebook, {})
Example 16
Project: cherrypy Author: cherrypy File: test_session.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def memcached_client_present(): pytest.importorskip('memcache')
Example 17
Project: python-clean-architecture Author: pcah File: test_tinydb.py License: MIT License | 5 votes |
def tinydb(): return pytest.importorskip("tinydb")
Example 18
Project: wuy Author: manatlan File: test_js.py License: GNU General Public License v2.0 | 5 votes |
def test_cef_if_present(): pytest.importorskip("cefpython3") try: old = wuy.ChromeApp wuy.ChromeApp = wuy.ChromeAppCef ut = UnitTests(log=True, val="mémé", iam="cef") reportJS(ut.tests, "main tests with cefpython3") assert len([ok for ok, *_ in ut.tests if ok]) == JSTEST finally: wuy.ChromeApp = old
Example 19
Project: py Author: pytest-dev File: test_assertion.py License: MIT License | 5 votes |
def setup_class(cls): cls.View = py.test.importorskip("py._code._assertionold").View
Example 20
Project: py Author: pytest-dev File: test_assertion.py License: MIT License | 5 votes |
def test_assert_customizable_reprcompare(monkeypatch): util = pytest.importorskip("_pytest.assertion.util") monkeypatch.setattr(util, '_reprcompare', lambda *args: 'hello') try: assert 3 == 4 except AssertionError: e = exvalue() s = str(e) assert "hello" in s
Example 21
Project: py Author: pytest-dev File: test_killproc.py License: MIT License | 5 votes |
def test_kill(tmpdir): subprocess = pytest.importorskip("subprocess") t = tmpdir.join("t.py") t.write("import time ; time.sleep(100)") proc = subprocess.Popen([sys.executable, str(t)]) assert proc.poll() is None # no return value yet py.process.kill(proc.pid) ret = proc.wait() if sys.platform == "win32" and ret == 0: pytest.skip("XXX on win32, subprocess.Popen().wait() on a killed " "process does not yield return value != 0") assert ret != 0
Example 22
Project: qutebrowser Author: qutebrowser File: fixtures.py License: GNU General Public License v3.0 | 5 votes |
def webkit_tab(web_tab_setup, qtbot, cookiejar_and_cache, mode_manager, widget_container, download_stub, webpage): webkittab = pytest.importorskip('qutebrowser.browser.webkit.webkittab') tab = webkittab.WebKitTab(win_id=0, mode_manager=mode_manager, private=False) widget_container.set_widget(tab) yield tab # Make sure the tab shuts itself down properly tab.private_api.shutdown()
Example 23
Project: qutebrowser Author: qutebrowser File: fixtures.py License: GNU General Public License v3.0 | 5 votes |
def webengine_tab(web_tab_setup, qtbot, redirect_webengine_data, tabbed_browser_stubs, mode_manager, widget_container, monkeypatch): tabwidget = tabbed_browser_stubs[0].widget tabwidget.current_index = 0 tabwidget.index_of = 0 webenginetab = pytest.importorskip( 'qutebrowser.browser.webengine.webenginetab') tab = webenginetab.WebEngineTab(win_id=0, mode_manager=mode_manager, private=False) widget_container.set_widget(tab) yield tab # If a page is still loading here, _on_load_finished could get called # during teardown when session_manager_stub is already deleted. tab.stop() # Make sure the tab shuts itself down properly tab.private_api.shutdown() # If we wait for the GC to clean things up, there's a segfault inside # QtWebEngine sometimes (e.g. if we only run # tests/unit/browser/test_caret.py). # However, with Qt < 5.12, doing this here will lead to an immediate # segfault... monkeypatch.undo() # version_check could be patched if qtutils.version_check('5.12'): sip.delete(tab._widget)
Example 24
Project: qutebrowser Author: qutebrowser File: fixtures.py License: GNU General Public License v3.0 | 5 votes |
def web_tab(request): """A WebKitTab/WebEngineTab.""" if request.param == 'webkit': pytest.importorskip('qutebrowser.browser.webkit.webkittab') return request.getfixturevalue('webkit_tab') elif request.param == 'webengine': pytest.importorskip('qutebrowser.browser.webengine.webenginetab') return request.getfixturevalue('webengine_tab') else: raise utils.Unreachable
Example 25
Project: qutebrowser Author: qutebrowser File: fixtures.py License: GNU General Public License v3.0 | 5 votes |
def webengineview(qtbot, monkeypatch, web_tab_setup): """Get a QWebEngineView if QtWebEngine is available.""" QtWebEngineWidgets = pytest.importorskip('PyQt5.QtWebEngineWidgets') monkeypatch.setattr(objects, 'backend', usertypes.Backend.QtWebEngine) view = QtWebEngineWidgets.QWebEngineView() qtbot.add_widget(view) return view
Example 26
Project: qutebrowser Author: qutebrowser File: test_version.py License: GNU General Public License v3.0 | 5 votes |
def test_existing_attributes(self, name, has_version): """Check if all dependencies have an expected __version__ attribute. The aim of this test is to fail if modules suddenly don't have a __version__ attribute anymore in a newer version. Args: name: The name of the module to check. has_version: Whether a __version__ attribute is expected. """ if name == 'cssutils': pytest.importorskip(name) module = importlib.import_module(name) assert hasattr(module, '__version__') == has_version
Example 27
Project: qutebrowser Author: qutebrowser File: test_version.py License: GNU General Public License v3.0 | 5 votes |
def test_chromium_version(monkeypatch, caplog): pytest.importorskip('PyQt5.QtWebEngineWidgets') ver = '77.0.3865.98' version.webenginesettings._init_user_agent_str( _QTWE_USER_AGENT.format(ver)) assert version._chromium_version() == ver
Example 28
Project: qutebrowser Author: qutebrowser File: test_version.py License: GNU General Public License v3.0 | 5 votes |
def test_chromium_version_prefers_saved_user_agent(monkeypatch): pytest.importorskip('PyQt5.QtWebEngineWidgets') version.webenginesettings._init_user_agent_str(_QTWE_USER_AGENT) class FakeProfile: def defaultProfile(self): raise AssertionError("Should not be called") monkeypatch.setattr(version.webenginesettings, 'QWebEngineProfile', FakeProfile()) version._chromium_version()
Example 29
Project: qutebrowser Author: qutebrowser File: test_version.py License: GNU General Public License v3.0 | 5 votes |
def test_chromium_version_unpatched(qapp, cache_tmpdir, data_tmpdir, config_stub): pytest.importorskip('PyQt5.QtWebEngineWidgets') assert version._chromium_version() not in ['', 'unknown', 'unavailable']
Example 30
Project: qutebrowser Author: qutebrowser File: test_version.py License: GNU General Public License v3.0 | 5 votes |
def test_func(self, qapp): """Simply call version.opengl_info() and see if it doesn't crash.""" pytest.importorskip("PyQt5.QtOpenGL") version.opengl_info()