From 4a3f70dc90fca40ac4e312305ad6b51f617bf9f3 Mon Sep 17 00:00:00 2001 From: Tom Russell Date: Tue, 30 Jul 2019 10:11:19 +0100 Subject: [PATCH] Fix assert 'str' in str(ex) for pytest 5 See pytest-dev/pytest#5579 for change --- tests/controller/test_modelrun.py | 4 +-- tests/convert/test_interval.py | 16 ++++----- tests/convert/test_region.py | 4 +-- tests/data_layer/test_config_store_yaml.py | 32 ++++++++--------- tests/data_layer/test_data_array.py | 21 ++++++------ tests/data_layer/test_data_handle.py | 8 ++--- tests/data_layer/test_data_store.py | 2 +- tests/data_layer/test_data_store_csv.py | 14 ++++---- tests/data_layer/test_model_loader.py | 2 +- tests/data_layer/test_results.py | 28 +++++++-------- tests/data_layer/test_store.py | 8 ++--- tests/decision/test_decision.py | 3 +- tests/metadata/test_coordinates.py | 6 ++-- tests/metadata/test_spec.py | 40 +++++++++++----------- tests/metadata/test_timestep.py | 6 ++-- tests/model/test_dependency.py | 8 ++--- tests/model/test_sector_model.py | 2 +- tests/model/test_sos_model.py | 24 +++++++------ tests/test_water_supply.py | 10 +++--- 19 files changed, 119 insertions(+), 119 deletions(-) diff --git a/tests/controller/test_modelrun.py b/tests/controller/test_modelrun.py index d029a0a0f..dc23c6ccb 100644 --- a/tests/controller/test_modelrun.py +++ b/tests/controller/test_modelrun.py @@ -131,7 +131,7 @@ def test_builder_scenario_sosmodelrun_not_in_sosmodel(self, config_data): with raises(SmifModelRunError) as ex: builder.finish() assert "ScenarioSets {'population'} are selected in the ModelRun " \ - "configuration but not found in the SosModel configuration" in str(ex) + "configuration but not found in the SosModel configuration" in str(ex.value) class TestModelRun: @@ -152,7 +152,7 @@ def test_run_timesteps(self, config_data): store = Mock() with raises(SmifModelRunError) as ex: model_run.run(store) - assert 'No timesteps specified' in str(ex) + assert 'No timesteps specified' in str(ex.value) def test_serialize(self, config_data): """Serialise back to config dict diff --git a/tests/convert/test_interval.py b/tests/convert/test_interval.py index 2350d066e..75762dcf6 100644 --- a/tests/convert/test_interval.py +++ b/tests/convert/test_interval.py @@ -497,10 +497,10 @@ def test_equality(self): def test_invalid_set_interval(self): interval = Interval('test', ('PT0H', 'PT1H')) - with raises(ValueError) as excinfo: + with raises(ValueError) as ex: interval.interval = None msg = "A time interval must add either a single tuple or a list of tuples" - assert msg in str(excinfo) + assert msg in str(ex.value) def test_empty_interval_tuple(self): with raises(ValueError): @@ -747,19 +747,19 @@ def test_validate_intervals_passes(self, remap_months): def test_validate_intervals_fails(self, remap_months): data = remap_months data.append({'name': '5', 'interval': [('PT0H', 'PT1H')]}) - with raises(ValueError) as excinfo: + with raises(ValueError) as ex: IntervalSet('remap_months', data) - assert "Duplicate entry for hour 0 in interval set remap_months." in str(excinfo.value) + assert "Duplicate entry for hour 0 in interval set remap_months." in str(ex.value) def test_time_interval_start_before_end(self): - with raises(ValueError) as excinfo: + with raises(ValueError) as ex: Interval('backwards', ('P1Y', 'P3M')) - assert "A time interval must not end before it starts" in str(excinfo) + assert "A time interval must not end before it starts" in str(ex.value) interval = Interval('starts_ok', ('P0Y', 'P1M')) - with raises(ValueError) as excinfo: + with raises(ValueError) as ex: interval.interval = ('P2M', 'P1M') - assert "A time interval must not end before it starts" in str(excinfo) + assert "A time interval must not end before it starts" in str(ex.value) class TestIntersection: diff --git a/tests/convert/test_region.py b/tests/convert/test_region.py index 264274515..0bc485735 100644 --- a/tests/convert/test_region.py +++ b/tests/convert/test_region.py @@ -235,7 +235,7 @@ def test_must_have_unique_names(self): } ]) - assert 'Region set must have uniquely named regions' in str(ex) + assert 'Region set must have uniquely named regions' in str(ex.value) class TestRegionRegister(): @@ -247,7 +247,7 @@ def test_create(self): with raises(ValueError) as ex: register.get_entry('nonexistent') - assert "ResolutionSet 'nonexistent' not registered" in str(ex) + assert "ResolutionSet 'nonexistent' not registered" in str(ex.value) def test_convert_equal(self, register): data = np.ones(1) diff --git a/tests/data_layer/test_config_store_yaml.py b/tests/data_layer/test_config_store_yaml.py index 48b55d5aa..de282c319 100644 --- a/tests/data_layer/test_config_store_yaml.py +++ b/tests/data_layer/test_config_store_yaml.py @@ -48,7 +48,7 @@ def test_model_run_write_twice(self, model_run, config_handler): with raises(SmifDataExistsError) as ex: config_handler.write_model_run(model_run1) - assert "Model_run 'unique' already exists" in str(ex) + assert "Model_run 'unique' already exists" in str(ex.value) def test_model_run_read_one(self, model_run, config_handler): """Test reading a single model_run. @@ -70,7 +70,7 @@ def test_model_run_read_missing(self, config_handler): """ with raises(SmifDataNotFoundError) as ex: config_handler.read_model_run('missing_name') - assert "Model_run 'missing_name' not found" in str(ex) + assert "Model_run 'missing_name' not found" in str(ex.value) def test_model_run_update(self, model_run, config_handler): """Test updating a model_run description @@ -95,7 +95,7 @@ def test_model_run_update_mismatch(self, model_run, config_handler): model_run['name'] = 'model_run' with raises(SmifDataMismatchError) as ex: config_handler.update_model_run('model_run2', model_run) - assert "name 'model_run2' must match 'model_run'" in str(ex) + assert "name 'model_run2' must match 'model_run'" in str(ex.value) def test_model_run_update_missing(self, model_run, config_handler): """Test that updating a nonexistent model_run should fail @@ -105,7 +105,7 @@ def test_model_run_update_missing(self, model_run, config_handler): with raises(SmifDataNotFoundError) as ex: config_handler.update_model_run('missing_name', model_run) - assert "Model_run 'missing_name' not found" in str(ex) + assert "Model_run 'missing_name' not found" in str(ex.value) def test_model_run_delete(self, model_run, config_handler): """Test that updating a nonexistent model_run should fail @@ -126,7 +126,7 @@ def test_model_run_delete_missing(self, model_run, config_handler): """ with raises(SmifDataNotFoundError) as ex: config_handler.delete_model_run('missing_name') - assert "Model_run 'missing_name' not found" in str(ex) + assert "Model_run 'missing_name' not found" in str(ex.value) class TestSosModel: @@ -162,7 +162,7 @@ def test_sos_model_write_twice(self, get_sos_model, config_handler): with raises(SmifDataExistsError) as ex: config_handler.write_sos_model(sos_model1) - assert "Sos_model 'unique' already exists" in str(ex) + assert "Sos_model 'unique' already exists" in str(ex.value) def test_sos_model_read_one(self, get_sos_model, config_handler): """Test reading a single sos_model. @@ -184,7 +184,7 @@ def test_sos_model_read_missing(self, config_handler): """ with raises(SmifDataNotFoundError) as ex: config_handler.read_sos_model('missing_name') - assert "Sos_model 'missing_name' not found" in str(ex) + assert "Sos_model 'missing_name' not found" in str(ex.value) def test_sos_model_update(self, get_sos_model, config_handler): """Test updating a sos_model description @@ -209,7 +209,7 @@ def test_sos_model_update_mismatch(self, get_sos_model, config_handler): sos_model['name'] = 'sos_model' with raises(SmifDataMismatchError) as ex: config_handler.update_sos_model('sos_model2', sos_model) - assert "name 'sos_model2' must match 'sos_model'" in str(ex) + assert "name 'sos_model2' must match 'sos_model'" in str(ex.value) def test_sos_model_update_missing(self, get_sos_model, config_handler): """Test that updating a nonexistent sos_model should fail @@ -219,7 +219,7 @@ def test_sos_model_update_missing(self, get_sos_model, config_handler): with raises(SmifDataNotFoundError) as ex: config_handler.update_sos_model('missing_name', sos_model) - assert "Sos_model 'missing_name' not found" in str(ex) + assert "Sos_model 'missing_name' not found" in str(ex.value) def test_sos_model_delete(self, get_sos_model, config_handler): """Test that updating a nonexistent sos_model should fail @@ -240,7 +240,7 @@ def test_sos_model_delete_missing(self, get_sos_model, config_handler): """ with raises(SmifDataNotFoundError) as ex: config_handler.delete_sos_model('missing_name') - assert "Sos_model 'missing_name' not found" in str(ex) + assert "Sos_model 'missing_name' not found" in str(ex.value) class TestSectorModel: @@ -278,7 +278,7 @@ def test_sector_model_write_twice(self, get_sector_model, config_handler): with raises(SmifDataExistsError) as ex: config_handler.write_model(sector_model1) - assert "Sector_model 'unique' already exists" in str(ex) + assert "Sector_model 'unique' already exists" in str(ex.value) def test_sector_model_read_one(self, get_sector_model, config_handler): """Test reading a single sector_model. @@ -300,7 +300,7 @@ def test_sector_model_read_missing(self, config_handler): """ with raises(SmifDataNotFoundError) as ex: config_handler.read_model('missing_name') - assert "Sector_model 'missing_name' not found" in str(ex) + assert "Sector_model 'missing_name' not found" in str(ex.value) def test_sector_model_update(self, get_sector_model, config_handler): """Test updating a sector_model description @@ -327,7 +327,7 @@ def test_sector_model_update_mismatch(self, get_sector_model, config_handler): sector_model['name'] = 'sector_model' with raises(SmifDataMismatchError) as ex: config_handler.update_model('sector_model2', sector_model) - assert "name 'sector_model2' must match 'sector_model'" in str(ex) + assert "name 'sector_model2' must match 'sector_model'" in str(ex.value) def test_sector_model_update_missing(self, get_sector_model, config_handler): """Test that updating a nonexistent sector_model should fail @@ -337,7 +337,7 @@ def test_sector_model_update_missing(self, get_sector_model, config_handler): with raises(SmifDataNotFoundError) as ex: config_handler.update_model('missing_name', sector_model) - assert "Sector_model 'missing_name' not found" in str(ex) + assert "Sector_model 'missing_name' not found" in str(ex.value) def test_sector_model_delete(self, get_sector_model, config_handler): """Test that updating a nonexistent sector_model should fail @@ -354,7 +354,7 @@ def test_sector_model_delete_missing(self, get_sector_model, config_handler): """ with raises(SmifDataNotFoundError) as ex: config_handler.delete_model('missing_name') - assert "Sector_model 'missing_name' not found" in str(ex) + assert "Sector_model 'missing_name' not found" in str(ex.value) class TestScenarios: @@ -374,4 +374,4 @@ def test_read_scenario_missing(self, config_handler): """ with raises(SmifDataNotFoundError) as ex: config_handler.read_scenario('missing') - assert "Scenario 'missing' not found" in str(ex) + assert "Scenario 'missing' not found" in str(ex.value) diff --git a/tests/data_layer/test_data_array.py b/tests/data_layer/test_data_array.py index a32387247..4913b2538 100644 --- a/tests/data_layer/test_data_array.py +++ b/tests/data_layer/test_data_array.py @@ -7,7 +7,7 @@ from numpy.testing import assert_array_equal from pytest import fixture, raises from smif.data_layer.data_array import DataArray, show_null -from smif.exception import SmifDataNotFoundError, SmifDataMismatchError +from smif.exception import SmifDataMismatchError from smif.metadata import Spec @@ -226,7 +226,7 @@ def test_multi_dim_order(self): dtype='float' ) data = numpy.array([ - #4 2 + # 4 2 [1, 2], # c [5, 6], # a [9, 0] # b @@ -264,7 +264,7 @@ def test_match_metadata(self): "['region'], instead got data columns ['other'] and index names ['region']" with raises(SmifDataMismatchError) as ex: DataArray.from_df(spec, df) - assert msg in str(ex) + assert msg in str(ex.value) # may not be indexed, if columns are otherwise all okay df = pd.DataFrame([ @@ -280,7 +280,7 @@ def test_match_metadata(self): "['region'], instead got data columns ['test'] and index names [None]" with raises(SmifDataMismatchError) as ex: DataArray.from_df(spec, df) - assert msg in str(ex) + assert msg in str(ex.value) # must not have dimension labels outside of the spec dimension df = pd.DataFrame([ @@ -291,7 +291,7 @@ def test_match_metadata(self): "dimension 'region': ['extra']" with raises(SmifDataMismatchError) as ex: DataArray.from_df(spec, df) - assert msg in str(ex) + assert msg in str(ex.value) def test_scalar(self): # should handle zero-dimensional case (numpy array as scalar) @@ -327,7 +327,7 @@ def test_error_duplicate_rows_single_index(self): DataArray.from_df(spec, df) msg = "Data for 'test' contains duplicate values at [{'a': 1}]" - assert msg in str(ex) + assert msg in str(ex.value) def test_error_duplicate_rows_multi_index(self): spec = Spec( @@ -349,7 +349,7 @@ def test_error_duplicate_rows_multi_index(self): msg = "Data for 'test' contains duplicate values at [{'a': 2, 'b': 4}]" msg_alt = "Data for 'test' contains duplicate values at [{'b': 4, 'a': 2}]" - assert msg in str(ex) or msg_alt in str(ex) + assert msg in str(ex.value) or msg_alt in str(ex.value) class TestMissingData: @@ -366,7 +366,7 @@ def test_missing_data_raises(self, small_da): msg = "Data for 'test_data' had missing values - read 20 but expected 24 in " + \ "total, from dims of length {a: 2, b: 3, c: 4}" - assert msg in str(ex) + assert msg in str(ex.value) def test_missing_data_message(self, small_da): """Should check for NaNs and raise SmifDataError @@ -380,7 +380,7 @@ def test_missing_data_message(self, small_da): expected = "Data for 'test_data' had missing values - read 22 but expected 24 in " + \ "total, from dims of length {a: 2, b: 3, c: 4}" - assert expected in str(ex) + assert expected in str(ex.value) def test_missing_data_message_non_numeric(self, small_da_non_numeric): """Should check for NaNs and raise SmifDataError @@ -394,7 +394,7 @@ def test_missing_data_message_non_numeric(self, small_da_non_numeric): expected = "Data for 'test_data' had missing values - read 22 but expected 24 in " + \ "total, from dims of length {a: 2, b: 3, c: 4}" - assert expected in str(ex) + assert expected in str(ex.value) def test_no_missing_data(self, small_da): @@ -439,7 +439,6 @@ def test_missing_data_non_numeric(self, small_da_non_numeric): except TypeError: index = pd.MultiIndex(levels=levels, labels=codes, names=names) - expected = pd.DataFrame(data=numpy.array([[None]], dtype=numpy.object), index=index, columns=['test_data']) diff --git a/tests/data_layer/test_data_handle.py b/tests/data_layer/test_data_handle.py index 3f5c54a9a..b5d47d0be 100644 --- a/tests/data_layer/test_data_handle.py +++ b/tests/data_layer/test_data_handle.py @@ -469,7 +469,7 @@ def test_set_data_wrong_shape(self, mock_store, mock_model_with_conversion): msg = "Data shape (1, 2) does not match spec " \ "(2, 1)" - assert msg in str(ex) + assert msg in str(ex.value) def test_set_data_with_square_brackets(self, mock_store, mock_model): """should allow dict-like write access to output data @@ -499,10 +499,10 @@ def test_set_data_with_square_brackets_raises(self, mock_store, mock_model): spec = mock_model.outputs['gas_demand'] da = DataArray(spec, data) - with raises(TypeError) as err: + with raises(TypeError) as ex: data_handle["gas_demand"] = da - assert "Pass in a numpy array" in str(err) + assert "Pass in a numpy array" in str(ex.value) class TestDataHandleState(): @@ -624,7 +624,7 @@ def test_previous_timestep_error(self, mock_model, mock_store): data_handle = DataHandle(mock_store, 1, 2015, [2015, 2020], mock_model) with raises(SmifTimestepResolutionError) as ex: data_handle.previous_timestep - assert 'no previous timestep' in str(ex) + assert 'no previous timestep' in str(ex.value) class TestDataHandleGetResults: diff --git a/tests/data_layer/test_data_store.py b/tests/data_layer/test_data_store.py index 1bcb47aee..8f73ac56f 100644 --- a/tests/data_layer/test_data_store.py +++ b/tests/data_layer/test_data_store.py @@ -119,7 +119,7 @@ def test_read_data_array_missing_timestep(self, handler, scenario): msg = "not found for timestep 2011" with raises(SmifDataNotFoundError) as ex: handler.read_scenario_variant_data('mortality.csv', spec, 2011) - assert msg in str(ex) + assert msg in str(ex.value) def test_string_data(self, handler): spec = Spec( diff --git a/tests/data_layer/test_data_store_csv.py b/tests/data_layer/test_data_store_csv.py index 34fea7e99..7702ec570 100644 --- a/tests/data_layer/test_data_store_csv.py +++ b/tests/data_layer/test_data_store_csv.py @@ -199,7 +199,7 @@ def test_missing_timestep(self, setup_folder_structure, config_handler, msg = "Data for 'population_count' expected a column called 'timestep', instead " + \ "got data columns ['population_count', 'county', 'season', 'year'] and " + \ "index names [None]" - assert msg in str(ex) + assert msg in str(ex.value) def test_data_column_error(self, setup_folder_structure, config_handler, scenario_spec, get_scenario_data): @@ -218,7 +218,7 @@ def test_data_column_error(self, setup_folder_structure, config_handler, scenari msg = "Data for 'population_count' expected a data column called " + \ "'population_count' and index names ['county', 'season'], instead got data " + \ "columns ['population_count', 'region', 'season'] and index names [None]" - assert msg in str(ex) + assert msg in str(ex.value) def test_scenario_data_validates(self, setup_folder_structure, config_handler, get_remapped_scenario_data, scenario_spec): @@ -296,7 +296,7 @@ def test_default_data_mismatch(self, config_handler, get_sector_model_parameter_ msg = "Data for 'smart_meter_savings' should contain a single value, instead got " + \ "4 while reading from" - assert msg in str(ex) + assert msg in str(ex.value) def test_error_duplicate_rows_single_index(self, config_handler): spec = Spec( @@ -319,7 +319,7 @@ def test_error_duplicate_rows_single_index(self, config_handler): config_handler.read_model_parameter_default('default', spec) msg = "Data for 'test' contains duplicate values at [{'a': 1}]" - assert msg in str(ex) + assert msg in str(ex.value) def test_error_duplicate_rows_multi_index(self, config_handler): spec = Spec( @@ -345,7 +345,7 @@ def test_error_duplicate_rows_multi_index(self, config_handler): msg = "Data for 'test' contains duplicate values at [{'a': 2, 'b': 4}]" msg_alt = "Data for 'test' contains duplicate values at [{'b': 4, 'a': 2}]" - assert msg in str(ex) or msg_alt in str(ex) + assert msg in str(ex.value) or msg_alt in str(ex.value) def test_error_wrong_name(self, config_handler): spec = Spec( @@ -369,7 +369,7 @@ def test_error_wrong_name(self, config_handler): msg = "Data for 'test' expected a data column called 'test' and index names " + \ "['a', 'b'], instead got data columns ['wrong_name'] and index names ['a', 'b']" - assert msg in str(ex) + assert msg in str(ex.value) def test_error_not_full(self, config_handler): spec = Spec( @@ -393,7 +393,7 @@ def test_error_not_full(self, config_handler): msg = "Data for 'test' had missing values - read 1 but expected 4 in total, from " + \ "dims of length {a: 2, b: 2}" - assert msg in str(ex) + assert msg in str(ex.value) class TestResults: diff --git a/tests/data_layer/test_model_loader.py b/tests/data_layer/test_model_loader.py index b2c8be339..1763ebd2c 100644 --- a/tests/data_layer/test_model_loader.py +++ b/tests/data_layer/test_model_loader.py @@ -13,4 +13,4 @@ def test_path_not_found(): 'classname': 'WaterSupplySectorModel' }) msg = "Cannot find '/path/to/model.py' for the 'test' model" - assert msg in str(ex) + assert msg in str(ex.value) diff --git a/tests/data_layer/test_results.py b/tests/data_layer/test_results.py index ac8bfe7f9..5d3314e06 100644 --- a/tests/data_layer/test_results.py +++ b/tests/data_layer/test_results.py @@ -139,43 +139,43 @@ class TestNoResults: def test_exceptions(self, empty_store): # No arguments is not allowed - with raises(TypeError) as e: + with raises(TypeError) as ex: Results() - assert "missing 1 required positional argument: 'store'" in str(e) + assert "missing 1 required positional argument: 'store'" in str(ex.value) # Check that constructing with just a store works fine Results(store=empty_store) # Check that valid configurations do work (but expect a SmifDataNotFoundError # because the store creation will fall over - with raises(SmifDataNotFoundError) as e: + with raises(SmifDataNotFoundError) as ex: Results(store={'interface': 'local_csv', 'dir': '.'}) - assert 'Expected data folder' in str(e) + assert 'Expected data folder' in str(ex.value) - with raises(SmifDataNotFoundError) as e: + with raises(SmifDataNotFoundError) as ex: Results(store={'interface': 'local_parquet', 'dir': '.'}) - assert 'Expected data folder' in str(e) + assert 'Expected data folder' in str(ex.value) # Interface left blank will default to local_csv - with raises(SmifDataNotFoundError) as e: + with raises(SmifDataNotFoundError) as ex: Results(store={'dir': '.'}) - assert 'Expected data folder' in str(e) + assert 'Expected data folder' in str(ex.value) # Dir left blank will default to '.' - with raises(SmifDataNotFoundError) as e: + with raises(SmifDataNotFoundError) as ex: Results(store={'interface': 'local_parquet'}) - assert 'Expected data folder' in str(e) + assert 'Expected data folder' in str(ex.value) # Invalid interface will raise a ValueError - with raises(ValueError) as e: + with raises(ValueError) as ex: Results(store={'interface': 'invalid', 'dir': '.'}) - assert 'Unsupported interface "invalid"' in str(e) + assert 'Unsupported interface "invalid"' in str(ex.value) # Invalid directory will raise a ValueError - with raises(ValueError) as e: + with raises(ValueError) as ex: invalid_dir = os.path.join(os.path.dirname(__file__), 'does', 'not', 'exist') Results(store={'interface': 'local_csv', 'dir': invalid_dir}) - assert 'to be a valid directory' in str(e) + assert 'to be a valid directory' in str(ex.value) def test_list_model_runs(self, results_no_results): assert results_no_results.list_model_runs() == ['model_run_1', 'model_run_2'] diff --git a/tests/data_layer/test_store.py b/tests/data_layer/test_store.py index b471ece54..92729dce6 100644 --- a/tests/data_layer/test_store.py +++ b/tests/data_layer/test_store.py @@ -177,12 +177,12 @@ def test_prepare_scenario(self, store, scenario, scenario_2_variants, # Must raise exception if scenario defines > 1 variants with raises(SmifDataError) as ex: store.prepare_scenario(scenario_2_variants['name'], list_of_variants) - assert "must define one unique template variant" in str(ex) + assert "must define one unique template variant" in str(ex.value) # Must raise exception if scenario defines 0 variants with raises(SmifDataError) as ex: store.prepare_scenario(scenario_no_variant['name'], list_of_variants) - assert "must define one unique template variant" in str(ex) + assert "must define one unique template variant" in str(ex.value) store.prepare_scenario(scenario['name'], list_of_variants) @@ -733,7 +733,7 @@ def test_narrative_variant(self, store, sample_dimensions, expected = "Variant name 'bla' does not exist in narrative 'technology'" - assert expected in str(ex) + assert expected in str(ex.value) def test_narrative_name(self, store, sample_dimensions, get_sos_model, get_sector_model, energy_supply_sector_model, @@ -758,4 +758,4 @@ def test_narrative_name(self, store, sample_dimensions, get_sos_model, sos_model_name, 'bla', variant_name, param_name) expected = "Narrative name 'bla' does not exist in sos_model 'energy'" - assert expected in str(ex) + assert expected in str(ex.value) diff --git a/tests/decision/test_decision.py b/tests/decision/test_decision.py index b15d03a51..338341f67 100644 --- a/tests/decision/test_decision.py +++ b/tests/decision/test_decision.py @@ -2,7 +2,6 @@ from unittest.mock import Mock from pytest import fixture, raises - from smif.data_layer.store import Store from smif.decision.decision import DecisionManager, RuleBased from smif.exception import SmifDataNotFoundError @@ -102,7 +101,7 @@ def test_get_intervention(self): with raises(SmifDataNotFoundError) as ex: dm.get_intervention('z') msg = "Intervention 'z' is not found in the list of available interventions" - assert msg in str(ex) + assert msg in str(ex.value) class TestRuleBasedIterationTimestepAccounting: diff --git a/tests/metadata/test_coordinates.py b/tests/metadata/test_coordinates.py index 1aeec3fc3..54d8b0b3f 100644 --- a/tests/metadata/test_coordinates.py +++ b/tests/metadata/test_coordinates.py @@ -96,7 +96,7 @@ def test_coordinates_must_have_elements(self): """ with raises(ValueError) as ex: Coordinates('zero_d', []) - assert "must not be empty" in str(ex) + assert "must not be empty" in str(ex.value) def test_elements_must_have_name(self): """Coordinates elements must have "name" @@ -108,7 +108,7 @@ def test_elements_must_have_name(self): ] with raises(KeyError) as ex: Coordinates('fossil_fuels', elements) - assert "must have a name" in str(ex) + assert "must have a name" in str(ex.value) def test_elements_must_be_finite(self): """Only accept finite Coordinatess @@ -123,7 +123,7 @@ def natural_numbers(): with raises(ValueError) as ex: Coordinates('natural_numbers', elements) - assert "must be finite" in str(ex) + assert "must be finite" in str(ex.value) def test_eq(self): """Equality based on equivalent name and elements diff --git a/tests/metadata/test_spec.py b/tests/metadata/test_spec.py index b578b4f65..76820e36b 100644 --- a/tests/metadata/test_spec.py +++ b/tests/metadata/test_spec.py @@ -65,21 +65,21 @@ def test_rename(self, spec): def test_dim_coords_method(self, spec): assert spec.dim_coords('countries') == Coordinates('countries', ["England", "Wales"]) - with raises(KeyError) as err: + with raises(KeyError) as ex: spec.dim_coords('does not exist') - assert "Could not find dim 'does not exist' in Spec 'population'" in str(err) + assert "Could not find dim 'does not exist' in Spec 'population'" in str(ex.value) - with raises(TypeError) as err: + with raises(TypeError) as ex: spec.dim_coords(['wrong type']) - assert "Expected string as argument, instead received " in str(err) + assert "Expected string as argument, instead received " in str(ex.value) spec._dims = ['countries', 'age', 'no coords'] - with raises(KeyError) as err: + with raises(KeyError) as ex: spec.dim_coords('no coords') - assert "Coords not found for dim 'no coords', in Spec 'population'" in str(err) + assert "Coords not found for dim 'no coords', in Spec 'population'" in str(ex.value) def test_dim_names(self, spec): """Names of each coordinate in a given dimension @@ -168,7 +168,7 @@ def test_empty_dtype_error(self): name='test', coords=[Coordinates('countries', ["England", "Wales"])] ) - assert "dtype must be provided" in str(ex) + assert "dtype must be provided" in str(ex.value) def test_coords_type_error(self): """A Spec must be constructed with a list of Coordinates @@ -179,7 +179,7 @@ def test_coords_type_error(self): dtype='int', coords=["England", "Wales"] ) - assert "coords may be a dict[str,list] or a list[Coordinates]" in str(ex) + assert "coords may be a dict[str,list] or a list[Coordinates]" in str(ex.value) def test_coords_from_dict(self): """A Spec may be constructed with a dict @@ -203,7 +203,7 @@ def test_coords_from_dict_error(self): dtype='int', coords={'countries': ["England", "Wales"]} ) - assert "dims must be specified" in str(ex) + assert "dims must be specified" in str(ex.value) with raises(ValueError) as ex: Spec( @@ -212,7 +212,7 @@ def test_coords_from_dict_error(self): dims=['countries', 'age'], coords={'countries': ["England", "Wales"]} ) - assert "dims must match the keys in coords" in str(ex) + assert "dims must match the keys in coords" in str(ex.value) with raises(ValueError) as ex: Spec( @@ -224,7 +224,7 @@ def test_coords_from_dict_error(self): 'age': [">30", "<30"] } ) - assert "dims must match the keys in coords" in str(ex) + assert "dims must match the keys in coords" in str(ex.value) def test_duplicate_dims_error(self): """A Spec must not have duplicate dimension names @@ -235,7 +235,7 @@ def test_duplicate_dims_error(self): dims=['countries', 'countries'], coords={'countries': ["Scotland", "Northern Ireland"]} ) - assert "duplicate dims" in str(ex) + assert "duplicate dims" in str(ex.value) with raises(ValueError) as ex: Spec( @@ -245,7 +245,7 @@ def test_duplicate_dims_error(self): Coordinates('countries', ['Scotland', 'Northern Ireland']), ] ) - assert "duplicate dims" in str(ex) + assert "duplicate dims" in str(ex.value) def test_coords_from_list_error(self): """A Spec constructed with a dict must have dims @@ -257,7 +257,7 @@ def test_coords_from_list_error(self): coords=[Coordinates('countries', ["England", "Wales"])], dims=['countries'] ) - assert "dims are derived" in str(ex) + assert "dims are derived" in str(ex.value) def test_ranges_must_be_list_like(self): """Absolute and expected ranges must be list or tuple @@ -267,14 +267,14 @@ def test_ranges_must_be_list_like(self): dtype='int', abs_range='string should fail' ) - assert "range must be a list or tuple" in str(ex) + assert "range must be a list or tuple" in str(ex.value) with raises(TypeError) as ex: Spec( dtype='int', exp_range='string should fail' ) - assert "range must be a list or tuple" in str(ex) + assert "range must be a list or tuple" in str(ex.value) def test_ranges_must_be_len_two(self): """Absolute and expected ranges must be length two (min and max) @@ -284,14 +284,14 @@ def test_ranges_must_be_len_two(self): dtype='int', abs_range=[0] ) - assert "range must have min and max values only" in str(ex) + assert "range must have min and max values only" in str(ex.value) with raises(ValueError) as ex: Spec( dtype='int', exp_range=[0, 1, 2] ) - assert "range must have min and max values only" in str(ex) + assert "range must have min and max values only" in str(ex.value) def test_ranges_must_be_min_max(self): """Absolute and expected ranges must be in order @@ -301,14 +301,14 @@ def test_ranges_must_be_min_max(self): dtype='int', abs_range=[2, 1] ) - assert "min value must be smaller than max value" in str(ex) + assert "min value must be smaller than max value" in str(ex.value) with raises(ValueError) as ex: Spec( dtype='int', exp_range=[2, 1] ) - assert "min value must be smaller than max value" in str(ex) + assert "min value must be smaller than max value" in str(ex.value) def test_eq(self): """Equality based on equivalent dtype, dims, coords, unit diff --git a/tests/metadata/test_timestep.py b/tests/metadata/test_timestep.py index e167fcf61..2f46e85bd 100644 --- a/tests/metadata/test_timestep.py +++ b/tests/metadata/test_timestep.py @@ -15,7 +15,7 @@ def test_create_from_name(self): assert RelativeTimestep.PREVIOUS == RelativeTimestep.from_name("PREVIOUS") with raises(ValueError) as ex: RelativeTimestep.from_name("UNKNOWN") - assert "Relative timestep 'UNKNOWN' is not recognised" in str(ex) + assert "Relative timestep 'UNKNOWN' is not recognised" in str(ex.value) def test_resolve(self): """Should be able to resolve current/previous/base timesteps @@ -32,9 +32,9 @@ def test_resolve(self): with raises(SmifTimestepResolutionError) as ex: rel.resolve_relative_to(99, timesteps) - assert "is not present" in str(ex) + assert "is not present" in str(ex.value) rel = RelativeTimestep.PREVIOUS with raises(SmifTimestepResolutionError) as ex: rel.resolve_relative_to(0, timesteps) - assert "has no previous timestep" in str(ex) + assert "has no previous timestep" in str(ex.value) diff --git a/tests/model/test_dependency.py b/tests/model/test_dependency.py index edf2db767..f7a263d2d 100644 --- a/tests/model/test_dependency.py +++ b/tests/model/test_dependency.py @@ -87,7 +87,7 @@ def test_create_with_identical_meta(): ) with raises(ValueError) as ex: Dependency(Mock(), source, Mock(), b_sink) - assert 'mismatched dtype' in str(ex) + assert 'mismatched dtype' in str(ex.value) c_sink = Spec( name='sink', @@ -98,7 +98,7 @@ def test_create_with_identical_meta(): ) with raises(ValueError) as ex: Dependency(Mock(), source, Mock(), c_sink) - assert 'mismatched dims' in str(ex) + assert 'mismatched dims' in str(ex.value) d_sink = Spec( name='sink', @@ -109,7 +109,7 @@ def test_create_with_identical_meta(): ) with raises(ValueError) as ex: Dependency(Mock(), source, Mock(), d_sink) - assert 'mismatched coords' in str(ex) + assert 'mismatched coords' in str(ex.value) e_sink = Spec( name='sink', @@ -120,7 +120,7 @@ def test_create_with_identical_meta(): ) with raises(ValueError) as ex: Dependency(Mock(), source, Mock(), e_sink) - assert 'mismatched unit' in str(ex) + assert 'mismatched unit' in str(ex.value) def test_repr(dep): diff --git a/tests/model/test_sector_model.py b/tests/model/test_sector_model.py index 3e10b5f49..e2d9eb6c1 100644 --- a/tests/model/test_sector_model.py +++ b/tests/model/test_sector_model.py @@ -130,7 +130,7 @@ class TestSectorModel(): def test_abstract(self): with raises(TypeError) as ex: SectorModel('cannot_instantiate') - assert "Can't instantiate abstract class" in str(ex) + assert "Can't instantiate abstract class" in str(ex.value) def test_construct(self, sector_model): assert sector_model.description == 'a description' diff --git a/tests/model/test_sos_model.py b/tests/model/test_sos_model.py index b74f88221..38a03267e 100644 --- a/tests/model/test_sos_model.py +++ b/tests/model/test_sos_model.py @@ -407,7 +407,7 @@ def test_compose(self, sos_model): with raises(AssertionError) as ex: sos_model.add_model(SosModel('test')) msg = "Only Models can be added to a SosModel (and SosModels cannot be nested)" - assert msg in str(ex) + assert msg in str(ex.value) def test_as_dict(self, sos_model): """as_dict correctly returns configuration as a dictionary, with child models as_dict @@ -541,7 +541,8 @@ def test_dependency_duplicate(self, sos_model, scenario_model, sector_model): sos_model.add_dependency( scenario_model, 'precipitation', sector_model, 'precipitation') - assert "Could not add dependency: input 'precipitation' already provided" in str(ex) + assert "Could not add dependency: input 'precipitation' already provided" in \ + str(ex.value) def test_dependency_not_present(self, sos_model, scenario_model, energy_model): """Should fail with missing input/output @@ -551,13 +552,13 @@ def test_dependency_not_present(self, sos_model, scenario_model, energy_model): sos_model.add_dependency( scenario_model, 'not_present', energy_model, 'electricity_demand_input') msg = "Output 'not_present' is not defined in '{}'".format(scenario_model.name) - assert msg in str(ex) + assert msg in str(ex.value) with raises(SmifValidationError) as ex: sos_model.add_dependency( scenario_model, 'precipitation', energy_model, 'incorrect_name') msg = "Input 'incorrect_name' is not defined in '{}'".format(energy_model.name) - assert msg in str(ex) + assert msg in str(ex.value) def test_dependency_model_not_exist(self, sos_model, scenario_model, energy_model): """Should fail with a SmifConfigurationError @@ -571,7 +572,7 @@ def test_dependency_model_not_exist(self, sos_model, scenario_model, energy_mode scenario_model, 'precipitation', missing_sink, 'does not matter' ) msg = "Sink model 'test_sink_model' does not exist in list of models" - assert msg in str(ex) + assert msg in str(ex.value) missing_source = Mock() type(missing_source).name = PropertyMock(return_value='test_source_model') @@ -581,7 +582,7 @@ def test_dependency_model_not_exist(self, sos_model, scenario_model, energy_mode missing_source, 'does not matter', energy_model, 'electricity_demand_input' ) msg = "Source model 'test_source_model' does not exist in list of models" - assert msg in str(ex) + assert msg in str(ex.value) def test_data_not_present(self, sos_model_dict, sector_model): """Raise a NotImplementedError if an input is defined but no dependency links @@ -606,7 +607,7 @@ def test_undefined_unit_conversion(self, sos_model_dict, sector_model, scenario_ with raises(ValueError) as ex: SosModel.from_dict(sos_model_dict, [sector_model, scenario_model, economic_model]) - assert "ml!=incompatible" in str(ex) + assert "ml!=incompatible" in str(ex.value) def test_invalid_unit_conversion(self, sos_model_dict, sector_model, scenario_model, economic_model): @@ -671,19 +672,20 @@ def test_add_narrative_raises_for_incorrect_parameter(self, sos_model, narrative narrative['provides'] = {'water_supply': ['no_such_parameter']} - with raises(SmifDataMismatchError) as err: + with raises(SmifDataMismatchError) as ex: sos_model.add_narrative(narrative) - assert "Parameter 'no_such_parameter' does not exist in 'water_supply'" in str(err) + assert "Parameter 'no_such_parameter' does not exist in 'water_supply'" in \ + str(ex.value) def test_add_narrative_raises_for_wrong_model(self, sos_model, narrative): narrative['provides'] = {'not_a_model': ['test_parameter']} - with raises(SmifDataMismatchError) as err: + with raises(SmifDataMismatchError) as ex: sos_model.add_narrative(narrative) - assert "'not_a_model' does not exist in 'test_sos_model'" in str(err) + assert "'not_a_model' does not exist in 'test_sos_model'" in str(ex.value) def test_narratives_in_as_dict(self, sos_model, narrative): diff --git a/tests/test_water_supply.py b/tests/test_water_supply.py index b4376afa9..8afd5d2ff 100644 --- a/tests/test_water_supply.py +++ b/tests/test_water_supply.py @@ -9,9 +9,9 @@ from pytest import fixture, raises -from .fixtures.water_supply import (ExampleWaterSupplySimulationModel, - ExampleWaterSupplySimulationModelWithReservoir, - process_results) +from .fixtures.water_supply import ( + ExampleWaterSupplySimulationModel, + ExampleWaterSupplySimulationModelWithReservoir, process_results) @fixture(scope='function') @@ -56,7 +56,7 @@ def test_water_supply_with_reservoir_negative_level(): msg = "Reservoir level cannot be negative" with raises(ValueError) as ex: ExampleWaterSupplySimulationModelWithReservoir(raininess, reservoir_level) - assert msg in str(ex) + assert msg in str(ex.value) def test_process_results(): @@ -79,7 +79,7 @@ def test_raininess_oracle_out_of_range(): msg = "timestep 2051 is outside of the range [2010, 2050]" with raises(AssertionError) as ex: a_raininess_oracle(2051) - assert msg in str(ex) + assert msg in str(ex.value) def test_simulate_rain_cost_python():