class TestImageLinkBlock: def test_properties(self): url = 'http://localhost/image.png' block = ImageLinkBlock(url=url) assert block.type == BlockType.IMAGE_LINK assert block.url == url @pytest.mark.parametrize('attributes,raises', [ (dict(), pytest.raises(ValidationError)), (dict(type='####', url='http://localhost/image.png'), pytest.raises(ValidationError)), (dict(url='$*(#Y$('), pytest.raises(ValidationError)), (dict(url='http://localhost'), does_not_raise()), (dict(url='http://localhost/image.png'), does_not_raise()), ]) def test_validator(self, attributes, raises): with raises: ImageLinkBlock(**attributes) def test_to_dict(self): assert ImageLinkBlock(url='http://localhost/image.png').dict( exclude_none=True) == { "type": "image_link", "url": "http://localhost/image.png", } def test_to_json(self): assert ImageLinkBlock(url='http://localhost/image.png').json( exclude_none=True ) == '{"type": "image_link", "url": "http://localhost/image.png"}'
class TestGetDestination: @pytest.mark.parametrize( "parent,raising", [ (flywheel.Subject(label="test"), does_not_raise()), (flywheel.Session(label="test"), does_not_raise()), (flywheel.Group(label="test"), pytest.raises(ValueError)), (flywheel.Project(label="test"), pytest.raises(ValueError)), (flywheel.Acquisition(label="test"), pytest.raises(ValueError)), ], ) def test_container(self, sdk_mock, parent, raising): container = flywheel.models.analysis_output.AnalysisOutput( parent=parent, id="test" ) sdk_mock.get_analysis.return_value = container sdk_mock.get.return_value = parent with raising: dest = get_destination(sdk_mock, "test") sdk_mock.get_analysis.assert_called_once_with("test") # assert dest.__class__ == parent.__class__ assert isinstance(dest, parent.__class__) def test_analysis_does_not_exist(self, sdk_mock): container = flywheel.models.analysis_output.AnalysisOutput( parent=flywheel.Project(), id="test" ) sdk_mock.get.side_effect = flywheel.rest.ApiException(status=404) sdk_mock.get_analysis.return_value = container with pytest.raises(flywheel.rest.ApiException): dest = get_destination(sdk_mock, "test") assert isinstance(dest, flywheel.Project)
def left_metric_wrong_group_test_data(self): smoke_data = [ dict(group=SpecialEuclidean(2), expected=does_not_raise()), dict(group=SpecialEuclidean(3), expected=does_not_raise()), dict( group=SpecialEuclidean(2, point_type="vector"), expected=pytest.raises(ValueError), ), dict(group=SpecialOrthogonal(3), expected=pytest.raises(ValueError)), ] return self.generate_tests(smoke_data)
def test_initializing_repository_without_git_repo_does_not_raise_error( tmp_path: str, ) -> None: """Check initializing repository without git repository does not raise error""" with does_not_raise(): repo = Repository(str(tmp_path)) assert repo.git_wrapper is None
def valid_axis_tester(Op): with pytest.raises(TypeError): Op(1.5) x = [tensor3()] * Op.nin with does_not_raise(): Op(2)(*x) with pytest.raises(ValueError): Op(3)(*x) with does_not_raise(): Op(-3)(*x) with pytest.raises(ValueError): Op(-4)(*x)
def test_timer_get_non_existent(self, name): if name == self.default_timer: condition = does_not_raise() else: condition = pytest.raises(IndexError) with condition: logger.get_timer(name)
def test_cuda_array_interface_interop_out(dtype, module): expectation = does_not_raise() if dtype == "str": expectation = pytest.raises(NotImplementedError) if module == "cupy": module_constructor = cupy.asarray def to_host_function(x): return cupy.asnumpy(x) elif module == "numba": module_constructor = cuda.as_cuda_array def to_host_function(x): return x.copy_to_host() with expectation: np_data = np.arange(10).astype(dtype) cudf_data = cudf.Series(np_data) assert isinstance(cudf_data.__cuda_array_interface__, dict) module_data = module_constructor(cudf_data) got = to_host_function(module_data) expect = np_data assert_eq(expect, got)
class TestLabelBlock: def test_properties(self): block = LabelBlock(text="msg", markdown=True) assert block.type == BlockType.LABEL assert block.text == 'msg' assert block.markdown is True @pytest.mark.parametrize( 'attributes,raises', [ (dict(), pytest.raises(ValidationError)), (dict(type='####'), pytest.raises(ValidationError)), (dict(text='msg'), pytest.raises(ValidationError)), (dict(text=''), pytest.raises(ValidationError)), (dict(text='a' * 201), pytest.raises(ValidationError)), (dict(markdown=True), pytest.raises(ValidationError)), (dict(text='msg', markdown=True), does_not_raise()), ], ) def test_validator(self, attributes, raises): with raises: LabelBlock(**attributes) def test_to_dict(self): assert LabelBlock(text="msg", markdown=True).dict(exclude_none=True) == { "type": "label", "text": "msg", "markdown": True, } def test_to_json(self): assert LabelBlock(text="msg", markdown=True).json( exclude_none=True ) == '{"type": "label", "text": "msg", "markdown": true}'
def test_runner_stop_dont_raise_runtime_error(cancel_all_tasks_mock): cancel_all_tasks_mock.side_effect = RuntimeError("faiô!") runner = LoaferRunner() with does_not_raise(): runner.loop.stop() runner.stop()
def test_cuda_array_interface_interop_out_masked(dtype, module): expectation = does_not_raise() if module == "cupy": pytest.skip("cupy doesn't support version 1 of " "`__cuda_array_interface__` yet") module_constructor = cupy.asarray def to_host_function(x): return cupy.asnumpy(x) elif module == "numba": expectation = pytest.raises(NotImplementedError) module_constructor = cuda.as_cuda_array def to_host_function(x): return x.copy_to_host() np_data = np.arange(10).astype("float64") np_data[[0, 2, 4, 6, 8]] = np.nan with expectation: cudf_data = cudf.Series(np_data).astype(dtype) assert isinstance(cudf_data.__cuda_array_interface__, dict) module_data = module_constructor(cudf_data) # noqa: F841
def tangent_extrinsic_to_spherical_raises_test_data(self): smoke_data = [] dim_list = [2, 3] for dim in dim_list: space = Hypersphere(dim) base_point = space.random_point() tangent_vec = space.to_tangent(space.random_point(), base_point) if dim == 2: expected = does_not_raise() smoke_data.append( dict( dim=2, tangent_vec=tangent_vec, base_point=None, base_point_spherical=None, expected=pytest.raises(ValueError), ) ) else: expected = pytest.raises(NotImplementedError) smoke_data.append( dict( dim=dim, tangent_vec=tangent_vec, base_point=base_point, base_point_spherical=None, expected=expected, ) ) return self.generate_tests(smoke_data)
def test_cuda_array_interface_interop_in(dtype, module): np_data = np.arange(10).astype(dtype) expectation = does_not_raise() if module == "cupy": if not _have_cupy: pytest.skip("no cupy") module_constructor = cupy.array if dtype in datetime_dtypes: expectation = pytest.raises(ValueError) elif module == "numba": module_constructor = cuda.to_device with expectation: module_data = module_constructor(np_data) pd_data = pd.Series(np_data) # Test using a specific function for __cuda_array_interface__ here cudf_data = cudf.Series(module_data) assert_eq(pd_data, cudf_data) gdf = cudf.DataFrame() gdf["test"] = module_data pd_data.name = "test" assert_eq(pd_data, gdf["test"])
class TestGetClassToBook: @pytest.mark.parametrize( "classes, target_time, class_name, expectation", ( ( [{ "id": 123, "timeid": "1700_60", "className": "foo" }], "1700", "foo", does_not_raise(), ), ( [ { "id": 123, "timeid": "1700_60", "className": "foo" }, { "id": 123, "timeid": "1700_60", "className": "foo" }, ], "1700", "foo", does_not_raise(), ), ( [{ "id": 123, "timeid": "1100_60", "className": "foo" }], "1700", "foo", pytest.raises(NoBookingGoal), ), ), ) def test_get_class_to_book(self, classes, target_time, class_name, expectation): with expectation: assert get_class_to_book(classes, target_time, class_name) == 123
def test_image_fetch(harness, oci_resource_data): harness.begin() with pytest.raises(MissingResourceError): harness.charm.image.fetch() harness.add_oci_resource(**oci_resource_data) with does_not_raise(): harness.charm.image.fetch()
def test_check_predicates(user, predicates, raises, error_message): if raises is None: ctx = does_not_raise() else: ctx = pytest.raises(ParselglossyError, match="|".join(error_message)) with ctx: check_predicates(incoming=user, predicates=predicates)
def test_get_step_context_output_for_step_with_one_output( step_context_with_single_output, ): """Tests that getting the artifact uri or materializer for a step context with a single output does NOT raise an exception.""" with does_not_raise(): step_context_with_single_output.get_output_artifact_uri() step_context_with_single_output.get_output_materializer()
def test_get_step_context_output_for_non_existing_output_key( step_context_with_two_outputs, ): """Tests that getting the artifact uri or materializer for an existing output does NOT raise an exception.""" with does_not_raise(): step_context_with_two_outputs.get_output_artifact_uri("output_1") step_context_with_two_outputs.get_output_materializer("output_2")
def data_size_expectation_builder(data, nan_null_param=False): if nan_null_param and np.isnan(data).any(): return pytest.raises((ValueError, )) if data.size > 0: return does_not_raise() else: return pytest.raises((ValueError, IndexError))
def test_storage(tmpdir, engine, kw, ex): if ex is None: ex = does_not_raise() with ex: storage = create_storage(tmpdir=tmpdir, engine=engine, **kw) if isinstance(storage, FileStorage): _test_hexdigeststorage(storage) if isinstance(storage, JsonStorage): _test_jsonstorage(storage)
def test_input_output_pairs(seqs, expected): """Test that the generation of input-output pairs works as expected.""" with expected: assert input_output_pairs(seqs) is not None if expected == does_not_raise(): xs, ys = input_output_pairs(seqs) assert xs.shape == (len(seqs), len(seqs[0]) + 1, 10) assert ys.shape == (len(seqs), len(seqs[0]) + 1, 25)
def test_input_output_pairs(seqs, expected): with expected: assert input_output_pairs(seqs) is not None if expected == does_not_raise(): xs, ys = input_output_pairs(seqs) assert xs.shape == (len(seqs), len(seqs[0]) + 1, 10) assert ys.shape == (len(seqs), len(seqs[0]) + 1, 25)
def test_assert_valid_raster(file_path, exp_error): exp_exception = pytest.raises( LaymanError) if exp_error else does_not_raise() with exp_exception as exc_info: gdal.assert_valid_raster(file_path) if exp_error: test_util.assert_error(exp_error, exc_info)
def test_validation_prediction_recorder(config): with TemporaryDirectory() as temp_folder: recorder = ValidationPredictionRecorder( output_data_dir=temp_folder, **config['recorder_kwargs'] ) for call_config in config['record_calls']: with call_config.get('record_raises', does_not_raise()): recorder.record(*call_config['args']) if call_config.get('record_raises', None) is not None: return with config.get('save_raises', does_not_raise()): recorder.save() if config.get('save_raises', None) is not None: return df = pd.read_csv(os.path.join(temp_folder, PREDICTIONS_OUTPUT_FILE), header=None) assert df.equals(config['expected_output'])
class TestToNormalize(object): """ to_normalizeのテスト """ lat_data = [ # @formatter:off (-000.000000000001, None, pytest.raises(StackRouteException)), (+000.000000000000, -90.000000000000, does_not_raise()), (+000.000000000001, -89.999999999999, does_not_raise()), (+090.000000000000, +00.000000000000, does_not_raise()), (+179.999999999999, +89.999999999999, does_not_raise()), (+180.000000000000, +90.000000000000, does_not_raise()), (+180.000000000001, None, pytest.raises(StackRouteException)) # @formatter:on ] @pytest.mark.parametrize('lat,expected,expectation', lat_data) def test_to_normalize_default(self, lat, expected, expectation): with expectation: assert stack_route._to_normalize(d=lat) == expected @pytest.mark.parametrize('lat,expected,expectation', lat_data) def test_to_normalize_lat(self, lat, expected, expectation): with expectation: assert stack_route._to_normalize(d=lat, is_lon=False) == expected lon_data = [ # @formatter:off (-000.000000000001, None, pytest.raises(StackRouteException)), (+000.000000000000, -180.000000000000, does_not_raise()), (+000.000000000001, -179.999999999999, does_not_raise()), (+180.000000000000, +000.000000000000, does_not_raise()), (+359.999999999999, +179.999999999999, does_not_raise()), (+360.000000000000, +180.000000000000, does_not_raise()), (+360.000000000001, None, pytest.raises(StackRouteException)) # @formatter:on ] @pytest.mark.parametrize('lon,expected,expectation', lon_data) def test_to_normalize_lon(self, lon, expected, expectation): with expectation: assert stack_route._to_normalize(d=lon, is_lon=True) == expected
def test_market_initialization(valid_binary_address, first_address, second_address): exception = pytest.raises(ValueError) if valid_binary_address == first_address == second_address: exception = does_not_raise() with exception: TokenPair(base_token=first_address, quote_token=second_address)
def test_import_csv(self, contacts, contacts_expectation): listings = 'sample_data/listings.csv' raise_exp = does_not_raise() if not isinstance(contacts_expectation, does_not_raise): raise_exp = contacts_expectation with raise_exp: listings_cv = create_path(listings) contacts_cv = create_path(contacts) listings_df, contacts_df = import_csv(listings_cv, contacts_cv)
def test_access_step_component_after_calling(): """Tests that a step component exists after the step was called.""" @step def some_step(): pass step_instance = some_step() step_instance() with does_not_raise(): _ = step_instance.component
def test_rep_same_lengths(seqs, expected): params = load_params()[1] with expected: assert rep_same_lengths(seqs, params, apply_fun) is not None if expected == does_not_raise(): h_final, c_final, h_avg = rep_same_lengths(seqs, params, apply_fun) assert h_final.shape == (len(seqs), 1900) assert c_final.shape == (len(seqs), 1900) assert h_avg.shape == (len(seqs), 1900)
def test_rep_arbitrary_lengths(seqs, expected): params = load_params_1900() with expected: assert rep_arbitrary_lengths(seqs, params) is not None if expected == does_not_raise(): h_final, c_final, h_avg = rep_arbitrary_lengths(seqs, params) assert h_final.shape == (len(seqs), 1900) assert c_final.shape == (len(seqs), 1900) assert h_avg.shape == (len(seqs), 1900)
def test_initialize_step_with_config(): """Tests that a step can only be initialized with it's defined config class.""" class StepConfig(BaseStepConfig): pass class DifferentConfig(BaseStepConfig): pass @step def step_with_config(config: StepConfig) -> None: pass # initialize with wrong config classes with pytest.raises(StepInterfaceError): step_with_config(config=BaseStepConfig()) # noqa with pytest.raises(StepInterfaceError): step_with_config(config=DifferentConfig()) # noqa # initialize with wrong key with pytest.raises(StepInterfaceError): step_with_config(wrong_config_key=StepConfig()) # noqa # initializing with correct key should work with does_not_raise(): step_with_config(config=StepConfig()) # initializing as non-kwarg should work as well with does_not_raise(): step_with_config(StepConfig()) # initializing with multiple args or kwargs should fail with pytest.raises(StepInterfaceError): step_with_config(StepConfig(), config=StepConfig()) with pytest.raises(StepInterfaceError): step_with_config(StepConfig(), StepConfig()) with pytest.raises(StepInterfaceError): step_with_config(config=StepConfig(), config2=StepConfig())