當前位置: 首頁>>代碼示例>>Python>>正文


Python pytest.importorskip方法代碼示例

本文整理匯總了Python中pytest.importorskip方法的典型用法代碼示例。如果您正苦於以下問題:Python pytest.importorskip方法的具體用法?Python pytest.importorskip怎麽用?Python pytest.importorskip使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pytest的用法示例。


在下文中一共展示了pytest.importorskip方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_rank_methods_frame

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import importorskip [as 別名]
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) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:27,代碼來源:test_rank.py

示例2: webpage

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import importorskip [as 別名]
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 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:23,代碼來源:fixtures.py

示例3: test_option_no_warning

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import importorskip [as 別名]
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 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:26,代碼來源:test_converter.py

示例4: test_rank_methods_series

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import importorskip [as 別名]
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) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:24,代碼來源:test_rank.py

示例5: test_parse_public_s3_bucket

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import importorskip [as 別名]
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) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:19,代碼來源:test_network.py

示例6: test_decompression_regex_sep

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import importorskip [as 別名]
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) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:23,代碼來源:test_python_parser_only.py

示例7: test_read_expands_user_home_dir

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import importorskip [as 別名]
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) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:22,代碼來源:test_common.py

示例8: test_write_fspath_hdf5

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import importorskip [as 別名]
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) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:21,代碼來源:test_common.py

示例9: test_plot_estimator_and_lightgbm

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import importorskip [as 別名]
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() 
開發者ID:ogrisel,項目名稱:pygbm,代碼行數:25,代碼來源:test_plotting.py

示例10: ftp_writable

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import importorskip [as 別名]
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 
開發者ID:intake,項目名稱:filesystem_spec,代碼行數:27,代碼來源:conftest.py

示例11: spawn

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import importorskip [as 別名]
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 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:23,代碼來源:pytester.py

示例12: test_rest_framework_basic

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import importorskip [as 別名]
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 
開發者ID:getsentry,項目名稱:sentry-python,代碼行數:27,代碼來源:test_basic.py

示例13: test_resample_dtype_coerceion

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import importorskip [as 別名]
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) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:22,代碼來源:test_resample.py

示例14: test_tutorial_notebook

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import importorskip [as 別名]
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, {}) 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:17,代碼來源:test_tutorial.py

示例15: memcached_client_present

# 需要導入模塊: import pytest [as 別名]
# 或者: from pytest import importorskip [as 別名]
def memcached_client_present():
    pytest.importorskip('memcache') 
開發者ID:cherrypy,項目名稱:cherrypy,代碼行數:4,代碼來源:test_session.py


注:本文中的pytest.importorskip方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。