Python pytest.warns() Examples
The following are 30 code examples for showing how to use pytest.warns(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
pytest
, or try the search function
.
Example 1
Project: pywr Author: pywr File: test_parameters.py License: GNU General Public License v3.0 | 6 votes |
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 2
Project: respy Author: OpenSourceEconomics File: test_model_processing.py License: MIT License | 6 votes |
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 3
Project: baseband Author: mhvk File: test_gsb.py License: GNU General Public License v3.0 | 6 votes |
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 4
Project: baseband Author: mhvk File: test_corrupt_files.py License: GNU General Public License v3.0 | 6 votes |
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 5
Project: pulse2percept Author: pulse2percept File: testing.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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 6
Project: tox Author: tox-dev File: test_config.py License: MIT License | 6 votes |
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 7
Project: tox Author: tox-dev File: test_config.py License: MIT License | 6 votes |
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 8
Project: astropy-healpix Author: astropy File: test_core.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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 9
Project: plugin.video.emby Author: MediaBrowser File: test_internals.py License: GNU General Public License v3.0 | 6 votes |
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 10
Project: plydata Author: has2k1 File: test_dataframe.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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 11
Project: gql Author: graphql-python File: test_client.py License: MIT License | 5 votes |
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)
Example 12
Project: cherrypy Author: cherrypy File: test_states.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example 13
Project: python-clean-architecture Author: pcah File: __init__.py License: MIT License | 5 votes |
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)
Example 14
Project: smbprotocol Author: jborean93 File: test_query_info.py License: MIT License | 5 votes |
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.'
Example 15
Project: QCElemental Author: MolSSI File: test_model_results.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example 16
Project: quart Author: pgjones File: test_asgi.py License: MIT License | 5 votes |
def test_websocket_accept_connection_warns() -> None: connection = ASGIWebsocketConnection(Quart(__name__), {}) async def mock_send(message: dict) -> None: pass with pytest.warns(None): await connection.accept_connection(mock_send, Headers({"a": "b"}), None)
Example 17
Project: pywr Author: pywr File: test_core.py License: GNU General Public License v3.0 | 5 votes |
def test_json_min_version(): """Test warning is raised if document minimum version is more than we have""" filename = os.path.join(TEST_FOLDER, "models", "version1.json") with pytest.warns(RuntimeWarning): model = Model.load(filename)
Example 18
Project: myhdl Author: myhdl File: test_keywords.py License: GNU Lesser General Public License v2.1 | 5 votes |
def test_invalid_keyword_name(): sig_1 = Signal(True) sig_2 = Signal(True) temp_directory = tempfile.mkdtemp() sys.path.append(temp_directory) keyword_template = string.Template(keyword_code) try: for keyword in _vhdl_keywords: if keyword in python_kwlist: continue fd, full_filename = tempfile.mkstemp( suffix='.py', dir=temp_directory) os.write(fd, keyword_template.substitute(keyword=keyword).encode('utf-8')) os.close(fd) module_name = os.path.basename(full_filename)[:-3] # chop off .py keyword_import = importlib.import_module(module_name) a_block = keyword_import.invalid_import_keyword(sig_1, sig_2) with pytest.warns(ToVHDLWarning): a_block.convert(hdl='VHDL') finally: sys.path.pop() shutil.rmtree(temp_directory)
Example 19
Project: myhdl Author: myhdl File: test_keywords.py License: GNU Lesser General Public License v2.1 | 5 votes |
def test_invalid_signal_underscore_name(): sig_1 = Signal(True) sig_2 = Signal(True) a_block = invalid_signal_underscore(sig_1, sig_2) # Multiple conversions of a valid block should pass without warning with pytest.warns(ToVHDLWarning): a_block.convert(hdl='VHDL')
Example 20
Project: myhdl Author: myhdl File: test_keywords.py License: GNU Lesser General Public License v2.1 | 5 votes |
def test_invalid_function_underscore_name(): sig_1 = Signal(True) sig_2 = Signal(True) clock = Signal(True) a_block = invalid_function_underscore(clock, sig_1, sig_2) # Multiple conversions of a valid block should pass without warning with pytest.warns(ToVHDLWarning): a_block.convert(hdl='VHDL')
Example 21
Project: sanic Author: huge-success File: test_blueprints.py License: MIT License | 5 votes |
def test_register_blueprint(app, debug): bp = Blueprint("bp") app.debug = debug with pytest.warns(DeprecationWarning) as record: app.register_blueprint(bp) assert record[0].message.args[0] == ( "Use of register_blueprint will be deprecated in " "version 1.0. Please use the blueprint method" " instead" )
Example 22
Project: differential-privacy-library Author: IBM File: test_LaplaceBoundedDomain.py License: MIT License | 5 votes |
def test_semi_inf_domain_inf_epsilon(self): self.mech.set_epsilon(float("inf")).set_sensitivity(1).set_bounds(0.0, float("inf")) with pytest.warns(None) as w: self.assertIsNotNone(self.mech.randomise(0)) self.assertFalse(w, "Warning thrown for LaplaceBoundedDomain")
Example 23
Project: flask_simplelogin Author: flask-extensions File: test_config.py License: MIT License | 5 votes |
def test_configs_are_loaded_with_backwards_compatibility(client): settings = Settings( SIMPLE_LOGIN_BLUEPRINT='custom_blueprint', SIMPLE_LOGIN_LOGIN_URL='/custom_login/', SIMPLE_LOGIN_LOGOUT_URL='/custom_logout/', SIMPLE_LOGIN_HOME_URL='/custom_home/' ) with pytest.warns(FutureWarning): sl = create_simple_login(settings) assert sl.config['blueprint'] == 'custom_blueprint' assert sl.config['login_url'] == '/custom_login/' assert sl.config['logout_url'] == '/custom_logout/' assert sl.config['home_url'] == '/custom_home/'
Example 24
Project: respy Author: OpenSourceEconomics File: test_model_processing.py License: MIT License | 5 votes |
def test_parse_initial_and_max_experience(): """Test ensures that probabilities are transformed with logs and rest passes.""" choices = ["a", "b"] options = {"n_periods": 10} optim_paras = {"choices_w_exp": choices, "choices": {"a": {}, "b": {}}} params = pd.DataFrame( { "category": [ "initial_exp_a_0", "initial_exp_a_5", "initial_exp_b_0", "initial_exp_b_5", "maximum_exp", ], "name": ["probability"] * 2 + ["constant"] * 2 + ["b"], "value": [2, 2, np.log(2), np.log(2), 5], } ).set_index(["category", "name"])["value"] with pytest.warns(UserWarning, match=r"The probabilities for parameter group"): optim_paras = _parse_initial_and_max_experience(optim_paras, params, options) assert ( optim_paras["choices"]["a"]["start"][0] == optim_paras["choices"]["a"]["start"][5] ).all() assert ( optim_paras["choices"]["b"]["start"][0] == optim_paras["choices"]["b"]["start"][5] ).all() assert optim_paras["choices"]["a"]["max"] == options["n_periods"] - 1 + max( optim_paras["choices"]["a"]["start"] ) assert optim_paras["choices"]["b"]["max"] == 5
Example 25
Project: baseband Author: mhvk File: test_base.py License: GNU General Public License v3.0 | 5 votes |
def test_make_setter(self): header = self.header.copy() header['x0_16_4'] = 0xe assert header.words[0] == 0x123e5678 header['x0_16_4'] = 0 assert header.words[0] == 0x12305678 header['x0_16_4'] = True # Special value: fill all bits assert header.words[0] == 0x123f5678 with pytest.raises(ValueError, match='cannot be represented with 4 bits'): header['x0_16_4'] = 0x10 with pytest.raises(ValueError, match='no default value'): header['x0_16_4'] = None header['x0_31_1'] = True assert header.words[0] == 0x923f5678 header['x1_0_32'] = 0x1234 assert header.words[:2] == [0x923f5678, 0x1234] header['x2_0_64'] = 1 assert header.words[2:] == [1, 0] header['x2_0_64'] = True # fill all bits assert header.words[2:] == [0xffffffff, 0xffffffff] header['x2_0_64'] = None # set to default assert header.words[2:] == [0, 1] # Also check update method. header.update(x1_0_32=0x5678, x2_0_64=1) assert header.words == [0x923f5678, 0x5678, 1, 0] with pytest.warns(UserWarning, match='unused.*bla'): header.update(bla=10) with pytest.raises(ValueError, match='cannot be represented'): header.update(x0_16_4=-1)
Example 26
Project: baseband Author: mhvk File: test_vdif.py License: GNU General Public License v3.0 | 5 votes |
def test_incomplete_stream(self, tmpdir, fill_value): vdif_incomplete = str(tmpdir.join('incomplete.vdif')) with vdif.open(SAMPLE_FILE, 'rs') as fr: record = fr.read(20010) with pytest.warns(UserWarning, match='partial buffer'): with vdif.open(vdif_incomplete, 'ws', header0=fr.header0, sample_rate=32*u.MHz, nthread=8) as fw: fw.write(record) with vdif.open(vdif_incomplete, 'rs', fill_value=fill_value) as fwr: valid = fwr.read(20000) assert np.all(valid == record[:20000]) assert fwr.fill_value == fill_value invalid = fwr.read() assert invalid.shape == valid.shape assert np.all(invalid == fill_value)
Example 27
Project: baseband Author: mhvk File: test_corrupt_files.py License: GNU General Public License v3.0 | 5 votes |
def test_missing_frames(self, missing, tmpdir): """Purely missing frames should just be marked invalid.""" # Even at the very start; gh-359 sample = np.frombuffer(self.sample_bytes, 'u1').reshape(-1, 5032) use = np.ones(len(sample), bool) use[missing] = False reduced = sample[use] corrupt_file = str(tmpdir.join('missing_frames.vdif')) with open(corrupt_file, 'wb') as s: s.write(reduced.tobytes()) with vdif.open(corrupt_file, 'rb') as fr: assert 'number_of_frames' not in fr.info.warnings if np.count_nonzero(use) % 8 == 0: assert 'number_of_framesset' not in fr.info.warnings else: assert 'number_of_framesets' in fr.info.warnings with vdif.open(corrupt_file, 'rs') as fh: with pytest.warns(UserWarning, match='problem loading frame'): data = fh.read() # Get data in frame order to zero expected bad frames. expected = (self.data.copy().reshape(-1, 20000, 8) .transpose(0, 2, 1).reshape(-1, 20000)) expected[missing] = 0. # Back into regular order expected = (expected.reshape(-1, 8, 20000) .transpose(0, 2, 1).reshape(-1, 8)) assert np.all(expected == data)
Example 28
Project: baseband Author: mhvk File: test_corrupt_files.py License: GNU General Public License v3.0 | 5 votes |
def test_missing_frameset(self, frame_nr, tmpdir): if not isinstance(frame_nr, slice): frame_nr = slice(frame_nr, frame_nr+1) missing = slice(frame_nr.start * self.frameset_nbytes, frame_nr.stop * self.frameset_nbytes) fake_file = self.fake_file(tmpdir) corrupt_file = self.corrupt_copy(fake_file, missing) with vdif.open(corrupt_file, 'rs') as fr: with pytest.warns(UserWarning, match='All threads'): data = fr.read() data = data.reshape((-1,) + self.data.shape) assert np.all(data[:frame_nr.start].astype(int) == self.data) assert np.all(data[frame_nr.stop:].astype(int) == self.data) assert np.all(data[frame_nr] == 0.)
Example 29
Project: baseband Author: mhvk File: test_corrupt_files.py License: GNU General Public License v3.0 | 5 votes |
def test_missing_middle(self, missing_bytes, missing_data, 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) with vdif.open(corrupt_file, 'rs') as fr: assert fr.size == 16 * self.data.size with pytest.warns(UserWarning, match='problem loading frame set'): data = fr.read() expected = np.concatenate([self.data] * 16) expected[missing_data] = 0. assert np.all(data.astype(int) == expected)
Example 30
Project: baseband Author: mhvk File: test_corrupt_files.py License: GNU General Public License v3.0 | 5 votes |
def test_missing_frames(self, frame_nr, tmpdir): if not isinstance(frame_nr, slice): frame_nr = slice(frame_nr, frame_nr+1) missing = slice(frame_nr.start * self.header0.frame_nbytes, frame_nr.stop * self.header0.frame_nbytes) fake_file = self.fake_file(tmpdir) corrupt_file = self.corrupt_copy(fake_file, missing) with mark5b.open(corrupt_file, 'rs', **self.kwargs) as fr: with pytest.warns(UserWarning, match='problem loading'): data = fr.read() data = data.reshape((-1,) + self.data.shape) assert np.all(data[:frame_nr.start].astype(int) == self.data) assert np.all(data[frame_nr.stop:].astype(int) == self.data) assert np.all(data[frame_nr] == 0.)