当前位置: 首页>>代码示例>>Python>>正文


Python pytest.warns方法代码示例

本文整理汇总了Python中pytest.warns方法的典型用法代码示例。如果您正苦于以下问题:Python pytest.warns方法的具体用法?Python pytest.warns怎么用?Python pytest.warns使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pytest的用法示例。


在下文中一共展示了pytest.warns方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_orphaned_components

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import warns [as 别名]
def test_orphaned_components(simple_linear_model):
    model = simple_linear_model
    model.nodes["Input"].max_flow = ConstantParameter(model, 10.0)

    result = model.find_orphaned_parameters()
    assert(not result)
    # assert that warning not raised by check
    with pytest.warns(None) as record:
        model.check()
    for w in record:
        if isinstance(w, OrphanedParameterWarning):
            pytest.fail("OrphanedParameterWarning raised unexpectedly!")

    # add some orphans
    orphan1 = ConstantParameter(model, 5.0)
    orphan2 = ConstantParameter(model, 10.0)
    orphans = {orphan1, orphan2}
    result = model.find_orphaned_parameters()
    assert(orphans == result)

    with pytest.warns(OrphanedParameterWarning):
        model.check() 
开发者ID:pywr,项目名称:pywr,代码行数:24,代码来源:test_parameters.py

示例2: test_normalize_probabilities

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import warns [as 别名]
def test_normalize_probabilities():
    constraints = {"observables": [3]}
    params, options = generate_random_model(point_constr=constraints)
    optim_paras_1, _ = process_params_and_options(params, options)

    for group in ["initial_exp_edu", "observable_"]:
        mask = params.index.get_level_values(0).str.contains(group)
        params.loc[mask, "value"] = params.loc[mask, "value"].to_numpy() / 2

    with pytest.warns(UserWarning, match=r"The probabilities for parameter group"):
        optim_paras_2, _ = process_params_and_options(params, options)

    for key in optim_paras_1["choices"]["edu"]["start"]:
        np.testing.assert_array_almost_equal(
            optim_paras_1["choices"]["edu"]["start"][key],
            optim_paras_2["choices"]["edu"]["start"][key],
        )
    for level in optim_paras_1["observables"]["observable_0"]:
        np.testing.assert_array_almost_equal(
            optim_paras_1["observables"]["observable_0"][level],
            optim_paras_2["observables"]["observable_0"][level],
        ) 
开发者ID:OpenSourceEconomics,项目名称:respy,代码行数:24,代码来源:test_model_processing.py

示例3: test_stream_incomplete_header

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import warns [as 别名]
def test_stream_incomplete_header(self, stop, nframes, tmpdir):
        # Test that an incomplete last header leads to the second-to-last
        # header being used, and raises a warning.
        sample_rate = self.frame_rate * self.payload_nbytes / 512
        filename_incompletehead = str(
            tmpdir.join('test_incomplete_header.timestamp'))
        with open(SAMPLE_PHASED_HEADER, 'rt') as fh, \
                open(filename_incompletehead, 'wt') as fw:
            fw.write(fh.read()[:stop])
        with gsb.open(filename_incompletehead, 'rs', raw=SAMPLE_PHASED,
                      sample_rate=sample_rate,
                      payload_nbytes=self.payload_nbytes,
                      squeeze=False) as fh_r:
            with pytest.warns(UserWarning, match='second-to-last entry'):
                shape = fh_r.shape

            assert shape[0] == nframes * fh_r.samples_per_frame

            info = fh_r.info
            assert info.errors == {}
            assert info.warnings.keys() == {'number_of_frames',
                                            'consistent'}
            assert 'incomplete' in info.warnings['number_of_frames']
            assert 'contains more bytes' in info.warnings['consistent'] 
开发者ID:mhvk,项目名称:baseband,代码行数:26,代码来源:test_gsb.py

示例4: test_missing_middle

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import warns [as 别名]
def test_missing_middle(self, missing_bytes, missing_frames, tmpdir):
        # In all these cases, some data will be missing.
        fake_file = self.fake_file(tmpdir)
        corrupt_file = self.corrupt_copy(fake_file, missing_bytes)
        # Check that bad frames are found with verify only.
        with mark4.open(corrupt_file, 'rs', verify=True, **self.kwargs) as fv:
            assert not fv.info.readable
            assert not fv.info.checks['continuous']
            assert 'continuous' in fv.info.errors
            expected_msg = 'While reading at {}'.format(
                missing_frames.start * fv.samples_per_frame)
            assert expected_msg in fv.info.errors['continuous']

        with mark4.open(corrupt_file, 'rs', **self.kwargs) as fr:
            assert fr.size == 8 * self.data.size
            with pytest.warns(UserWarning, match='problem loading frame'):
                data = fr.read()

        data = data.reshape((-1,) + self.data.shape)
        expected = np.stack([self.data] * 8)
        expected[missing_frames] = 0.
        assert np.all(data.astype(int) == expected) 
开发者ID:mhvk,项目名称:baseband,代码行数:24,代码来源:test_corrupt_files.py

示例5: assert_warns_msg

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import warns [as 别名]
def assert_warns_msg(expected_warning, func, msg, *args, **kwargs):
    """Assert a call leads to a warning with a specific message

    Test whether a function call leads to a warning of type
    ``expected_warning`` with a message that contains the string ``msg``.

    Parameters
    ----------
    expected_warning : warning class
        The class of warning to be checked; e.g., DeprecationWarning
    func : object
        The class, method, property, or function to be called as\
        func(\*args, \*\*kwargs)
    msg : str
        The message or a substring of the message to test for.
    \*args : positional arguments to ``func``
    \*\*kwargs: keyword arguments to ``func``

    """
    with pytest.warns(expected_warning) as record:
        func(*args, **kwargs)
    npt.assert_equal(len(record), 1)
    if msg is not None:
        npt.assert_equal(msg in record[0].message.args[0], True) 
开发者ID:pulse2percept,项目名称:pulse2percept,代码行数:26,代码来源:testing.py

示例6: test_default_factors_conflict

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import warns [as 别名]
def test_default_factors_conflict(self, newconfig, capsys):
        with pytest.warns(UserWarning, match=r"conflicting basepython .*"):
            exe = "pypy3" if tox.INFO.IS_PYPY else "python3"
            env = "pypy27" if tox.INFO.IS_PYPY else "py27"
            config = newconfig(
                """\
                [testenv]
                basepython={}
                [testenv:{}]
                commands = python --version
                """.format(
                    exe, env,
                ),
            )
        assert len(config.envconfigs) == 1
        envconfig = config.envconfigs[env]
        assert envconfig.basepython == exe 
开发者ID:tox-dev,项目名称:tox,代码行数:19,代码来源:test_config.py

示例7: test_default_factors_conflict_ignore

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import warns [as 别名]
def test_default_factors_conflict_ignore(self, newconfig, capsys):
        with pytest.warns(None) as record:
            config = newconfig(
                """
                [tox]
                ignore_basepython_conflict=True
                [testenv]
                basepython=python3
                [testenv:py27]
                commands = python --version
            """,
            )
        assert len(config.envconfigs) == 1
        envconfig = config.envconfigs["py27"]
        assert envconfig.basepython == "python2.7"
        assert len(record) == 0, "\n".join(repr(r.message) for r in record) 
开发者ID:tox-dev,项目名称:tox,代码行数:18,代码来源:test_config.py

示例8: test_healpix_to_lonlat_invalid

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import warns [as 别名]
def test_healpix_to_lonlat_invalid():
    dx = [0.1, 0.4, 0.9]
    dy = [0.4, 0.3, 0.2]

    with pytest.warns(RuntimeWarning, match='invalid value'):
        lon, lat = healpix_to_lonlat([-1, 2, 3], 4)

    with pytest.warns(RuntimeWarning, match='invalid value'):
        lon, lat = healpix_to_lonlat([192, 2, 3], 4)

    with pytest.raises(ValueError) as exc:
        lon, lat = healpix_to_lonlat([1, 2, 3], 5)
    assert exc.value.args[0] == 'nside must be a power of two'

    with pytest.raises(ValueError) as exc:
        lon, lat = healpix_to_lonlat([1, 2, 3], 4, order='banana')
    assert exc.value.args[0] == "order must be 'nested' or 'ring'"

    with pytest.raises(ValueError) as exc:
        lon, lat = healpix_to_lonlat([1, 2, 3], 4, dx=[-0.1, 0.4, 0.5], dy=dy)
    assert exc.value.args[0] == 'dx must be in the range [0:1]'

    with pytest.raises(ValueError) as exc:
        lon, lat = healpix_to_lonlat([1, 2, 3], 4, dx=dx, dy=[-0.1, 0.4, 0.5])
    assert exc.value.args[0] == 'dy must be in the range [0:1]' 
开发者ID:astropy,项目名称:astropy-healpix,代码行数:27,代码来源:test_core.py

示例9: test_parser_parser_private_not_warns

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import warns [as 别名]
def test_parser_parser_private_not_warns():
    from dateutil.parser._parser import _timelex, _tzparser
    from dateutil.parser._parser import _parsetz

    with pytest.warns(None) as recorder:
        _tzparser()
        assert len(recorder) == 0

    with pytest.warns(None) as recorder:
        _timelex('2014-03-03')

        assert len(recorder) == 0

    with pytest.warns(None) as recorder:
        _parsetz('+05:00')
        assert len(recorder) == 0 
开发者ID:MediaBrowser,项目名称:plugin.video.emby,代码行数:18,代码来源:test_internals.py

示例10: test_group_indices

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import warns [as 别名]
def test_group_indices():
    df = pd.DataFrame({'x': [1, 5, 2, 2, 4, 0, 4],
                       'y': [1, 2, 3, 4, 5, 6, 5]})

    results = df >> group_by('x') >> group_indices()
    assert all(results == [1, 4, 2, 2, 3, 0, 3])

    results = df >> group_indices('y % 2')
    assert all(results == [1, 0, 1, 0, 1, 0, 1])

    results = df >> group_indices()
    assert all(results == [1, 1, 1, 1, 1, 1, 1])

    # Branches
    with pytest.warns(UserWarning):
        df >> group_by('x') >> group_indices('y') 
开发者ID:has2k1,项目名称:plydata,代码行数:18,代码来源:test_dataframe.py

示例11: test_http_transport_verify_error

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import warns [as 别名]
def test_http_transport_verify_error(http_transport_query):
    with Client(
        transport=RequestsHTTPTransport(
            url="https://countries.trevorblades.com/", verify=False,
        )
    ) as client:
        with pytest.warns(Warning) as record:
            client.execute(http_transport_query)
    assert len(record) == 1
    assert "Unverified HTTPS request is being made to host" in str(record[0].message) 
开发者ID:graphql-python,项目名称:gql,代码行数:12,代码来源:test_client.py

示例12: test_safe_wait_INADDR_ANY

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import warns [as 别名]
def test_safe_wait_INADDR_ANY():  # pylint: disable=invalid-name
    """
    Wait on INADDR_ANY should not raise IOError

    In cases where the loopback interface does not exist, CherryPy cannot
    effectively determine if a port binding to INADDR_ANY was effected.
    In this situation, CherryPy should assume that it failed to detect
    the binding (not that the binding failed) and only warn that it could
    not verify it.
    """
    # At such a time that CherryPy can reliably determine one or more
    #  viable IP addresses of the host, this test may be removed.

    # Simulate the behavior we observe when no loopback interface is
    #  present by: finding a port that's not occupied, then wait on it.

    free_port = portend.find_available_local_port()

    servers = cherrypy.process.servers

    inaddr_any = '0.0.0.0'

    # Wait on the free port that's unbound
    with pytest.warns(
            UserWarning,
            match='Unable to verify that the server is bound on ',
    ) as warnings:
        # pylint: disable=protected-access
        with servers._safe_wait(inaddr_any, free_port):
            portend.occupied(inaddr_any, free_port, timeout=1)
    assert len(warnings) == 1

    # The wait should still raise an IO error if INADDR_ANY was
    #  not supplied.
    with pytest.raises(IOError):
        # pylint: disable=protected-access
        with servers._safe_wait('127.0.0.1', free_port):
            portend.occupied('127.0.0.1', free_port, timeout=1) 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:40,代码来源:test_states.py

示例13: test_import_warning

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import warns [as 别名]
def test_import_warning():
    with pytest.warns(None) as record:
        import_all_names(__file__, __name__)
    assert issubclass(record[-1].category, UserWarning)
    assert "conflicting names" in str(record[-1].message) 
开发者ID:pcah,项目名称:python-clean-architecture,代码行数:7,代码来源:__init__.py

示例14: test_query_info_deprecation

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import warns [as 别名]
def test_query_info_deprecation():
    with pytest.warns(DeprecationWarning) as record:
        from smbprotocol import query_info

    assert len(record) == 1
    assert str(record.list[0].message) == 'The smbprotocol.query_info file has been renamed to ' \
                                          'smbprotocol.file_info and will be removed in the next major release.' 
开发者ID:jborean93,项目名称:smbprotocol,代码行数:9,代码来源:test_query_info.py

示例15: test_result_model_deprecations

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import warns [as 别名]
def test_result_model_deprecations(result_data_fixture, optimization_data_fixture):

    with pytest.warns(DeprecationWarning):
        qcel.models.ResultProperties(scf_one_electron_energy="-5.0")

    with pytest.warns(DeprecationWarning):
        qcel.models.ResultInput(**{k: result_data_fixture[k] for k in ["molecule", "model", "driver"]})

    with pytest.warns(DeprecationWarning):
        qcel.models.Result(**result_data_fixture)

    with pytest.warns(DeprecationWarning):
        qcel.models.Optimization(**optimization_data_fixture) 
开发者ID:MolSSI,项目名称:QCElemental,代码行数:15,代码来源:test_model_results.py


注:本文中的pytest.warns方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。