當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。