Python pytest.warns() Examples

The following are 30 code examples of pytest.warns(). 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 also want to check out all available functions/classes of the module pytest , or try the search function .
Example #1
Source File: testing.py    From pulse2percept with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #2
Source File: test_core.py    From astropy-healpix with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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]' 
Example #3
Source File: test_model_processing.py    From respy with MIT License 6 votes vote down vote up
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],
        ) 
Example #4
Source File: test_internals.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #5
Source File: test_config.py    From tox with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: test_gsb.py    From baseband with GNU General Public License v3.0 6 votes vote down vote up
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'] 
Example #7
Source File: test_config.py    From tox with MIT License 6 votes vote down vote up
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 
Example #8
Source File: test_parameters.py    From pywr with GNU General Public License v3.0 6 votes vote down vote up
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() 
Example #9
Source File: test_dataframe.py    From plydata with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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') 
Example #10
Source File: test_corrupt_files.py    From baseband with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #11
Source File: test_core_common.py    From pdvega with MIT License 5 votes vote down vote up
def test_series_plot_kwd_warnings(data, kind, info):
    col = info['col']
    kwds = info.get('kwds', {})
    data = data[col]

    with pytest.warns(UserWarning, match="Unrecognized keywords in vgplot.[a-z]+\(\): 'unrecognized_arg'"):
        data.vgplot(kind=kind, unrecognized_arg=None, **kwds)

    with pytest.warns(UserWarning):
        data.vgplot(kind=kind, unrecognized1=None, unrecognized2=None, **kwds) 
Example #12
Source File: test_contract.py    From brownie with MIT License 5 votes vote down vote up
def test_retrieve_existing(network):
    network.connect("mainnet")
    with pytest.warns(BrownieCompilerWarning):
        new = Contract.from_explorer("0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2")

    existing = Contract("0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2")
    assert new == existing 
Example #13
Source File: test_cli.py    From ara-archive with GNU General Public License v3.0 5 votes vote down vote up
def test_generate_empty_html(self):
        """ Ensures the application is still rendered gracefully """
        self.app.config['ARA_IGNORE_EMPTY_GENERATION'] = False
        dir = self.generate_dir
        shell = ara.shell.AraCli()
        shell.prepare_to_run_command(ara.cli.generate.GenerateHtml)
        cmd = ara.cli.generate.GenerateHtml(shell, None)
        parser = cmd.get_parser('test')
        args = parser.parse_args([dir])

        with pytest.warns(MissingURLGeneratorWarning) as warnings:
            cmd.take_action(args)

        # pytest 3.0 through 3.1 are backwards incompatible here
        if LooseVersion(pytest.__version__) >= LooseVersion('3.1.0'):
            cat = [item._category_name for item in warnings]
            self.assertTrue(any('MissingURLGeneratorWarning' in c
                                for c in cat))
        else:
            self.assertTrue(any(MissingURLGeneratorWarning == w.category
                                for w in warnings))

        paths = [
            os.path.join(dir, 'index.html'),
            os.path.join(dir, 'static'),
        ]

        for path in paths:
            self.assertTrue(os.path.exists(path)) 
Example #14
Source File: test_build.py    From bamnostic with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_check_index():
    with bs.AlignmentFile(bs.example_bam) as bam:
        with pytest.warns(UserWarning):
            bam.check_index('not_a_file.bai') 
Example #15
Source File: test_contract.py    From brownie with MIT License 5 votes vote down vote up
def test_duplicate_alias(network):
    network.connect("mainnet")

    foo = Contract.from_explorer("0x2af5d2ad76741191d15dfe7bf6ac92d4bd912ca3")
    with pytest.warns(BrownieCompilerWarning):
        bar = Contract.from_explorer("0x2157a7894439191e520825fe9399ab8655e0f708")

    foo.set_alias("foo")
    with pytest.raises(ValueError):
        bar.set_alias("foo")

    bar.set_alias("bar")
    foo.set_alias(None)
    bar.set_alias("foo") 
Example #16
Source File: test_contract.py    From brownie with MIT License 5 votes vote down vote up
def test_alias(network):
    network.connect("mainnet")
    with pytest.warns(BrownieCompilerWarning):
        contract = Contract.from_explorer("0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2")

    contract.set_alias("testalias")

    assert contract.alias == "testalias"
    assert Contract("testalias") == contract

    contract.set_alias(None)

    assert contract.alias is None
    with pytest.raises(ValueError):
        Contract("testalias") 
Example #17
Source File: test_build.py    From bamnostic with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_index():
    with pytest.warns(UserWarning):
        bam_no_bai = bs.AlignmentFile(bs.example_bam, index_filename='not_a_file.bai') 
Example #18
Source File: test_main.py    From python-devtools with MIT License 5 votes vote down vote up
def test_warnings_disabled():
    debug_ = Debug(warnings=False)
    with pytest.warns(None) as warnings:
        v1 = eval('debug_.format(1)')
        assert str(v1) == '<string>:1 <module>\n    1 (int)'
        v2 = debug_.format(1)
        assert 'test_warnings_disabled\n    1 (int)' in str(v2)
    assert len(warnings) == 0 
Example #19
Source File: test_contract.py    From brownie with MIT License 5 votes vote down vote up
def test_existing_different_chains(network):
    network.connect("mainnet")
    with pytest.warns(BrownieCompilerWarning):
        Contract.from_explorer("0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2")

    network.disconnect()
    network.connect("ropsten")
    with pytest.raises(ValueError):
        Contract("0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2") 
Example #20
Source File: test_stateful_models.py    From async2rewrite with MIT License 5 votes vote down vote up
def test_wait_for_message_warning():
    with pytest.warns(UserWarning):
        async2rewrite.from_text("bot.wait_for_message(author=member)") 
Example #21
Source File: test_contract.py    From brownie with MIT License 5 votes vote down vote up
def test_from_explorer_etc(network):
    network.connect("etc")
    with pytest.warns(BrownieCompilerWarning):
        contract = Contract.from_explorer("0x085b0fdf115aa9e16ae1bddd396ce1f993c52220")

    assert contract._name == "ONEX" 
Example #22
Source File: test_contract.py    From brownie with MIT License 5 votes vote down vote up
def test_from_explorer_osx_pre_050(network, monkeypatch):
    network.connect("mainnet")
    monkeypatch.setattr("sys.platform", "darwin")
    installed = ["v0.5.8", "v0.5.7"]
    monkeypatch.setattr("solcx.get_installed_solc_versions", lambda: installed)

    # chainlink, compiler version 0.4.24
    with pytest.warns(BrownieCompilerWarning):
        contract = Contract.from_explorer("0xf79d6afbb6da890132f9d7c355e3015f15f3406f")
    assert "pcMap" not in contract._build 
Example #23
Source File: test_contract.py    From brownie with MIT License 5 votes vote down vote up
def test_from_explorer_pre_422(network):
    network.connect("mainnet")

    # MKR, compiler version 0.4.18
    with pytest.warns(BrownieCompilerWarning):
        contract = Contract.from_explorer("0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2")
    assert contract._name == "DSToken"
    assert "pcMap" not in contract._build 
Example #24
Source File: test_contract.py    From brownie with MIT License 5 votes vote down vote up
def test_from_explorer_only_abi(network):
    network.connect("mainnet")
    # uniswap DAI market - ABI is available but source is not
    with pytest.warns(BrownieCompilerWarning):
        contract = Contract.from_explorer("0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667")

    assert contract._name == "UnknownContractName"
    assert "pcMap" not in contract._build 
Example #25
Source File: test_contract.py    From brownie with MIT License 5 votes vote down vote up
def test_deprecated_init_ethpm(ipfs_mock, network):
    network.connect("ropsten")

    with pytest.warns(DeprecationWarning):
        old = Contract("ComplexNothing", manifest_uri="ipfs://testipfs-complex")

    assert old == Contract.from_ethpm("ComplexNothing", manifest_uri="ipfs://testipfs-complex") 
Example #26
Source File: test_contract.py    From brownie with MIT License 5 votes vote down vote up
def test_deprecated_init_abi(tester):
    with pytest.warns(DeprecationWarning):
        old = Contract("BrownieTester", tester.address, tester.abi)

    assert old == Contract.from_abi("BrownieTester", tester.address, tester.abi) 
Example #27
Source File: test_surfgen.py    From NURBS-Python with MIT License 5 votes vote down vote up
def test_bumps5(grid2):
    with pytest.warns(UserWarning):
        # non-integer num_bumps
        grid2.bumps(num_bumps=1.1, bump_height=5, base_extent=2) 
Example #28
Source File: test_surfgen.py    From NURBS-Python with MIT License 5 votes vote down vote up
def test_grid_generate4():
    test_grid = CPGen.GridWeighted(7, 13)
    with pytest.warns(UserWarning):
        test_grid.generate(3, 4.2) 
Example #29
Source File: test_surfgen.py    From NURBS-Python with MIT License 5 votes vote down vote up
def test_grid_generate3():
    test_grid = CPGen.GridWeighted(7, 13)
    with pytest.warns(UserWarning):
        test_grid.generate(3.5, 4) 
Example #30
Source File: connection_commands_test.py    From aioredis with MIT License 5 votes vote down vote up
def test_yield_from_backwards_compatibility(create_redis, server):
    redis = await create_redis(server.tcp_address)

    assert isinstance(redis, Redis)
    # TODO: there should not be warning
    # with pytest.warns(UserWarning):
    with await redis as client:
        assert isinstance(client, Redis)
        assert client is not redis
        assert await client.ping()