def test_curent_vs_past_spacing(): with pytest.deprecated_call(): mg1 = RasterModelGrid(3, 3, spacing=(5, 4)) with pytest.deprecated_call(): mg2 = RasterModelGrid(3, 3, xy_spacing=(4, 5)) assert_array_equal(mg1.x_of_node, mg2.x_of_node) assert_array_equal(mg1.y_of_node, mg2.y_of_node)
def test_warn_on_deprecated_db_port(self): with pytest.deprecated_call(): validate_config({'MONGODB_HOST': Defaults.MONGODB_HOST, 'MONGODB_PORT': 1234}) with pytest.deprecated_call(): validate_config({'MONGODB_HOST': Defaults.MONGODB_HOST, 'MONGODB_DB': 'udata'})
def test_object_depracation_warnings(recwarn): class MyObject(BaseObject): pass obj = MyObject() pytest.deprecated_call(obj.from_dict, {}) pytest.deprecated_call(obj.to_dict)
def test_query_segdb(self): with pytest.deprecated_call(): result = query_segdb(self.TEST_CLASS.query_segdb, QUERY_FLAGS[0], 0, 10) RESULT = QUERY_RESULT[QUERY_FLAGS[0]] assert isinstance(result, self.TEST_CLASS) utils.assert_segmentlist_equal(result.known, RESULT.known) utils.assert_segmentlist_equal(result.active, RESULT.active) with pytest.deprecated_call(): result2 = query_segdb(self.TEST_CLASS.query_segdb, QUERY_FLAGS[0], (0, 10)) utils.assert_flag_equal(result, result2) with pytest.deprecated_call(): result2 = query_segdb(self.TEST_CLASS.query_segdb, QUERY_FLAGS[0], SegmentList([(0, 10)])) utils.assert_flag_equal(result, result2) with pytest.deprecated_call(): with pytest.raises(ValueError): self.TEST_CLASS.query_segdb(QUERY_FLAGS[0], 1, 2, 3) with pytest.raises(ValueError): self.TEST_CLASS.query_segdb(QUERY_FLAGS[0], (1, 2, 3))
def test_median_mean(lal_func, pycbc_func): """Check that the registered "median-mean" method works Should resolve in this order to - ``pycbc_median_mean`` - ``lal_median_mean`` - `KeyError` """ # first call goes to pycbc with pytest.deprecated_call() as record: fft_median_mean.median_mean(1, 2, 3) try: assert len(record) == 2 # once for pycbc, once for mm except TypeError: # pytest < 3.9.1 pass else: assert "pycbc_median_mean" in record[-1].message.args[0] assert pycbc_func.called_with(1, 2, 3) # second call goes to lal with pytest.deprecated_call() as record: fft_median_mean.median_mean(1, 2, 3) try: assert len(record) == 3 # once for pycbc, once for lal, once for mm except TypeError: # pytest < 3.9.1 pass else: assert "lal_median_mean" in record[-1].message.args[0] assert lal_func.called_with(1, 2, 3) # third call errors with pytest.deprecated_call(), pytest.raises(KeyError): fft_median_mean.median_mean(1, 2, 3)
def testCustomSessionsDir( self, tmpdir, monkeypatch, environment, session_args): from argparse import Namespace from omero.util import get_user_dir from path import path for var in environment.keys(): if environment[var]: monkeypatch.setenv(var, tmpdir / environment.get(var)) else: monkeypatch.delenv(var, raising=False) # args.session_dir sets the sessions dir args = Namespace() if session_args: setattr(args, session_args, tmpdir / session_args) if environment.get('OMERO_SESSION_DIR') or session_args: pytest.deprecated_call(self.cli.controls['sessions'].store, args) store = self.cli.controls['sessions'].store(args) # By order of precedence if environment.get('OMERO_SESSIONDIR'): sdir = path(tmpdir) / environment.get('OMERO_SESSIONDIR') elif environment.get('OMERO_SESSION_DIR'): sdir = (path(tmpdir) / environment.get('OMERO_SESSION_DIR') / 'omero' / 'sessions') elif session_args: sdir = path(getattr(args, session_args)) / 'omero' / 'sessions' elif environment.get('OMERO_USERDIR'): sdir = path(tmpdir) / environment.get('OMERO_USERDIR') / 'sessions' else: sdir = path(get_user_dir()) / 'omero' / 'sessions' assert store.dir == sdir
def test_enable_receiving(self, monitor): """ Test that enable_receiving() is deprecated and calls out to start(). """ with mock.patch.object(monitor, 'start') as start: pytest.deprecated_call(monitor.enable_receiving) assert start.called
def test_multicall_deprecated(pm): class P1(object): @hookimpl def m(self, __multicall__, x): pass pytest.deprecated_call(pm.register, P1())
def test_curent_vs_past_origin(): with pytest.deprecated_call(): mg1 = RasterModelGrid(3, 3, origin=(10, 13)) with pytest.deprecated_call(): mg2 = RasterModelGrid(3, 3, xy_of_lower_left=(10, 13)) assert_array_equal(mg1.x_of_node, mg2.x_of_node) assert_array_equal(mg1.y_of_node, mg2.y_of_node)
def test_deprecated_call_supports_match(self): with pytest.deprecated_call(match=r"must be \d+$"): warnings.warn("value must be 42", DeprecationWarning) with pytest.raises(pytest.fail.Exception): with pytest.deprecated_call(match=r"must be \d+$"): warnings.warn("this is not here", DeprecationWarning)
def test_deprecated_call_specificity(self): other_warnings = [Warning, UserWarning, SyntaxWarning, RuntimeWarning, FutureWarning, ImportWarning, UnicodeWarning] for warning in other_warnings: f = lambda: py.std.warnings.warn(warning("hi")) with pytest.raises(AssertionError): pytest.deprecated_call(f)
def test_verify_false_deprecated(self, jws, recwarn): example_jws = ( b'eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9' b'.eyJoZWxsbyI6ICJ3b3JsZCJ9' b'.tvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8') pytest.deprecated_call(jws.decode, example_jws, verify=False)
def test_signing_with_example_keys(self, backend, vector, hash_type): curve_type = ec._CURVE_TYPES[vector['curve']] _skip_ecdsa_vector(backend, curve_type, hash_type) key = ec.EllipticCurvePrivateNumbers( vector['d'], ec.EllipticCurvePublicNumbers( vector['x'], vector['y'], curve_type() ) ).private_key(backend) assert key pkey = key.public_key() assert pkey signer = pytest.deprecated_call(key.signer, ec.ECDSA(hash_type())) signer.update(b"YELLOW SUBMARINE") signature = signer.finalize() verifier = pytest.deprecated_call( pkey.verifier, signature, ec.ECDSA(hash_type()) ) verifier.update(b"YELLOW SUBMARINE") verifier.verify()
def test_start_container_with_links(self): def call_start(): self.client.start( fake_api.FAKE_CONTAINER_ID, links={'path': 'alias'} ) pytest.deprecated_call(call_start)
def test_create_rsa_signature_ctx(self): private_key = rsa.RSAPrivateKey.generate(65537, 512, backend) pytest.deprecated_call( backend.create_rsa_signature_ctx, private_key, padding.PKCS1v15(), hashes.SHA1() )
def test_create_dsa_signature_ctx(self): params = dsa.DSAParameters.generate(1024, backend) key = dsa.DSAPrivateKey.generate(params, backend) pytest.deprecated_call( backend.create_dsa_signature_ctx, key, hashes.SHA1() )
def test_deprecated_methods(): env = TrueSkill() r1, r2, r3 = Rating(), Rating(), Rating() deprecated_call(transform_ratings, [(r1,), (r2,), (r3,)]) deprecated_call(match_quality, [(r1,), (r2,), (r3,)]) deprecated_call(env.transform_ratings, [(r1,), (r2,), (r3,)]) deprecated_call(env.match_quality, [(r1,), (r2,), (r3,)]) deprecated_call(env.Rating)
def test_start_container_with_lxc_conf(self): def call_start(): self.client.start( fake_api.FAKE_CONTAINER_ID, lxc_conf={'lxc.conf.k': 'lxc.conf.value'} ) pytest.deprecated_call(call_start)
def test_start_container_with_lxc_conf_compat(self): def call_start(): self.client.start( fake_api.FAKE_CONTAINER_ID, lxc_conf=[{'Key': 'lxc.conf.k', 'Value': 'lxc.conf.value'}] ) pytest.deprecated_call(call_start)
def test_find_edf_events_deprecation(): """Test find_edf_events deprecation.""" raw = read_raw_edf(edf_path) with pytest.deprecated_call(match="find_edf_events"): raw.find_edf_events() with pytest.deprecated_call(match="find_edf_events"): find_edf_events(raw)
def test_dict_headers(self): """ Sending headers using dict is deprecated but still valid. """ test_headers = {'key': 'value'} c = h2.connection.H2Connection() pytest.deprecated_call(c.send_headers, 1, test_headers)
def test_decode_with_optional_algorithms(self, jws): example_secret = 'secret' example_jws = ( b'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.' b'aGVsbG8gd29ybGQ.' b'SIr03zM64awWRdPrAM_61QWsZchAtgDV3pphfHPPWkI' ) pytest.deprecated_call(jws.decode, example_jws, key=example_secret)
def test_decode_with_optional_algorithms(self, jwt, payload): secret = 'secret' jwt_message = jwt.encode(payload, secret) pytest.deprecated_call( jwt.decode, jwt_message, secret )
def test_ASYNC_config_raises_deprecation(self): config = { 'ORGANIZATION_ID': '1', 'APP_ID': '1', 'SECRET_TOKEN': '1', 'ASYNC': True, } with self.settings(OPBEAT=config): pytest.deprecated_call(get_client_config)
def test_async_arg_deprecation(self): pytest.deprecated_call( Client, servers=["http://example.com"], organization_id="organization_id", app_id="app_id", secret_token="secret", async=True, )
def test_async_arg_deprecation(self): pytest.deprecated_call( Client, servers=['http://example.com'], organization_id='organization_id', app_id='app_id', secret_token='secret', async=True, )
def test_start_container_with_binds_rw(self): def call_start(): self.client.start( fake_api.FAKE_CONTAINER_ID, binds={ '/tmp': {"bind": '/mnt', "ro": False} } ) pytest.deprecated_call(call_start)
def test_transform(): with rasterio.open(raster) as src: arr = src.read(1) affine = src.transform polygons = os.path.join(DATA, 'polygons.shp') stats = zonal_stats(polygons, arr, affine=affine) stats2 = zonal_stats(polygons, arr, transform=affine.to_gdal()) assert stats == stats2 pytest.deprecated_call(zonal_stats, polygons, raster, transform=affine.to_gdal())
def test_check_fields(dans_grid1): """Check to make sure the right fields have been created.""" with pytest.deprecated_call(): FlowRouter(dans_grid1.mg) assert_array_equal(dans_grid1.z, dans_grid1.mg.at_node["topographic__elevation"]) assert_array_equal(np.zeros(25), dans_grid1.mg.at_node["drainage_area"]) assert_array_equal(np.ones(25), dans_grid1.mg.at_node["water__unit_flux_in"]) with pytest.deprecated_call(): FlowRouter(dans_grid1.mg, dans_grid1.infile) assert_array_equal(np.full(25, 2.), dans_grid1.mg.at_node["water__unit_flux_in"])
def test_implprefix_deprecated(): with pytest.deprecated_call(): pm = PluginManager("blah", implprefix="blah_") class Plugin: def blah_myhook(self, arg1): return arg1 with pytest.deprecated_call(): pm.register(Plugin())
def test_irrelevant_handlers_with_when_not_satisfied(cause_any_diff, registry, register_fn): register_fn(some_fn, reason='another-reason', when=lambda **_: False) with pytest.deprecated_call(match=r"cease using the internal registries"): handlers = registry.get_resource_changing_handlers(cause_any_diff) assert not handlers
def test_deprecated_methods(self): pytest.deprecated_call(self.zbx_container.set_type, 'items') pytest.deprecated_call(self.zbx_container.set_debug, False) pytest.deprecated_call(self.zbx_container.set_debug, True) pytest.deprecated_call(self.zbx_container.set_verbosity, False) pytest.deprecated_call(self.zbx_container.set_dryrun, False) pytest.deprecated_call(self.zbx_container.set_dryrun, True) pytest.deprecated_call(self.zbx_container.set_dryrun, None) pytest.deprecated_call(self.zbx_container.set_host, '127.0.0.1') pytest.deprecated_call(self.zbx_container.set_port, 10051)
def test_catchall_handlers_without_annotations(registry, register_fn, resource, annotations): cause = Mock(resource=resource, reason='some-reason', diff=None, body={'metadata': {'annotations': annotations}}) register_fn(some_fn, reason=None, field=None, annotations=None) with pytest.deprecated_call(match=r"use registry.resource_changing_handlers"): handlers = registry.get_resource_changing_handlers(cause) assert handlers
def test_relevant_handlers_without_field_found(cause_any_diff, registry, register_fn): register_fn(some_fn, reason='some-reason') with pytest.deprecated_call(match=r"use registry.resource_changing_handlers"): handlers = registry.get_resource_changing_handlers(cause_any_diff) assert handlers
def test_catchall_handlers_without_field_found(cause_any_diff, registry, register_fn): register_fn(some_fn, reason=None, field=None) with pytest.deprecated_call(match=r"cease using the internal registries"): handlers = registry.get_resource_changing_handlers(cause_any_diff) assert handlers
def test_irrelevant_handlers_with_field_ignored(cause_any_diff, registry, register_fn): register_fn(some_fn, reason='another-reason', field='another-field') with pytest.deprecated_call(match=r"cease using the internal registries"): handlers = registry.get_resource_changing_handlers(cause_any_diff) assert not handlers
def test_url(self, name): with pytest.deprecated_call(): p = getattr(bt, name) assert p.url == _STAMEN_URLS[name]
def register_fn(registry, resource): if isinstance(registry, OperatorRegistry): with pytest.deprecated_call(match=r"register_resource_changing_handler\(\) is deprecated"): yield functools.partial(registry.register_resource_changing_handler, resource.group, resource.version, resource.plural) else: raise Exception(f"Unsupported registry type: {registry}")
def test_copies(self, name): with pytest.deprecated_call(): p1 = getattr(bt, name) p2 = getattr(bt, name) assert p1 is not p2
def test_result_deprecated(): r = _Result(10, None) with pytest.deprecated_call(): assert r.result == 10
def test_relevant_handlers_with_filter_not_satisfied(cause_any_diff, registry, register_fn): register_fn(some_fn, reason='some-reason', when=lambda *_: False) with pytest.deprecated_call(match=r"use registry.resource_changing_handlers"): handlers = registry.get_resource_changing_handlers(cause_any_diff) assert not handlers
def test_relevant_handlers_with_annotations_not_satisfied(cause_any_diff, registry, register_fn): register_fn(some_fn, reason='some-reason', annotations={'otherannotation': None}) with pytest.deprecated_call(match=r"use registry.resource_changing_handlers"): handlers = registry.get_resource_changing_handlers(cause_any_diff) assert not handlers
def test_query_segdb(self): with pytest.deprecated_call(): result = query_segdb(self.TEST_CLASS.query_segdb, QUERY_FLAGS, 0, 10) assert isinstance(result, self.TEST_CLASS) utils.assert_dict_equal(result, QUERY_RESULT, utils.assert_flag_equal)
def test_irrelevant_handlers_with_labels_not_satisfied(cause_any_diff, registry, register_fn): register_fn(some_fn, reason='another-reason', labels={'otherlabel': None}) with pytest.deprecated_call(match=r"cease using the internal registries"): handlers = registry.get_resource_changing_handlers(cause_any_diff) assert not handlers
def test_plot(self, table): with pytest.deprecated_call(): plot = table.plot('time', 'frequency', color='snr') plot.close()
def test_catchall_handlers_with_labels_exist(registry, register_fn, resource, labels): cause = Mock(resource=resource, reason='some-reason', diff=None, body={'metadata': {'labels': labels}}) register_fn(some_fn, reason=None, field=None, labels={'somelabel': None}) with pytest.deprecated_call(match=r"use registry.resource_changing_handlers"): handlers = registry.get_resource_changing_handlers(cause) assert handlers
def test_catchall_handlers_with_field_ignored(cause_no_diff, registry, register_fn): register_fn(some_fn, reason=None, field='some-field') with pytest.deprecated_call(match=r"cease using the internal registries"): handlers = registry.get_resource_changing_handlers(cause_no_diff) assert not handlers
def test_find_best_app(test_apps): """Test if `find_best_app` behaves as expected with different combinations of input.""" # noqa: B950 script_info = ScriptInfo() class Module: app = Flask("appname") assert find_best_app(script_info, Module) == Module.app class Module: application = Flask("appname") assert find_best_app(script_info, Module) == Module.application class Module: myapp = Flask("appname") assert find_best_app(script_info, Module) == Module.myapp class Module: @staticmethod def create_app(): return Flask("appname") app = find_best_app(script_info, Module) assert isinstance(app, Flask) assert app.name == "appname" class Module: @staticmethod def create_app(foo): return Flask("appname") with pytest.deprecated_call(match="Script info"): app = find_best_app(script_info, Module) assert isinstance(app, Flask) assert app.name == "appname" class Module: @staticmethod def create_app(foo=None, script_info=None): return Flask("appname") with pytest.deprecated_call(match="script_info"): app = find_best_app(script_info, Module) assert isinstance(app, Flask) assert app.name == "appname" class Module: @staticmethod def make_app(): return Flask("appname") app = find_best_app(script_info, Module) assert isinstance(app, Flask) assert app.name == "appname" class Module: myapp = Flask("appname1") @staticmethod def create_app(): return Flask("appname2") assert find_best_app(script_info, Module) == Module.myapp class Module: myapp = Flask("appname1") @staticmethod def create_app(): return Flask("appname2") assert find_best_app(script_info, Module) == Module.myapp class Module: pass pytest.raises(NoAppException, find_best_app, script_info, Module) class Module: myapp1 = Flask("appname1") myapp2 = Flask("appname2") pytest.raises(NoAppException, find_best_app, script_info, Module) class Module: @staticmethod def create_app(foo, bar): return Flask("appname2") pytest.raises(NoAppException, find_best_app, script_info, Module) class Module: @staticmethod def create_app(): raise TypeError("bad bad factory!") pytest.raises(TypeError, find_best_app, script_info, Module)
def test_gpu_stats_monitor_cpu_machine(tmpdir): """Test GPUStatsMonitor on CPU machine.""" with pytest.raises(MisconfigurationException, match="NVIDIA driver is not installed"), pytest.deprecated_call( match="GPUStatsMonitor` callback was deprecated in v1.5" ): GPUStatsMonitor()
def test_catchall_handlers_with_labels_and_annotations_not_satisfied(registry, register_fn, resource, labels): cause = Mock(resource=resource, reason='some-reason', diff=None, body={'metadata': {'labels': labels}}) register_fn(some_fn, reason=None, field=None, labels={'somelabel': 'somevalue'}, annotations={'someannotation': 'somevalue'}) with pytest.deprecated_call(match=r"use registry.resource_changing_handlers"): handlers = registry.get_resource_changing_handlers(cause) assert not handlers
def test_auc_reorder_remove_in_v1_1_0(): with pytest.deprecated_call(match='The `reorder` parameter to `auc` has been deprecated'): _ = auc(torch.tensor([0, 1, 2, 3]), torch.tensor([0, 1, 2, 2]), reorder=True)
def test_add_column_depricated(table): with pytest.deprecated_call(): table.add_column(ibis.now().cast('date'), name='date')
def test_trainer_profiler_remove_in_v1_3_0(profiler, expected): with pytest.deprecated_call(match='will be removed in v1.3'): trainer = Trainer(profiler=profiler) assert isinstance(trainer.profiler, expected)
def test_type(self, name): with pytest.deprecated_call(): p = getattr(bt, name) assert isinstance(p, WMTSTileSource)
def wat(hdr): with pytest.deprecated_call(): return nils.which_analyze_type(hdr.binaryblock)
def test_find_delimiter_deprecated_fn(): """Test that the deprecated function still actually works""" assert properties.find_delimeter(u"key=value") == ('=', 3) deprecated_call(properties.find_delimeter, u"key=value")
def test_cancel_long_running_tasks_on_connection_loss__warning(self): c = self.get_consumer() c.app.conf.worker_cancel_long_running_tasks_on_connection_loss = False with pytest.deprecated_call(match=CANCEL_TASKS_BY_DEFAULT): c.on_connection_error_after_connected(Mock())
def test_logger_collection_versions_order(): loggers = [CustomLogger(version=v) for v in ("1", "2", "1", "3")] with pytest.deprecated_call( match="`LoggerCollection` is deprecated in v1.6"): logger = LoggerCollection(loggers) assert logger.version == f"{loggers[0].version}_{loggers[1].version}_{loggers[3].version}"
def test_relevant_handlers_with_field_ignored(cause_no_diff, registry, register_fn): register_fn(some_fn, reason='some-reason', field='some-field') with pytest.deprecated_call(match=r"use registry.resource_changing_handlers"): handlers = registry.get_resource_changing_handlers(cause_no_diff) assert not handlers
def test_logger_is_deprecated(): dataset = DatasetForTesting() with pytest.deprecated_call( match="The `Dataset.logger` attribute is deprecated"): dataset.logger