当前位置: 首页>>代码示例>>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;未经允许,请勿转载。