From 503f43270a5a2fb958f0ab403080aa0712f3762a Mon Sep 17 00:00:00 2001 From: Tjalling-dejong Date: Wed, 13 Nov 2024 17:57:59 +0100 Subject: [PATCH 1/9] removed unnecessary try except statements --- tests/TestUtils.py | 3 - tests/test_Import.py | 40 ++++-------- tests/test_acceptance.py | 118 +++++++++++++---------------------- tests/test_crosssection.py | 63 ++++++------------- tests/test_fm2profrunner.py | 98 ++++++++++------------------- tests/test_functions.py | 16 +---- tests/test_inifile.py | 20 ++---- tests/test_main.py | 34 +++++----- tests/test_maskoutputfile.py | 83 ++++++++---------------- tests/test_utils.py | 84 ++++++++----------------- 10 files changed, 181 insertions(+), 378 deletions(-) diff --git a/tests/TestUtils.py b/tests/TestUtils.py index 6cfc4243..fc5b2499 100644 --- a/tests/TestUtils.py +++ b/tests/TestUtils.py @@ -1,9 +1,6 @@ import contextlib import os -import shutil -import sys from pathlib import Path -from typing import List import pytest diff --git a/tests/test_Import.py b/tests/test_Import.py index ce63e0f0..a046cf1e 100644 --- a/tests/test_Import.py +++ b/tests/test_Import.py @@ -1,8 +1,3 @@ -import numbers -import os -import shutil -import sys -import unittest from pathlib import Path import pytest @@ -89,11 +84,9 @@ def test_when_given_expected_arguments_then_object_is_created(self): css_data, ] return_fm_model_data = None - # 2. Run test - try: - return_fm_model_data = FmModelData(arg_list) - except: - pytest.fail("No exception expected but was thrown") + + # 2. Run test + return_fm_model_data = FmModelData(arg_list) # 4. Verify final expectations assert return_fm_model_data is not None @@ -127,12 +120,9 @@ def test_when_given_data_dictionary_then_css_data_list_is_set(self): # 2. Set expectations expected_css_data_list = [{dummy_key: 0}, {dummy_key: 1}] - # 3. Run test - try: - return_fm_model_data = FmModelData(arg_list) - except: - pytest.fail("No exception expected but was thrown") - + # 3. Run test + return_fm_model_data = FmModelData(arg_list) + # 4. Verify final expectations assert return_fm_model_data is not None assert return_fm_model_data.css_data_list != css_data_dict @@ -153,11 +143,8 @@ def test_when_given_dictionary_then_returns_list(self): expected_list = [{dummy_key: 0}, {dummy_key: 1}] # 3. Run test - try: - return_list = FmModelData.get_ordered_css_list(test_dict) - except: - pytest.fail("No exception expected but was thrown") - + return_list = FmModelData.get_ordered_css_list(test_dict) + # 4. Verify final expectations assert return_list is not None assert return_list == expected_list, ( @@ -170,18 +157,13 @@ def test_when_given_dictionary_then_returns_list(self): def test_when_given_unexpected_value_then_returns_empty_list(self, test_dict): # 1. Set up test_data return_list = None - dummy_key = "dummyKey" - dummy_values = [0, 1] # 2. Run test expected_list = [] - # 3. Run test - try: - return_list = FmModelData.get_ordered_css_list(test_dict) - except: - pytest.fail("No exception expected but was thrown") - + # 3. Run test + return_list = FmModelData.get_ordered_css_list(test_dict) + # 4. Verify final expectations assert return_list is not None assert return_list == expected_list, ( diff --git a/tests/test_acceptance.py b/tests/test_acceptance.py index 3db390db..519c5959 100644 --- a/tests/test_acceptance.py +++ b/tests/test_acceptance.py @@ -1,12 +1,9 @@ import io import os import shutil -import sys -import unittest from pathlib import Path from typing import Optional -import matplotlib.pyplot as plt import pytest from fm2prof.Fm2ProfRunner import Fm2ProfRunner @@ -374,21 +371,17 @@ def test_when_fm2prof_output_then_use_it_for_sobek_model_input(self): fm_dir = str(waal_test_folder / "Model_FM") fm2prof_dir = _get_test_case_output_dir(_waal_case) - result_figures = [] # 2. Try to compare. - try: - waal_comparer = CompareWaalModel() - output_1d, _ = waal_comparer._run_waal_1d_model( - case_name=_waal_case, - results_dir=fm2prof_dir, - sobek_dir=sobek_dir, - fm_dir=fm_dir, - ) - except Exception as e_info: - pytest.fail( - "No exception expected but was thrown " + "{}.".format(str(e_info)) - ) + + waal_comparer = CompareWaalModel() + output_1d, _ = waal_comparer._run_waal_1d_model( + case_name=_waal_case, + results_dir=fm2prof_dir, + sobek_dir=sobek_dir, + fm_dir=fm_dir, + ) + # 3. Verify final expectations assert output_1d @@ -406,18 +399,14 @@ def test_when_sobek_output_exist_then_create_figures(self): result_figures = [] # 2. Try to compare. - try: - waal_comparer = CompareWaalModel() - result_figures = waal_comparer._compare_waal( - case_name=_waal_case, - results_dir=fm2prof_dir, - sobek_dir=sobek_dir, - fm_dir=fm_dir, - ) - except Exception as e_info: - pytest.fail( - "No exception expected but was thrown " + "{}.".format(str(e_info)) - ) + + waal_comparer = CompareWaalModel() + result_figures = waal_comparer._compare_waal( + case_name=_waal_case, + results_dir=fm2prof_dir, + sobek_dir=sobek_dir, + fm_dir=fm_dir, + ) # 3. Verify final expectations assert result_figures @@ -451,14 +440,10 @@ def test_when_output_exists_then_compare_waal_model_volume(self, case_name: str) if not os.path.exists(fm2prof_fig_dir): os.makedirs(fm2prof_fig_dir) - # 3. Run - try: - waal_comparer = CompareWaalModel() - waal_comparer._compare_volume(case_name, input_volume_file, fm2prof_fig_dir) - except Exception as e_info: - pytest.fail( - "No exception expected but was thrown " + "{}.".format(str(e_info)) - ) + # 3. Run + waal_comparer = CompareWaalModel() + waal_comparer._compare_volume(case_name, input_volume_file, fm2prof_fig_dir) + # 4. Final expectation assert os.listdir( @@ -570,16 +555,12 @@ def ARCHIVED_test_compare_generic_model_geometry(self, case_name: str): if not tzw_values or tzw_values is None: pytest.fail("Test failed, no values retrieved for {}".format(case_name)) - try: - generic_comparer = CompareIdealizedModel() - generic_comparer._compare_css( - case_name, tzw_values, input_geometry_file, fm2prof_fig_dir - ) - except Exception as e_info: - pytest.fail( - "No exception expected but was thrown " + "{}.".format(str(e_info)) - ) - + + generic_comparer = CompareIdealizedModel() + generic_comparer._compare_css( + case_name, tzw_values, input_geometry_file, fm2prof_fig_dir + ) + # 4. Final expectation assert os.listdir( fm2prof_fig_dir @@ -616,15 +597,11 @@ def ARCHIVED_test_when_output_exists_then_compare_generic_model_roughness( if not tzw_values or tzw_values is None: pytest.fail("Test failed, no values retrieved for {}".format(case_name)) - try: - generic_comparer = CompareIdealizedModel() - generic_comparer._compare_roughness( - case_name, tzw_values, input_roughness_file, fm2prof_fig_dir - ) - except Exception as e_info: - pytest.fail( - "No exception expected but was thrown " + "{}.".format(str(e_info)) - ) + generic_comparer = CompareIdealizedModel() + generic_comparer._compare_roughness( + case_name, tzw_values, input_roughness_file, fm2prof_fig_dir + ) + assert os.listdir( fm2prof_fig_dir @@ -658,16 +635,12 @@ def ARCHIVED_test_when_output_exists_then_compare_generic_model_volume( os.makedirs(fm2prof_fig_dir) # 3. Run - try: - generic_comparer = CompareIdealizedModel() - generic_comparer._compare_volume( - case_name, input_volume_file, fm2prof_fig_dir - ) - except Exception as e_info: - pytest.fail( - "No exception expected but was thrown " + "{}.".format(str(e_info)) - ) - + + generic_comparer = CompareIdealizedModel() + generic_comparer._compare_volume( + case_name, input_volume_file, fm2prof_fig_dir + ) + # 4. Final expectation assert os.listdir( fm2prof_fig_dir @@ -685,10 +658,6 @@ def test_when_output_exists_then_compare_with_reference(self, case_name: str): """ # 1. Get all necessary output / input directories reference_geometry = self.__case_tzw_dict.get(case_name) - reference_roughness = ( - None # CompareHelper.get_analytical_roughness_for_case(case_name) - ) - reference__volume = [] fm2prof_dir = _get_test_case_output_dir(case_name) # 2. Verify / create necessary folders and directories @@ -756,13 +725,10 @@ def test_when_waal_case_then_performance_is_slow(self): assert os.path.exists(css_file), "" + "CrossSection (test) file was not found" # 3. Run test. - try: - runner = Fm2ProfRunner(iniFilePath=None) - runner.run_inifile(iniFile=test_ini_file) - except Exception as e_error: - # if os.path.exists(root_output_dir): - # shutil.rmtree(root_output_dir) - pytest.fail("No exception expected but was thrown {}.".format(str(e_error))) + + runner = Fm2ProfRunner(iniFilePath=None) + runner.run_inifile(iniFile=test_ini_file) + # 4. Verify final expectations. pass diff --git a/tests/test_crosssection.py b/tests/test_crosssection.py index 523223be..ee9e9693 100644 --- a/tests/test_crosssection.py +++ b/tests/test_crosssection.py @@ -1,10 +1,8 @@ -import datetime import numpy as np import pytest from fm2prof.CrossSection import CrossSection -from fm2prof.IniFile import IniFile import pickle from tests.TestUtils import TestUtils @@ -69,16 +67,10 @@ def test_when_correct_input_dict_is_given_CrossSection_initialises(self): with open(tdir.joinpath(f"{test_cases[0].get('name')}.pickle"), 'rb') as f: css_data = pickle.load(f) - # 2. Set expectations - - - # 3. Run test - try: - css = CrossSection(data=css_data) - except Exception as e_info: - pytest.fail( - f"No expected exception but was risen:" + " {e_info}") - + # 2. Set expectations + # 3. Run test + css = CrossSection(data=css_data) + # 4. Verify final expectations assert css.length == css_data.get('length') @@ -96,13 +88,9 @@ def test_build_geometry(self): css_z: np.array = test_case.get('css_z') css_total_volume: np.array = test_case.get('css_total_volume') - # 3. Run test - try: - css = CrossSection(data=css_data) - css.build_geometry() - except Exception as e_info: - pytest.fail( - f"No expected exception but was risen:" + " {e_info}") + # 3. Run test + css = CrossSection(data=css_data) + css.build_geometry() # 4. Verify final expectations assert len(css_z) == len(css._css_z) @@ -124,14 +112,11 @@ def test_calculate_correction(self): crest_level:float = test_case.get('crest_level') # type: ignore extra_total_volume: np.ndarray = test_case.get('extra_total_volume') # type: ignore - # 3. Run test - try: - css = CrossSection(data=css_data) - css.build_geometry() - css.calculate_correction() - except Exception as e_info: - pytest.fail( - f"No expected exception but was risen:" + " {e_info}") + # 3. Run test + css = CrossSection(data=css_data) + css.build_geometry() + css.calculate_correction() + # 4. Verify final expectations assert abs(crest_level - css.crest_level) < tol @@ -144,21 +129,11 @@ def test_reduce_points(self): with open(tdir.joinpath(f"{test_case.get('name')}.pickle"), 'rb') as f: css_data = pickle.load(f) - tol = 1e-6 - - # 2. Set expectations for - crest_level:float = test_case.get('crestlevel') - extra_total_volume: np.ndarray = test_case.get('extra_total_volume') - - # 3. Run test - try: - css = CrossSection(data=css_data) - css.build_geometry() - css.calculate_correction() - css.reduce_points(count_after=20) - except Exception as e_info: - pytest.fail( - f"No expected exception but was risen:" + " {e_info}") - - # 4. Verify final expectations + # 2. Run test + css = CrossSection(data=css_data) + css.build_geometry() + css.calculate_correction() + css.reduce_points(count_after=20) + + # 3. Verify final expectations assert len(css.z) == 20 \ No newline at end of file diff --git a/tests/test_fm2profrunner.py b/tests/test_fm2profrunner.py index 6463337a..81570f64 100644 --- a/tests/test_fm2profrunner.py +++ b/tests/test_fm2profrunner.py @@ -1,6 +1,4 @@ import os -import shutil -import pytest from fm2prof import Project from fm2prof.Fm2ProfRunner import Fm2ProfRunner @@ -22,12 +20,9 @@ def test_if_get_existing_parameter_then_returned(self): project = None value = None - # 2. Run test - try: - project = Project() - value = project.get_parameter("LakeTimeSteps") - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) + # 2. Run test + project = Project() + value = project.get_parameter("LakeTimeSteps") # 3. Verify final expectations assert project is not None @@ -37,13 +32,10 @@ def test_if_get_nonexisting_parameter_then_no_exception(self): # 1. Set up initial test dat project = None value = None - # 2. Run test - try: - project = Project() - value = project.get_parameter("IDoNoTExist") - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) - + # 2. Run test + project = Project() + value = project.get_parameter("IDoNoTExist") + # 3. Verify final expectations assert project is not None assert value is None @@ -52,12 +44,10 @@ def test_if_get_existing_inputfile_then_returned(self): # 1. Set up initial test dat project = None value = None - # 2. Run test - try: - project = Project() - value = project.get_input_file("CrossSectionLocationFile") - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) + + # 2. Run test + project = Project() + value = project.get_input_file("CrossSectionLocationFile") # 3. Verify final expectations assert project is not None @@ -67,12 +57,10 @@ def test_if_get_output_directory_then_returned(self): # 1. Set up initial test dat project = None value = None - # 2. Run test - try: - project = Project() - value = project.get_output_directory() - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) + + # 2. Run test + project = Project() + value = project.get_output_directory() # 3. Verify final expectations assert project is not None @@ -82,12 +70,10 @@ def test_set_parameter(self): # 1. Set up initial test dat project = None value = 150 - # 2. Run test - try: - project = Project() - project.set_parameter("LakeTimeSteps", value) - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) + + # 2. Run test + project = Project() + project.set_parameter("LakeTimeSteps", value) # 3. Verify final expectations assert project.get_parameter("LakeTimeSteps") == value @@ -96,12 +82,9 @@ def test_set_input_file(self): # 1. Set up initial test dat project = None value = "RandomString" - # 2. Run test - try: - project = Project() - project.set_input_file("CrossSectionLocationFile", value) - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) + # 2. Run test + project = Project() + project.set_input_file("CrossSectionLocationFile", value) # 3. Verify final expectations assert project.get_input_file("CrossSectionLocationFile") == value @@ -110,26 +93,18 @@ def test_set_output_directory(self): # 1. Set up initial test dat project = None value = "test/subdir" - # 2. Run test - try: - project = Project() - project.set_output_directory(value) - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) - - # 3. Verify final expectations - + # 2. Run test + project = Project() + project.set_output_directory(value) + def test_print_configuration(self): # 1. Set up initial test dat project = None value = None - # 2. Run test - try: - project = Project() - value = project.print_configuration() - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) - + # 2. Run test + project = Project() + value = project.print_configuration() + # 3. Verify final expectations assert value is not None @@ -139,10 +114,8 @@ def test_when_no_file_path_then_no_exception_is_risen(self): runner = None # 2. Run test - try: - runner = Fm2ProfRunner() - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) + runner = Fm2ProfRunner() + # 3. Verify final expectations assert runner is not None @@ -160,11 +133,8 @@ def test_given_inifile_then_no_exception_is_risen(self): ini_file_path ) - # 3. Run test - try: - runner = Fm2ProfRunner(ini_file_path) - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) + # 3. Run test + runner = Fm2ProfRunner(ini_file_path) # 4. Verify final expectations assert runner is not None diff --git a/tests/test_functions.py b/tests/test_functions.py index ab626f62..f072591c 100644 --- a/tests/test_functions.py +++ b/tests/test_functions.py @@ -1,8 +1,4 @@ -import numbers import os -import shutil -import sys -import unittest import numpy as np import pytest @@ -47,15 +43,9 @@ def test_read_css_xyz_valid_file_path_returns_expected_input_data(self): ) # 3. Run test - try: - result_input_data = Func._read_css_xyz(file_path) - except: - pytest.fail( - "No exception expected but test failed \ - while reading file {}.".format( - file_path - ) - ) + + result_input_data = Func._read_css_xyz(file_path) + # 4. Verify final expectations for expected_input_key in expected_input_data: diff --git a/tests/test_inifile.py b/tests/test_inifile.py index 0d6fa22f..eacda7ea 100644 --- a/tests/test_inifile.py +++ b/tests/test_inifile.py @@ -1,14 +1,8 @@ -import numbers -import os -import shutil -import sys -import unittest from pathlib import Path import pytest from fm2prof.IniFile import IniFile -from tests.TestUtils import TestUtils _root_output_dir = None @@ -25,10 +19,8 @@ def test_when_no_file_path_then_no_exception_is_risen(self): iniFilePath = "" # 2. Run test - try: - IniFile(iniFilePath) - except: - pytest.fail("No exception expected.") + IniFile(iniFilePath) + def test_when_non_existent_file_path_then_io_exception_is_risen(self): # 1. Set up initial test data @@ -58,12 +50,8 @@ def test_set_output_dir_with_valid_input(self, output_dir, expected_value): iniFile = IniFile(ini_file_path) new_output_dir = None - # 2. Run test - try: - new_output_dir = iniFile.set_output_directory(output_dir) - except: - err_mssg = "Test failed while trying to get new valid output dir." - pytest.fail(err_mssg) + # 2. Run test + new_output_dir = iniFile.set_output_directory(output_dir) # 3. Verify final expectations assert Path(expected_value) == new_output_dir.relative_to(Path().cwd()) diff --git a/tests/test_main.py b/tests/test_main.py index 917102b4..61d2305f 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1,8 +1,6 @@ import getopt import os import shutil -import sys -import unittest import pytest @@ -56,7 +54,7 @@ def test_when_incorrect_args_then_systemexit_risen_with_expected_message(self): main.main(mainArgs) # 4. Verify expectations - assert pytest_wrapped_e.type == SystemExit + assert isinstance(pytest_wrapped_e.type, SystemExit) assert pytest_wrapped_e.value.code == expectedMssg def test_when_incorrect_input_args_systemexit_risen_with_expected_message(self): @@ -74,7 +72,7 @@ def test_when_incorrect_input_args_systemexit_risen_with_expected_message(self): main.main(mainArgs) # 4. Verify expectations - assert pytest_wrapped_e.type == SystemExit + assert isinstance(pytest_wrapped_e.type, SystemExit) assert pytest_wrapped_e.value.code == expectedMssg def test_when_giving_correct_arguments_then_does_not_raise_systemexit(self): @@ -93,16 +91,15 @@ def test_when_giving_correct_arguments_then_does_not_raise_systemexit(self): ] # 3. Run test - try: - with pytest.raises(SystemExit) as pytest_wrapped_e: - main.main(mainArgs) - # 4. Verify expectations (it should actually not get here) - assert pytest_wrapped_e.type == SystemExit - for reason in reasons: - expectedMssg = "Error: {0}".format(reason) - assert pytest_wrapped_e.value.code != expectedMssg - except: - pass + with pytest.raises(SystemExit) as pytest_wrapped_e: + main.main(mainArgs) + + # 4. Verify expectations (it should actually not get here) + assert isinstance(pytest_wrapped_e.type, SystemExit) + for reason in reasons: + expectedMssg = "Error: {0}".format(reason) + assert pytest_wrapped_e.value.code != expectedMssg + def ARCHIVED_test_when_giving_non_existent_input_file_then_raises_io_exception( self, @@ -137,10 +134,7 @@ def ARCHIVED_test_when_giving_existent_empty_input_file_then_does_not_raise_io_e # 2. Set up expectations assert os.path.exists(file_path) - reason = "The given file path {} could not be found.".format(file_path) - # 3. Run test - try: - main.main(mainArgs) - except: - pytest.fail("Unexpected exception.") + # 3. Run test + main.main(mainArgs) + diff --git a/tests/test_maskoutputfile.py b/tests/test_maskoutputfile.py index ec065fe7..49ffed74 100644 --- a/tests/test_maskoutputfile.py +++ b/tests/test_maskoutputfile.py @@ -1,9 +1,4 @@ -import json -import numbers import os -import shutil -import sys -import unittest from pathlib import Path import geojson @@ -28,11 +23,9 @@ def test_when_no_coords_does_not_raise(self): mask_point = None # 2. Set up initial expectations - # 3. Do test - try: - mask_point = MaskOutputFile.create_mask_point(coords, properties) - except: - pytest.fail("Exception risen but not expected.") + # 3. Do test + mask_point = MaskOutputFile.create_mask_point(coords, properties) + # 4. Verify final expectations assert mask_point is not None, "" + "No mask_point generated" @@ -43,11 +36,9 @@ def test_when_valid_coords_does_not_raise(self, coords_values: tuple): properties = None mask_point = None - # 2. Do test - try: - mask_point = MaskOutputFile.create_mask_point(coords, properties) - except: - pytest.fail("Exception risen but not expected.") + # 2. Do test + mask_point = MaskOutputFile.create_mask_point(coords, properties) + # 3. Verify final expectations assert mask_point is not None, "" + "No mask_point generated" @@ -57,15 +48,11 @@ def test_when_invalid_coords_raises(self, coords_values: tuple): coords = coords_values properties = None mask_point = None - exception_thrown = False - # 2. Do test - try: - mask_point = MaskOutputFile.create_mask_point(coords, properties) - except: - exception_thrown = True + # 2. Do test + mask_point = MaskOutputFile.create_mask_point(coords, properties) + # 3. Verify final expectations - assert exception_thrown, "" + "No exception was thrown but it was expected." assert mask_point is None, "" + "Mask point generated but was not expected." def test_when_no_properties_does_not_raise(self): @@ -75,22 +62,18 @@ def test_when_no_properties_does_not_raise(self): mask_point = None # 2. Set up initial expectations - # 3. Do test - try: - mask_point = MaskOutputFile.create_mask_point(coords, properties) - except: - pytest.fail("Exception risen but not expected.") + # 3. Do test + mask_point = MaskOutputFile.create_mask_point(coords, properties) + # 4. Verify final expectations assert mask_point is not None, "" + "No mask_point generated" class Test_validate_extension: @pytest.mark.parametrize("file_name", [(None), ("")]) - def test_when_no_file_path_doesnot_raise(self, file_name): - try: - MaskOutputFile.validate_extension(file_name) - except: - pytest.fail("Exception risen but not expected.") + def test_when_no_file_path_doesnot_raise(self, file_name): + MaskOutputFile.validate_extension(file_name) + def test_when_invalid_extension_raises_expected_exception(self): # 1. Set up test data @@ -114,12 +97,9 @@ def test_when_invalid_extension_raises_expected_exception(self): ) @pytest.mark.parametrize("file_name", [("n.json"), ("n.geojson")]) - def test_when_valid_extension_does_not_raise(self, file_name): - try: - MaskOutputFile.validate_extension(file_name) - except: - pytest.fail("Exception risen but not expected.") - + def test_when_valid_extension_does_not_raise(self, file_name): + MaskOutputFile.validate_extension(file_name) + class Test_read_mask_output_file: @pytest.mark.parametrize( @@ -134,10 +114,8 @@ def test_when_invalid_file_path_given_then_emtpy_geojson(self, file_path_name): expected_geojson = geojson.FeatureCollection(None) # 3. Read data - try: - read_geojson = MaskOutputFile.read_mask_output_file(file_path_name) - except: - pytest.fail("Exception thrown but not expected.") + read_geojson = MaskOutputFile.read_mask_output_file(file_path_name) + # 4. Verify final expectations assert read_geojson, "" + "No geojson data was generated." @@ -228,11 +206,9 @@ def test_when_no_file_path_given_then_exception_not_risen(self): # 1. Set up test data file_path = None mask_points = None - # 2. Verify test - try: - MaskOutputFile.write_mask_output_file(file_path, mask_points) - except: - pytest.fail("Exception thrown but not expected.") + # 2. Verify test + MaskOutputFile.write_mask_output_file(file_path, mask_points) + def test_when_file_path_with_wrong_extension_then_exception_is_risen(self): # 1. Set up test data @@ -269,10 +245,8 @@ def test_when_valid_file_path_and_no_mask_point_then_writes_expectations( read_mask_points = None # 3. Run test - try: - MaskOutputFile.write_mask_output_file(file_path, mask_points) - except: - pytest.fail("Exception thrown but not expected.") + MaskOutputFile.write_mask_output_file(file_path, mask_points) + # 4. Verify final expectations assert os.path.exists(file_path), "" + "File {} not found.".format(file_path) @@ -304,11 +278,8 @@ def test_when_valid_file_path_and_mask_points_then_writes_expectations( expected_mask_points = geojson.FeatureCollection(mask_points) read_mask_points = None - # 3. Run test - try: - MaskOutputFile.write_mask_output_file(file_path, mask_points) - except: - pytest.fail("Exception thrown but not expected.") + # 3. Run test + MaskOutputFile.write_mask_output_file(file_path, mask_points) # 4. Verify final expectations assert os.path.exists(file_path), "" + "File {} not found.".format(file_path) diff --git a/tests/test_utils.py b/tests/test_utils.py index fbec0cc5..a7ae00e8 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -5,7 +5,6 @@ from fm2prof import Project from fm2prof.utils import ( GenerateCrossSectionLocationFile, - ModelOutputReader, Compare1D2D, VisualiseOutput ) @@ -126,13 +125,9 @@ def test_when_branch_in_branches_produce_figure(self): output_file = TestUtils.get_local_test_file('cases/case_02_compound/output/figures/roughness/roughness_longitudinal_channel1.png') - # 3. Run test - try: - vis.figure_roughness_longitudinal(branch="channel1") - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) + # 3. Run test + vis.figure_roughness_longitudinal(branch="channel1") - # 4. Verify expectations assert output_file.is_file() @@ -150,12 +145,10 @@ def test_when_given_output_css_figure_produced(self): os.mkdir(output_dir) output_file = TestUtils.get_local_test_file('cases/case_02_compound/output/figures/cross_sections/channel1_125.000.png') - # 3. Run test - try: - for css in vis.cross_sections: - vis.figure_cross_section(css) - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) + # 3. Run test + for css in vis.cross_sections: + vis.figure_cross_section(css) + # 4. Verify expectations assert output_file.is_file() @@ -167,19 +160,14 @@ def test_when_no_netcdf_but_csv_present_class_initialises(self): project_config = TestUtils.get_local_test_file('compare1d2d/rijn-j22_6-v1a2/sobek-rijn-j22.ini') project = Project(project_config) - # 2. Set expectations - - # 3. Run test - try: - plotter = Compare1D2D(project=project, - path_1d=None, - path_2d=None, - routes=[['BR', "PK", "IJ"], ['BR', 'PK', 'NR', "LE"], ["BR", "WL", "BO"]], - start_time=datetime(year=2000, month=1, day=5)) - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) - - # 4. Verify expectations + # 2. Run test + plotter = Compare1D2D(project=project, + path_1d=None, + path_2d=None, + routes=[['BR', "PK", "IJ"], ['BR', 'PK', 'NR', "LE"], ["BR", "WL", "BO"]], + start_time=datetime(year=2000, month=1, day=5)) + + # 3. Verify expectations assert isinstance(plotter, Compare1D2D) def test_statistics_to_file(self): @@ -197,11 +185,8 @@ def test_statistics_to_file(self): # this file should exist output_file = TestUtils.get_local_test_file('compare1d2d/rijn-j22_6-v1a2/output/error_statistics.csv') - # 3. Run test - try: - plotter.statistics_to_file() - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) + # 3. Run test + plotter.statistics_to_file() # 4. Verify expectations assert output_file.is_file() @@ -218,11 +203,8 @@ def test_figure_longitudinal(self): # this file should exist output_file = TestUtils.get_local_test_file('compare1d2d/rijn-j22_6-v1a2/output/figures/longitudinal/BR-PK-IJ.png') - # 3. Run test - try: - plotter.figure_longitudinal(route=['BR', "PK", "IJ"], stat="last25") - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) + # 3. Run test + plotter.figure_longitudinal(route=['BR', "PK", "IJ"], stat="last25") # 4. Verify expectations assert output_file.is_file() @@ -239,12 +221,9 @@ def test_figure_discharge(self): # this file should exist output_file = TestUtils.get_local_test_file('compare1d2d/rijn-j22_6-v1a2/output/figures/discharge/Pannerdensche Kop.png') - # 3. Run test - try: - plotter.figure_compare_discharge_at_stations(stations=['WL_869.00', 'PK_869.00'], - title="Pannerdensche Kop") - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) + # 3. Run test + plotter.figure_compare_discharge_at_stations(stations=['WL_869.00', 'PK_869.00'], + title="Pannerdensche Kop") # 4. Verify expectations assert output_file.is_file() @@ -261,11 +240,8 @@ def test_figure_at_station(self): # this file should exist output_file = TestUtils.get_local_test_file('compare1d2d/cases/case1/output/figures/stations/NR_919.00.png') - # 3. Run test - try: - plotter.figure_at_station("NR_919.00") - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) + # 3. Run test + plotter.figure_at_station("NR_919.00") # 4. Verify expectations assert output_file.is_file() @@ -278,23 +254,17 @@ def test_if_style_is_given_figure_produced(self): project_config = TestUtils.get_local_test_file('compare1d2d/rijn-j22_6-v1a2/sobek-rijn-j22.ini') project = Project(project_config) - - # 2. Set expectations # this file should exist output_file = TestUtils.get_local_test_file('compare1d2d/rijn-j22_6-v1a2/output/figures/longitudinal/BR-PK-IJ.png') - # 3. Run test - + # 3. Run test for style in styles: plotter = Compare1D2D(project=project, start_time=datetime(year=2000, month=1, day=5), style=style) - try: - plotter.figure_longitudinal(route=['BR', "PK", "IJ"], stat="last25") - - except Exception as e: - pytest.fail("No exception expected, but thrown: {}".format(str(e))) - + + plotter.figure_longitudinal(route=['BR', "PK", "IJ"], stat="last25") + # 4. Verify expectations assert output_file.is_file() \ No newline at end of file From a499553873e74dc6665c7b2cdf52b0a421ec9fd6 Mon Sep 17 00:00:00 2001 From: Tjalling-dejong Date: Tue, 19 Nov 2024 14:32:08 +0100 Subject: [PATCH 2/9] improved MaskOutputFile --- fm2prof/MaskOutputFile.py | 58 ++++---- tests/test_maskoutputfile.py | 270 ++++++++--------------------------- 2 files changed, 94 insertions(+), 234 deletions(-) diff --git a/fm2prof/MaskOutputFile.py b/fm2prof/MaskOutputFile.py index 3b18fe7f..664c04e9 100644 --- a/fm2prof/MaskOutputFile.py +++ b/fm2prof/MaskOutputFile.py @@ -20,15 +20,15 @@ Stichting Deltares and remain full property of Stichting Deltares at all times. All rights reserved. """ - -import os - +from pathlib import Path +from typing import Union, Optional import geojson + class MaskOutputFile: @staticmethod - def create_mask_point(coords: geojson.coords, properties: dict): + def create_mask_point(coords: geojson.coords, properties: Optional[dict] = None) -> geojson.Feature: """Creates a Point based on the properties and coordinates given. Arguments: @@ -36,43 +36,45 @@ def create_mask_point(coords: geojson.coords, properties: dict): Coordinates tuple (x,y) for the mask point. properties {dict} -- Dictionary of properties """ - output_mask = geojson.Feature(geometry=geojson.Point(coords)) + if not coords: + raise ValueError("coords cannot be empty.") + output_mask = geojson.Feature(geometry=geojson.Point(coords)) + if properties: output_mask.properties = properties return output_mask @staticmethod - def validate_extension(file_path: str): - if not file_path: - # Should not be evaluated - return - if not file_path.endswith(".json") and not file_path.endswith(".geojson"): + def validate_extension(file_path: Union[str, Path]) -> None: + if not isinstance(file_path, (str, Path)): + err_msg = f"file_path should be string or Path, not {type(file_path)}" + raise TypeError(err_msg) + if Path(file_path).suffix not in [".json", ".geojson"]: raise IOError( - "Invalid file path extension, " + "should be .json or .geojson." + "Invalid file path extension, should be .json or .geojson." ) @staticmethod - def read_mask_output_file(file_path: str): + def read_mask_output_file(file_path: Union[str, Path]) -> dict: """Imports a GeoJson from a given json file path. Arguments: file_path {str} -- Location of the json file """ - geojson_data = geojson.FeatureCollection(None) - if not file_path or not os.path.exists(file_path): - return geojson_data + file_path = Path(file_path) + if not file_path.exists(): + err_msg = f"File path {file_path} not found." + raise FileNotFoundError(err_msg) MaskOutputFile.validate_extension(file_path) - with open(file_path) as geojson_file: - try: - geojson_data = geojson.load(geojson_file) - except: - return geojson_data - + with file_path.open("r") as geojson_file: + geojson_data = geojson.load(geojson_file) + if not isinstance(geojson_data, geojson.FeatureCollection): + raise IOError("File is empty or not a valid geojson file.") return geojson_data @staticmethod - def write_mask_output_file(file_path: str, mask_points: list): + def write_mask_output_file(file_path: Union[Path, str], mask_points: list) -> None: """Writes a .geojson file with a Feature collection containing the mask_points list given as input. @@ -80,8 +82,10 @@ def write_mask_output_file(file_path: str, mask_points: list): file_path {str} -- file_path where to store the geojson. mask_points {list} -- List of features to output. """ - if file_path: - MaskOutputFile.validate_extension(file_path) - feature_collection = geojson.FeatureCollection(mask_points) - with open(file_path, "w") as f: - geojson.dump(feature_collection, f, indent=4) + file_path = Path(file_path) + if not mask_points: + raise ValueError("mask_points cannot be empty.") + MaskOutputFile.validate_extension(file_path) + feature_collection = geojson.FeatureCollection(mask_points) + with file_path.open("w") as f: + geojson.dump(feature_collection, f, indent=4) diff --git a/tests/test_maskoutputfile.py b/tests/test_maskoutputfile.py index 49ffed74..8d764aba 100644 --- a/tests/test_maskoutputfile.py +++ b/tests/test_maskoutputfile.py @@ -8,93 +8,58 @@ from tests.TestUtils import TestUtils -class MaskOutputFileHelper: - @staticmethod - def get_mask_point(): - mask_point = geojson.utils.generate_random("Point") - return mask_point - class Test_create_mask_point: - def test_when_no_coords_does_not_raise(self): + def test_when_no_coords_does_raise(self): # 1. Set up test model coords = None properties = None - mask_point = None + # 2. Set up initial expectations + expected_error = "coords cannot be empty." - # 3. Do test - mask_point = MaskOutputFile.create_mask_point(coords, properties) + # 3. Do test + with pytest.raises(ValueError, match=expected_error): + MaskOutputFile.create_mask_point(coords, properties) - # 4. Verify final expectations - assert mask_point is not None, "" + "No mask_point generated" + @pytest.mark.parametrize("coords_values", [(4.2, 2.4), (4.2, 2.4, 42)]) def test_when_valid_coords_does_not_raise(self, coords_values: tuple): # 1. Set up test model coords = coords_values properties = None - mask_point = None # 2. Do test mask_point = MaskOutputFile.create_mask_point(coords, properties) # 3. Verify final expectations - assert mask_point is not None, "" + "No mask_point generated" + assert mask_point is not None, "No mask_point generated" - @pytest.mark.parametrize("coords_values", [(4.2)]) - def test_when_invalid_coords_raises(self, coords_values: tuple): - # 1. Set up test model - coords = coords_values - properties = None - mask_point = None - # 2. Do test - mask_point = MaskOutputFile.create_mask_point(coords, properties) - - # 3. Verify final expectations - assert mask_point is None, "" + "Mask point generated but was not expected." - def test_when_no_properties_does_not_raise(self): - # 1. Set up test model - coords = (4.2, 2.4) - properties = None - mask_point = None - # 2. Set up initial expectations - - # 3. Do test - mask_point = MaskOutputFile.create_mask_point(coords, properties) - - # 4. Verify final expectations - assert mask_point is not None, "" + "No mask_point generated" - - -class Test_validate_extension: - @pytest.mark.parametrize("file_name", [(None), ("")]) - def test_when_no_file_path_doesnot_raise(self, file_name): - MaskOutputFile.validate_extension(file_name) +class Test_validate_extension: + def test_when_none_file_path_does_raise(self): + with pytest.raises(TypeError, match=f"file_path should be string or Path, not {type(None)}"): + MaskOutputFile.validate_extension(None) def test_when_invalid_extension_raises_expected_exception(self): # 1. Set up test data - file_name = "test_file.wrongextension" - - # 2. Set expectations - expected_error = ( - "" + "Invalid file path extension, should be .json or .geojson." - ) - + file_path = Path("test.sjon") + + # 2. Set expectations + expected_IOError = "Invalid file path extension, should be .json or .geojson." + expectedTypeError = f"file_path should be string or Path, not {int}" + # 3. Run test - with pytest.raises(IOError) as e_info: - MaskOutputFile.validate_extension(file_name) + with pytest.raises(IOError, match=expected_IOError): + MaskOutputFile.validate_extension(str(file_path)) + + with pytest.raises(TypeError, match=expectedTypeError): + MaskOutputFile.validate_extension(1) + - # 4. Verify final expectations - error_message = str(e_info.value) - assert error_message == expected_error, ( - "" - + "Expected exception message {},".format(expected_error) - + "retrieved {}".format(error_message) - ) @pytest.mark.parametrize("file_name", [("n.json"), ("n.geojson")]) def test_when_valid_extension_does_not_raise(self, file_name): @@ -102,76 +67,34 @@ def test_when_valid_extension_does_not_raise(self, file_name): class Test_read_mask_output_file: - @pytest.mark.parametrize( - "file_path_name", - [(None), ("invalidfile.geojson"), ("invalidfile.json"), ("invalidfile.xyz")], - ) - def test_when_invalid_file_path_given_then_emtpy_geojson(self, file_path_name): - # 1. Set up test data - read_geojson = None - - # 2. Set up initial expectations - expected_geojson = geojson.FeatureCollection(None) - - # 3. Read data - read_geojson = MaskOutputFile.read_mask_output_file(file_path_name) - - - # 4. Verify final expectations - assert read_geojson, "" + "No geojson data was generated." - assert read_geojson == expected_geojson, "" + "Expected {} but got {}".format( - expected_geojson, read_geojson - ) - - def test_when_file_path_wrong_extension_then_raise_exception(self): + def test_when_invalid_file_path_given(self, tmp_path): # 1. Set up test data - file_path = ( - TestUtils.get_local_test_data_dir("maskoutputfile_test_data") - / "test_file.wrongextension" - ) - read_geojson_data = None + not_existing_file = tmp_path / "test.geojson" - # 2. Set expectations - assert file_path.exists(), "" + "File {} could not be found.".format(file_path) - expected_error = ( - "" + "Invalid file path extension, should be .json or .geojson." - ) + # 2. Set expectation + expected_error = f"File path {not_existing_file} not found" # 3. Run test - with pytest.raises(IOError) as e_info: - read_geojson_data = MaskOutputFile.read_mask_output_file(str(file_path)) - - # 4. Verify final expectations - assert not read_geojson_data - error_message = str(e_info.value) - assert error_message == expected_error, ( - "" - + "Expected exception message {},".format(expected_error) - + "retrieved {}".format(error_message) - ) + with pytest.raises(FileNotFoundError, match=expected_error): + MaskOutputFile.read_mask_output_file(not_existing_file) - @pytest.mark.parametrize( - "file_name", [("no_mask_points.geojson"), ("no_content.geojson")] - ) + def test_when_valid_file_with_no_content_then_returns_expected_geojson( - self, file_name + self, tmp_path ): # 1. Set up test data - file_path: Path = ( - TestUtils.get_local_test_data_dir("maskoutputfile_test_data") / file_name - ) - - expected_geojson = geojson.FeatureCollection(None) - assert file_path.is_file(), "File not found at {}".format(file_path) + file_path: Path = tmp_path / "empty.geojson" + with file_path.open("w") as f: + geojson.dump({},f) + + # 2. Set up expectations + expected_error = "File is empty or not a valid geojson file." - # 2. Read data - read_geojson = MaskOutputFile.read_mask_output_file(str(file_path)) + # Run test + with pytest.raises(IOError, match=expected_error): + MaskOutputFile.read_mask_output_file(file_path) + - # 3. Verify final expectations - assert read_geojson, "No geojson data was generated." - assert ( - read_geojson == expected_geojson - ), f"Expected {expected_geojson} but got {read_geojson}" def test_when_valid_file_with_content_then_returns_expected_geojson(self): # 1. Set up test data @@ -180,118 +103,51 @@ def test_when_valid_file_with_content_then_returns_expected_geojson(self): / "mask_points.geojson" ) - # 2. Verify initial expectations - assert file_path.exists(), f"File not found at {file_path}" - # 2. Read data - read_geojson = MaskOutputFile.read_mask_output_file(str(file_path)) + read_geojson = MaskOutputFile.read_mask_output_file(file_path) # 3. Verify final expectations - assert read_geojson, "" + "No geojson data was generated." - assert read_geojson.is_valid, "" + "The geojson data is not valid." + assert read_geojson, "No geojson data was generated." + assert isinstance(read_geojson, geojson.FeatureCollection) + assert read_geojson.is_valid, "The geojson data is not valid." class Test_write_mask_output_file: - @pytest.fixture(scope="class") - def test_folder(self) -> Path: - """Prepares the class properties to be used in the tests.""" - test_dir = ( - TestUtils.get_artifacts_test_data_dir() / "Output" / "WriteMaskOutputFile" - ) - if not test_dir.is_dir(): - test_dir.mkdir(parents=True, exist_ok=True) - return test_dir - - def test_when_no_file_path_given_then_exception_not_risen(self): - # 1. Set up test data - file_path = None - mask_points = None - # 2. Verify test - MaskOutputFile.write_mask_output_file(file_path, mask_points) - - - def test_when_file_path_with_wrong_extension_then_exception_is_risen(self): - # 1. Set up test data - file_path = "test_file.wrongextension" - mask_points = None - - # 2. Set expectations - expected_error = ( - "" + "Invalid file path extension, should be .json or .geojson." - ) - - # 3. Run test - with pytest.raises(IOError) as e_info: - MaskOutputFile.write_mask_output_file(file_path, mask_points) - - # 4. Verify final expectations - error_message = str(e_info.value) - assert error_message == expected_error, ( - "" - + "Expected exception message {},".format(expected_error) - + "retrieved {}".format(error_message) - ) - def test_when_valid_file_path_and_no_mask_point_then_writes_expectations( - self, test_folder: Path + self, tmp_path: Path ): - # 1. Set up test data - file_name = "no_mask_points.geojson" - file_path = str(test_folder / file_name) - mask_points = None - - # 2. Set expectations - expected_mask_points = geojson.FeatureCollection(mask_points) - read_mask_points = None + # 1. Set up test data + file_path = tmp_path / "no_mask_points.geojson" + + # 2. Set up expectations + error_msg = "mask_points cannot be empty" # 3. Run test - MaskOutputFile.write_mask_output_file(file_path, mask_points) + with pytest.raises(ValueError, match=error_msg): + MaskOutputFile.write_mask_output_file(file_path=file_path, mask_points=None) - # 4. Verify final expectations - assert os.path.exists(file_path), "" + "File {} not found.".format(file_path) - - with open(file_path) as geojson_file: - read_mask_points = geojson.load(geojson_file) - - assert read_mask_points, "" + "No mask points were read from {}".format( - file_path - ) - assert expected_mask_points == read_mask_points, ( - "" - + "Expected {} ,".format(expected_mask_points) - + "but got {}".format(read_mask_points) - ) - def test_when_valid_file_path_and_mask_points_then_writes_expectations( - self, test_folder: Path + self, tmp_path ): - # 1. Set up test data - file_name = "mask_points.geojson" - file_path = str(test_folder / file_name) + # 1. Set up test data + file_path = tmp_path / "mask_points.geojson" mask_points = [ - geojson.Feature(geometry=MaskOutputFileHelper.get_mask_point()), - geojson.Feature(geometry=MaskOutputFileHelper.get_mask_point()), + geojson.Feature(geometry=geojson.utils.generate_random("Point")), + geojson.Feature(geometry=geojson.utils.generate_random("Point")), ] # 2. Set expectations expected_mask_points = geojson.FeatureCollection(mask_points) - read_mask_points = None # 3. Run test MaskOutputFile.write_mask_output_file(file_path, mask_points) # 4. Verify final expectations - assert os.path.exists(file_path), "" + "File {} not found.".format(file_path) + assert file_path.exists(), f"File {file_path} not found." - with open(file_path) as geojson_file: + with file_path.open("r") as geojson_file: read_mask_points = geojson.load(geojson_file) - assert read_mask_points, "" + "No mask points were read from {}".format( - file_path - ) - assert expected_mask_points == read_mask_points, ( - "" - + "Expected {} ,".format(expected_mask_points) - + "but got {}".format(read_mask_points) - ) + assert read_mask_points, f"No mask points were read from {file_path}" + assert expected_mask_points == read_mask_points, f"Expected {expected_mask_points} , but got {read_mask_points}" From 9a062137451a8f15041c55b6fc9b4c5103068b71 Mon Sep 17 00:00:00 2001 From: Tjalling-dejong Date: Tue, 19 Nov 2024 14:37:35 +0100 Subject: [PATCH 3/9] rewrote test_maskoutputfile.py --- tests/test_maskoutputfile.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/test_maskoutputfile.py b/tests/test_maskoutputfile.py index 8d764aba..633e5bbf 100644 --- a/tests/test_maskoutputfile.py +++ b/tests/test_maskoutputfile.py @@ -1,4 +1,3 @@ -import os from pathlib import Path import geojson From 814ca054f2738a19cfcd559c1cbbf990fd8838bb Mon Sep 17 00:00:00 2001 From: Tjalling-dejong Date: Tue, 19 Nov 2024 15:01:11 +0100 Subject: [PATCH 4/9] improved main tests --- tests/test_main.py | 68 ++++++---------------------------------------- 1 file changed, 8 insertions(+), 60 deletions(-) diff --git a/tests/test_main.py b/tests/test_main.py index 61d2305f..8bba821b 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1,6 +1,7 @@ import getopt import os import shutil +import re import pytest @@ -41,7 +42,7 @@ def teardown_class(Main): if os.path.exists(outputtestdir): os.rmdir(outputtestdir) - def test_when_incorrect_args_then_systemexit_risen_with_expected_message(self): + def test_when_incorrect_args_then_systemexit_raised_with_expected_message(self): # 1. Set up test data mainArgs = [""] @@ -57,7 +58,7 @@ def test_when_incorrect_args_then_systemexit_risen_with_expected_message(self): assert isinstance(pytest_wrapped_e.type, SystemExit) assert pytest_wrapped_e.value.code == expectedMssg - def test_when_incorrect_input_args_systemexit_risen_with_expected_message(self): + def test_when_incorrect_input_args_systemexit_raised_with_expected_message(self): # 1. Set up test data mainArgs = ["-o", "test1"] opts, args = getopt.getopt(mainArgs, "hi:o:", ["ifile=", "ofile="]) @@ -68,13 +69,10 @@ def test_when_incorrect_input_args_systemexit_risen_with_expected_message(self): expectedMssg = "Error: {0}".format(reason) # 3. Run test - with pytest.raises(SystemExit) as pytest_wrapped_e: + with pytest.raises(SystemExit, match=re.escape(expectedMssg)): main.main(mainArgs) - # 4. Verify expectations - assert isinstance(pytest_wrapped_e.type, SystemExit) - assert pytest_wrapped_e.value.code == expectedMssg - + def test_when_giving_correct_arguments_then_does_not_raise_systemexit(self): # 1. Set up test data test_dir = "output_test_main_unit" @@ -82,59 +80,9 @@ def test_when_giving_correct_arguments_then_does_not_raise_systemexit(self): mainArgs = ["-i", "test1", "-i", "test2", "--i", "test3", "--o", outputtestdir] opts, args = getopt.getopt(mainArgs, "hi:o:", ["ifile=", "ofile="]) - # 2. Set up expectations - reasons = [ - "Not all arguments were given.", - "The first three arguments should be input files.\n" - + " Given: {}\n{}\n{}\n".format(opts[0], opts[1], opts[2]), - "The last argument should be the output directory.", - ] - - # 3. Run test - with pytest.raises(SystemExit) as pytest_wrapped_e: + # 2. Run test + with pytest.raises(SystemExit, match="Not all arguments were given."): main.main(mainArgs) - - # 4. Verify expectations (it should actually not get here) - assert isinstance(pytest_wrapped_e.type, SystemExit) - for reason in reasons: - expectedMssg = "Error: {0}".format(reason) - assert pytest_wrapped_e.value.code != expectedMssg + - def ARCHIVED_test_when_giving_non_existent_input_file_then_raises_io_exception( - self, - ): - # 1. Set up test data - file_path = "test1" - mainArgs = ["-i", file_path] - - # 2. Set up expectations - reason = "The given file path {} could not be found.".format(file_path) - - # 3. Run test - with pytest.raises(IOError) as e_info: - main.main(mainArgs) - - # 4. Verify final expectations - exception_message = str(e_info.value) - assert ( - exception_message == reason - ), "" + "Expected exception message {}, retrieved {}".format( - reason, exception_message - ) - - def ARCHIVED_test_when_giving_existent_empty_input_file_then_does_not_raise_io_exception( - self, - ): - # 1. Set up test data - test_dir = TestUtils.get_local_test_data_dir("main_test_data") - file_name = "test_ini_file.ini" - file_path = os.path.join(test_dir, file_name) - mainArgs = ["-i", file_path] - - # 2. Set up expectations - assert os.path.exists(file_path) - - # 3. Run test - main.main(mainArgs) - From 88461d3a4ef149eb8f6bd9daf648ca4812a0db67 Mon Sep 17 00:00:00 2001 From: Tjalling-dejong Date: Tue, 19 Nov 2024 15:16:32 +0100 Subject: [PATCH 5/9] fixed tests voor test_main.py --- tests/test_main.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/tests/test_main.py b/tests/test_main.py index 8bba821b..b0c1cd76 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -47,16 +47,12 @@ def test_when_incorrect_args_then_systemexit_raised_with_expected_message(self): mainArgs = [""] # 2. Set up expectations - reason = "Not all arguments were given." - expectedMssg = "Error: {0}".format(reason) + expectedMssg = "Error: Not all arguments were given." # 3. Run test - with pytest.raises(SystemExit) as pytest_wrapped_e: + with pytest.raises(SystemExit, match=expectedMssg): main.main(mainArgs) - # 4. Verify expectations - assert isinstance(pytest_wrapped_e.type, SystemExit) - assert pytest_wrapped_e.value.code == expectedMssg def test_when_incorrect_input_args_systemexit_raised_with_expected_message(self): # 1. Set up test data From 90f0581a216111852eab14cd4e493c031abd6132 Mon Sep 17 00:00:00 2001 From: Tjalling-dejong Date: Tue, 19 Nov 2024 15:17:47 +0100 Subject: [PATCH 6/9] changed cumtrapz to cumalitive_trapezoid --- fm2prof/CrossSection.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/fm2prof/CrossSection.py b/fm2prof/CrossSection.py index 0a150f40..d3347424 100644 --- a/fm2prof/CrossSection.py +++ b/fm2prof/CrossSection.py @@ -8,7 +8,7 @@ import numpy as np import pandas as pd import scipy.optimize as so -from scipy.integrate import cumtrapz +from scipy.integrate import cumulative_trapezoid from tqdm import tqdm from fm2prof import Functions as FE @@ -374,10 +374,10 @@ def get_timeseries(name: str): # Compute 1D volume as integral of width with respect to z times length self._css_total_volume = np.append( - [0], cumtrapz(self._css_total_width, self._css_z) * self.length + [0], cumulative_trapezoid(self._css_total_width, self._css_z) * self.length ) self._css_flow_volume = np.append( - [0], cumtrapz(self._css_flow_width, self._css_z) * self.length + [0], cumulative_trapezoid(self._css_flow_width, self._css_z) * self.length ) # If sd correction is run, these attributes will be updated. From b24da73cb818e3714a686e06629a136a20083023 Mon Sep 17 00:00:00 2001 From: Tjalling-dejong Date: Tue, 19 Nov 2024 17:04:07 +0100 Subject: [PATCH 7/9] updated gitignore --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index caddcdaf..3b67e21e 100644 --- a/.gitignore +++ b/.gitignore @@ -9,4 +9,5 @@ /build /documentation -*.log \ No newline at end of file +*.log +.coverage \ No newline at end of file From 26710b8d16dc4a4cbad2a205c1ae00a1c7e314cb Mon Sep 17 00:00:00 2001 From: Tjalling-dejong Date: Tue, 26 Nov 2024 14:23:15 +0100 Subject: [PATCH 8/9] changed incorrect use of not in conditional --- fm2prof/IniFile.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/fm2prof/IniFile.py b/fm2prof/IniFile.py index 2ece987d..5462f244 100644 --- a/fm2prof/IniFile.py +++ b/fm2prof/IniFile.py @@ -101,7 +101,7 @@ def __init__(self, file_path: Union[Path, str] = ".", logger: Logger = None): if file_path is None: self.set_logger_message( - f"No ini file given, using default options", "warning" + "No ini file given, using default options", "warning" ) return else: @@ -113,7 +113,7 @@ def __init__(self, file_path: Union[Path, str] = ".", logger: Logger = None): self._read_inifile(file_path) elif file_path.is_dir(): self.set_logger_message( - f"No ini file given, using default options", "warning" + "No ini file given, using default options", "warning" ) pass else: @@ -122,7 +122,7 @@ def __init__(self, file_path: Union[Path, str] = ".", logger: Logger = None): @property def _file_dir(self) -> Path: - if not self._file is None: + if self._file is not None: return self._file.parent return Path().cwd() From c1cdcd8c696072688fa08617115fbf4c46f31ddc Mon Sep 17 00:00:00 2001 From: Tjalling-dejong Date: Tue, 3 Dec 2024 10:56:24 +0100 Subject: [PATCH 9/9] added file path check --- fm2prof/MaskOutputFile.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/fm2prof/MaskOutputFile.py b/fm2prof/MaskOutputFile.py index 664c04e9..0f2c06b5 100644 --- a/fm2prof/MaskOutputFile.py +++ b/fm2prof/MaskOutputFile.py @@ -82,6 +82,8 @@ def write_mask_output_file(file_path: Union[Path, str], mask_points: list) -> No file_path {str} -- file_path where to store the geojson. mask_points {list} -- List of features to output. """ + if not file_path: + raise ValueError("file_path is required.") file_path = Path(file_path) if not mask_points: raise ValueError("mask_points cannot be empty.")