Best Python code snippet using avocado_python
toml_v1_parser_test.py
Source:toml_v1_parser_test.py
...24 data_builder = get_data_builder(SANSFacility.ISIS, file_information)25 data_builder.set_sample_scatter("SANS2D00022024")26 data_builder.set_sample_scatter_period(3)27 return data_builder.build()28 def _setup_parser(self, dict_vals) -> TomlV1Parser:29 def _add_missing_mandatory_key(dict_to_check: Dict, key_path: List[str], replacement_val):30 _dict = dict_to_check31 for key in key_path[0:-1]:32 if key not in _dict:33 _dict[key] = {}34 _dict = _dict[key]35 if key_path[-1] not in _dict:36 _dict[key_path[-1]] = replacement_val # Add in child value37 return dict_to_check38 self._mocked_data_info = self._get_mock_data_info()39 # instrument key needs to generally be present40 dict_vals = _add_missing_mandatory_key(dict_vals, ["instrument", "name"], "LOQ")41 dict_vals = _add_missing_mandatory_key(dict_vals, ["detector", "configuration", "selected_detector"], "rear")42 return TomlV1Parser(dict_vals, file_information=None)43 def test_instrument(self):44 parser = self._setup_parser(dict_vals={"instrument": {"name": SANSInstrument.SANS2D.value}})45 inst = parser._implementation.instrument46 self.assertTrue(inst is SANSInstrument.SANS2D, msg="Got %r instead" % inst)47 def test_validate_is_called_on_init(self):48 schema_validator = mock.Mock()49 # No implementation needed50 with mock.patch("sans.user_file.toml_parsers.toml_v1_parser.TomlV1Parser._get_impl"):51 TomlV1Parser(dict_to_parse=None, schema_validator=schema_validator, file_information=None)52 self.assertTrue(schema_validator.validate.called)53 def _loop_over_supported_keys(self, supported_keys, top_level_keys):54 top_level_dict = {}55 dict_view = top_level_dict56 # We need to append a mock object using the bottom key in the below loop57 for key in top_level_keys[:-1]:58 dict_view[key] = {}59 dict_view = dict_view[key]60 for k, func in supported_keys:61 expected = mock.NonCallableMock()62 dict_view[top_level_keys[-1]] = {k: expected}63 parser = self._setup_parser(top_level_dict)64 val = func(parser)65 self.assertEqual(expected, val, "Failed to get key {0}".format(k))66 def test_instrument_configuration_parsed(self):67 supported_keys = [68 ("collimation_length", lambda x: x.get_state_convert_to_q().q_resolution_collimation_length),69 ("gravity_extra_length", lambda x: x.get_state_convert_to_q().gravity_extra_length),70 ("sample_aperture_diameter", lambda x: x.get_state_convert_to_q().q_resolution_a2),71 ("sample_offset", lambda x: x.get_state_move(None).sample_offset),72 ("gravity_enabled", lambda x: x.get_state_convert_to_q().use_gravity)73 ]74 self._loop_over_supported_keys(supported_keys=supported_keys, top_level_keys=["instrument", "configuration"])75 def test_detector_configuration_parsed(self):76 supported_keys = [77 ("rear_scale", lambda x: x.get_state_scale(file_information=None).scale),78 # ("front_scale", lambda x: x.get_state_scale()) TODO this is issue # 2794879 ]80 self._loop_over_supported_keys(supported_keys=supported_keys, top_level_keys=["detector", "configuration"])81 top_level_dict = {"detector": {"configuration": {}}}82 config_dict = top_level_dict["detector"]["configuration"]83 expected_reduction_mode = ReductionMode.ALL84 config_dict["selected_detector"] = expected_reduction_mode.value85 config_dict["front_centre"] = {"x": 1, "y": 2}86 config_dict["rear_centre"] = {"x": 2, "y": 3}87 def get_beam_position(state_move, bank_enum):88 x = state_move.detectors[bank_enum.value].sample_centre_pos189 y = state_move.detectors[bank_enum.value].sample_centre_pos290 return x, y91 parser = self._setup_parser(dict_vals=top_level_dict)92 state_move = parser.get_state_move(None)93 self.assertTrue(parser.get_state_reduction_mode().reduction_mode is expected_reduction_mode)94 self.assertEqual((1, 2), get_beam_position(state_move, DetectorType.HAB))95 self.assertEqual((2, 3), get_beam_position(state_move, DetectorType.LAB))96 def test_all_centre_entry(self):97 input_dict = {"detector": {"configuration": {"all_centre": {"x": 2, "y": 3.4}}}}98 parser = self._setup_parser(input_dict)99 for i in [ReductionMode.HAB, ReductionMode.LAB]:100 move = parser.get_state_move(None)101 self.assertEqual(2, move.detectors[i.value].sample_centre_pos1)102 self.assertEqual(3.4, move.detectors[i.value].sample_centre_pos2)103 def test_throws_when_all_and_rear_specified(self):104 input_dict = {"detector": {"configuration": {"all_centre": {"x": 2, "y": 3.4},105 "rear_centre": {"x": 2}}}}106 with self.assertRaisesRegex(ValueError, "front_centre"):107 self._setup_parser(input_dict)108 def test_throws_when_all_and_front_specified(self):109 input_dict = {"detector": {"configuration": {"all_centre": {"x": 2, "y": 3.4},110 "front_centre": {"x": 2}}}}111 with self.assertRaisesRegex(ValueError, "front_centre"):112 self._setup_parser(input_dict)113 def test_rear_front_maps_to_enum_correctly(self):114 for user_input, enum_val in [("rear", ReductionMode.LAB), ("front", ReductionMode.HAB),115 ("all", ReductionMode.ALL), ("merged", ReductionMode.MERGED)]:116 input_dict = {"detector": {"configuration": {"selected_detector": user_input}}}117 parser = self._setup_parser(dict_vals=input_dict)118 self.assertEqual(enum_val, parser.get_state_reduction_mode().reduction_mode)119 def test_legacy_reduction_mode_rejected(self):120 for legacy_input in ["hab", "lab"]:121 with self.assertRaisesRegex(ValueError, "rear"):122 input_dict = {"detector": {"configuration": {"selected_detector": legacy_input}}}123 self._setup_parser(dict_vals=input_dict)124 def test_reduction_mode_mandatory(self):125 with self.assertRaisesRegex(MissingMandatoryParam, "selected_detector"):126 TomlV1Parser({"instrument": {"name": "LOQ"}}, None)127 def test_binning_commands_parsed(self):128 # Wavelength129 for bin_type in ["Lin", "Log"]:130 wavelength_dict = {"binning": {"wavelength": {"start": 1.1, "step": 0.1, "stop": 2.2, "type": bin_type}}}131 wavelength = self._setup_parser(wavelength_dict).get_state_wavelength()132 self.assertEqual((1.1, 2.2), wavelength.wavelength_interval.wavelength_full_range)133 self.assertEqual(0.1, wavelength.wavelength_interval.wavelength_step)134 self.assertEqual(RangeStepType(bin_type), wavelength.wavelength_step_type)135 one_d_reduction_q_dict = {"binning": {"1d_reduction": {"binning": "1.0, 0.1, 2.0, -0.2, 3.0",136 "radius_cut": 12.3,137 "wavelength_cut": 23.4}}}138 one_d_convert_to_q = self._setup_parser(one_d_reduction_q_dict).get_state_convert_to_q()139 self.assertEqual(1.0, one_d_convert_to_q.q_min)140 self.assertEqual(3.0, one_d_convert_to_q.q_max)141 self.assertEqual("1.0, 0.1, 2.0, -0.2, 3.0", one_d_convert_to_q.q_1d_rebin_string.strip())142 self.assertEqual(12.3, one_d_convert_to_q.radius_cutoff)143 self.assertEqual(23.4, one_d_convert_to_q.wavelength_cutoff)144 two_d_reduction_q_dict = {"binning": {"2d_reduction": {"step": 1.0, "stop": 5.0, "type": "Lin"}}}145 results = self._setup_parser(two_d_reduction_q_dict)146 two_d_convert_to_q = results.get_state_convert_to_q()147 self.assertEqual(5.0, two_d_convert_to_q.q_xy_max)148 self.assertEqual(1.0, two_d_convert_to_q.q_xy_step)149 self.assertTrue(two_d_convert_to_q.q_xy_step_type is RangeStepType.LIN)150 self.assertTrue(results.get_state_calculate_transmission().rebin_type is RebinType.REBIN)151 def test_reduction_commands_parsed(self):152 top_level_dict = {"reduction": {"merged": {},153 "events": {}}}154 merged_dict = top_level_dict["reduction"]["merged"]155 merged_dict["merge_range"] = {"min": 1, "max": 2, "use_fit": False}156 merged_dict["rescale"] = {"min": 0.1, "max": 0.2, "use_fit": True}157 merged_dict["shift"] = {"min": 0.3, "max": 0.4, "use_fit": True}158 events_dict = top_level_dict["reduction"]["events"]159 expected_binning = "1,1,10"160 events_dict["binning"] = expected_binning161 parsed_obj = self._setup_parser(top_level_dict)162 self.assertEqual(parsed_obj.get_state_compatibility().time_rebin_string, expected_binning)163 state_reduction = parsed_obj.get_state_reduction_mode()164 self.assertEqual(state_reduction.merge_min, 1)165 self.assertEqual(state_reduction.merge_max, 2)166 self.assertEqual(state_reduction.merge_mask, False)167 # Note this should take the max and min of rescale and shift when both are present168 self.assertEqual(state_reduction.merge_range_min, 0.1)169 self.assertEqual(state_reduction.merge_range_max, 0.4)170 self.assertEqual(state_reduction.merge_fit_mode, FitModeForMerge.BOTH)171 def test_detector_parsed(self):172 top_level_dict = {"detector": {"correction": {"direct": {},173 "flat": {},174 "tube": {},175 "position": {}},176 "radius_limit": {"min": None,177 "max": None}}}178 correction_dict = top_level_dict["detector"]["correction"]179 direct_front = mock.NonCallableMock()180 direct_rear = mock.NonCallableMock()181 correction_dict["direct"]["front_file"] = direct_front182 correction_dict["direct"]["rear_file"] = direct_rear183 flat_front = mock.NonCallableMock()184 flat_rear = mock.NonCallableMock()185 correction_dict["flat"]["front_file"] = flat_front186 correction_dict["flat"]["rear_file"] = flat_rear187 tube_file = mock.NonCallableMock()188 correction_dict["tube"]["file"] = tube_file189 radius_limit = top_level_dict["detector"]["radius_limit"]190 radius_limit["min"] = 100191 radius_limit["max"] = 200192 parser = self._setup_parser(top_level_dict)193 wavelength_state = parser.get_state_wavelength_and_pixel_adjustment()194 # Where Front = HAB and Rear = LAB in SANS terminology195 self.assertEqual(wavelength_state.adjustment_files[DetectorType.LAB.value].wavelength_adjustment_file,196 direct_rear)197 self.assertEqual(wavelength_state.adjustment_files[DetectorType.HAB.value].wavelength_adjustment_file,198 direct_front)199 self.assertEqual(wavelength_state.adjustment_files[DetectorType.LAB.value].pixel_adjustment_file,200 flat_rear)201 self.assertEqual(wavelength_state.adjustment_files[DetectorType.HAB.value].pixel_adjustment_file,202 flat_front)203 self.assertEqual(parser.get_state_adjustment(None).calibration, tube_file)204 mask = parser.get_state_mask(None)205 self.assertIsInstance(mask, StateMask)206 self.assertEqual(100, mask.radius_min)207 self.assertEqual(200, mask.radius_max)208 def test_detector_correction_position(self):209 top_level_dict = {"detector": {"correction": {"position": {}}}}210 position_dict = top_level_dict["detector"]["correction"]["position"]211 for adjustment in ["_x", "_y", "_z", "_rot", "_radius", "_side", "_x_tilt", "_y_tilt", "_z_tilt"]:212 position_dict["front" + adjustment] = mock.NonCallableMock()213 position_dict["rear" + adjustment] = mock.NonCallableMock()214 def assert_lab_hab_val(move_state, adjustment_name, state_name):215 lab_val = getattr(move_state.detectors[DetectorType.LAB.value], state_name)216 hab_val = getattr(move_state.detectors[DetectorType.HAB.value], state_name)217 self.assertEqual(position_dict["front" + adjustment_name], hab_val)218 self.assertEqual(position_dict["rear" + adjustment_name], lab_val)219 state_move = self._setup_parser(top_level_dict).get_state_move(None)220 assert_lab_hab_val(state_move, "_x", "x_translation_correction")221 assert_lab_hab_val(state_move, "_y", "y_translation_correction")222 def test_q_resolution(self):223 top_level_dict = {"q_resolution": {}}224 q_resolution_dict = top_level_dict["q_resolution"]225 q_resolution_dict["enabled"] = True226 q_resolution_dict["moderator_file"] = mock.NonCallableMock()227 q_resolution_dict["source_aperture"] = 1228 q_resolution_dict["delta_r"] = 2229 q_resolution_dict["h1"], q_resolution_dict["h2"] = 3, 4230 q_resolution_dict["w1"], q_resolution_dict["w2"] = 5, 6231 q_resolution = self._setup_parser(top_level_dict).get_state_convert_to_q()232 self.assertEqual(True, q_resolution.use_q_resolution)233 self.assertEqual(1, q_resolution.q_resolution_a1)234 self.assertEqual(2, q_resolution.q_resolution_delta_r)235 self.assertEqual(3, q_resolution.q_resolution_h1)236 self.assertEqual(4, q_resolution.q_resolution_h2)237 self.assertEqual(5, q_resolution.q_resolution_w1)238 self.assertEqual(6, q_resolution.q_resolution_w2)239 self.assertEqual(q_resolution_dict["moderator_file"], q_resolution.moderator_file)240 def test_transmission(self):241 top_level_dict = {242 "instrument": {"configuration": {"norm_monitor": "", "trans_monitor": ""}},243 "normalisation": {"monitor": {"M3": {}, "M5": {}}},244 "transmission": {"monitor": {"M3": {}, "M5": {}}}245 }246 monitor_dict = top_level_dict["transmission"]["monitor"]247 m3_dict = monitor_dict["M3"]248 m3_dict["background"] = [100, 200]249 m3_dict["spectrum_number"] = 3250 m3_dict["shift"] = 10251 m3_dict["use_own_background"] = True252 top_level_dict["normalisation"]["monitor"]["M3"]["spectrum_number"] = 100253 m5_dict = monitor_dict["M5"]254 m5_dict["spectrum_number"] = 5255 m5_dict["use_own_background"] = False256 m5_dict["shift"] = -10257 top_level_dict["normalisation"]["monitor"]["M5"]["spectrum_number"] = 200258 top_level_dict["instrument"]["configuration"]["norm_monitor"] = "M3"259 top_level_dict["instrument"]["configuration"]["trans_monitor"] = "M3"260 parser = self._setup_parser(top_level_dict)261 calc_transmission = parser.get_state_calculate_transmission()262 self.assertEqual(100, calc_transmission.incident_monitor)263 self.assertEqual(3, calc_transmission.transmission_monitor)264 self.assertEqual(10, parser.get_state_move(None).monitor_4_offset)265 self.assertEqual({'3': 100}, calc_transmission.background_TOF_monitor_start)266 self.assertEqual({'3': 200}, calc_transmission.background_TOF_monitor_stop)267 # Check switching the selected monitor picks up correctly268 top_level_dict["instrument"]["configuration"]["norm_monitor"] = "M5"269 top_level_dict["instrument"]["configuration"]["trans_monitor"] = "M5"270 parser = self._setup_parser(top_level_dict)271 calc_transmission = parser.get_state_calculate_transmission()272 self.assertEqual(200, calc_transmission.incident_monitor)273 self.assertEqual(5, calc_transmission.transmission_monitor)274 self.assertEqual(-10, parser.get_state_move(None).monitor_5_offset)275 self.assertFalse(calc_transmission.background_TOF_monitor_start)276 self.assertFalse(calc_transmission.background_TOF_monitor_stop)277 with self.assertRaises(KeyError):278 top_level_dict["instrument"]["configuration"]["trans_monitor"] = "M999"279 self._setup_parser(top_level_dict)280 def test_transmission_with_different_norm_monitor(self):281 # A transmission run can be normalised by a different norm monitor. This is useful for cryostats282 # where a different transmission monitor is used due to physical space limitations on the instrument283 top_level_dict = {284 "instrument": {"configuration": {"norm_monitor": "M3", "trans_monitor": "M3"}},285 "normalisation": {"monitor": {"M3": {}, "M5": {}}},286 "transmission": {"monitor": {"M3": {}}}287 }288 monitor_dict = top_level_dict["transmission"]["monitor"]289 top_level_dict["normalisation"]["monitor"]["M3"]["spectrum_number"] = 3290 top_level_dict["normalisation"]["monitor"]["M5"]["spectrum_number"] = 5291 m3_dict = monitor_dict["M3"]292 m3_dict["spectrum_number"] = 3293 m3_dict["use_different_norm_monitor"] = True294 with self.assertRaises(KeyError):295 self._setup_parser(top_level_dict)296 m3_dict["trans_norm_monitor"] = "M5"297 parser = self._setup_parser(top_level_dict)298 calc_transmission = parser.get_state_calculate_transmission()299 self.assertEqual(5, calc_transmission.incident_monitor)300 self.assertEqual(3, calc_transmission.transmission_monitor)301 def test_transmission_monitor_parser_ignores_roi(self):302 top_level_dict = {303 "instrument": {"configuration": {"trans_monitor": "ROI"}},304 "transmission": {"monitor": {"M3": {}},305 "ROI": {"file": "foo"}}306 }307 monitor_dict = top_level_dict["transmission"]["monitor"]308 m3_dict = monitor_dict["M3"]309 m3_dict["spectrum_number"] = 3310 parser = self._setup_parser(top_level_dict)311 calc_transmission = parser.get_state_calculate_transmission()312 self.assertEqual(3, calc_transmission.transmission_monitor)313 def test_transmission_monitor_parses_roi(self):314 expected_file_name = "test.xml"315 top_level_dict = {316 "instrument": {"configuration": {"trans_monitor": "ROI"}},317 "transmission": {"ROI": {"file": expected_file_name}}318 }319 result = self._setup_parser(top_level_dict)320 self.assertEqual([expected_file_name], result.get_state_calculate_transmission().transmission_roi_files)321 def test_transmission_monitor_errors_for_multiple_values(self):322 top_level_dict = {323 "instrument": {"configuration": {"trans_monitor": "ROI"}},324 "transmission": {"ROI": {"file": ["test1.xml", "test2.xml"]}}325 }326 with self.assertRaisesRegex(ValueError, "single file"):327 self._setup_parser(top_level_dict)328 def test_transmission_monitor_errors_for_empty_value(self):329 top_level_dict = {330 "instrument": {"configuration": {"trans_monitor": "ROI"}},331 "transmission": {"ROI": {"file": ""}}332 }333 with self.assertRaisesRegex(ValueError, "empty"):334 self._setup_parser(top_level_dict)335 def test_transmission_fitting(self):336 top_level_dict = {"transmission": {"fitting": {}}}337 fitting_dict = top_level_dict["transmission"]["fitting"]338 fitting_dict["enabled"] = True339 fitting_dict["function"] = "Polynomial"340 fitting_dict["polynomial_order"] = 5341 fitting_dict["parameters"] = {"lambda_min": 20, "lambda_max": 30}342 def check_can_and_sample(parser, attr_name, expected):343 can = parser.get_state_calculate_transmission().fit[DataType.CAN.value]344 sample = parser.get_state_calculate_transmission().fit[DataType.SAMPLE.value]345 self.assertEqual(expected, getattr(can, attr_name))346 self.assertEqual(expected, getattr(sample, attr_name))347 parser = self._setup_parser(top_level_dict)348 check_can_and_sample(parser, "fit_type", FitType.POLYNOMIAL)349 check_can_and_sample(parser, "polynomial_order", 5)350 check_can_and_sample(parser, "wavelength_low", 20)351 check_can_and_sample(parser, "wavelength_high", 30)352 # Linear / Log should not set the above353 fitting_dict["function"] = "Linear"354 parser = self._setup_parser(top_level_dict)355 check_can_and_sample(parser, "fit_type", FitType.LINEAR)356 check_can_and_sample(parser, "polynomial_order", 0)357 check_can_and_sample(parser, "wavelength_low", 20)358 check_can_and_sample(parser, "wavelength_high", 30)359 fitting_dict["function"] = "NotSet"360 with self.assertRaises(KeyError):361 self._setup_parser(top_level_dict)362 fitting_dict["enabled"] = False363 self.assertIsNotNone(self._setup_parser(top_level_dict))364 def test_normalisation_normalization_both_accepted(self):365 for norm_key in "normalisation", "normalization":366 norm_dict = {367 "instrument": {"configuration": {"norm_monitor": "M1"}},368 norm_key: {"monitor": {"M1": {}, "A2": {}}}369 }370 monitor_dict = norm_dict[norm_key]["monitor"]371 m1_dict = monitor_dict["M1"]372 m1_dict["background"] = [100, 200]373 m1_dict["spectrum_number"] = 1374 calc_transmission = self._setup_parser(norm_dict).get_state_calculate_transmission()375 self.assertEqual({'1': 100}, calc_transmission.background_TOF_monitor_start)376 self.assertEqual({'1': 200}, calc_transmission.background_TOF_monitor_stop)377 def test_parsing_all_monitor_background(self):378 top_level_dict = {"normalisation": {"all_monitors": {"enabled": True,379 "background": [1200, 2400]}}}380 parsed = self._setup_parser(top_level_dict)381 parsed_transmission = parsed.get_state_calculate_transmission()382 self.assertEqual(1200, parsed_transmission.background_TOF_general_start)383 self.assertEqual(2400, parsed_transmission.background_TOF_general_stop)384 parsed_norm_monitors = parsed.get_state_normalize_to_monitor(None)385 self.assertEqual(1200, parsed_norm_monitors.background_TOF_general_start)386 self.assertEqual(2400, parsed_norm_monitors.background_TOF_general_stop)387 def test_parsing_all_monitor_background_ignored_false(self):388 top_level_dict = {"normalisation": {"all_monitors": {"enabled": False,389 "background": [1200, 2400]}}}390 parsed = self._setup_parser(top_level_dict)391 parsed_transmission = parsed.get_state_calculate_transmission()392 self.assertIsNone(parsed_transmission.background_TOF_general_start)393 self.assertIsNone(parsed_transmission.background_TOF_general_stop)394 parsed_norm_monitors = parsed.get_state_normalize_to_monitor(None)395 self.assertIsNone(parsed_norm_monitors.background_TOF_general_start)396 self.assertIsNone(parsed_norm_monitors.background_TOF_general_stop)397 def test_parse_normalisation(self):398 # A2 is intentional to check were not hardcoded to Monitor x (Mx), such that a user could have FooY399 top_level_dict = {400 "instrument": {"configuration": {"norm_monitor": ""}},401 "normalisation": {"monitor": {"M1": {}, "A2": {}}}402 }403 monitor_dict = top_level_dict["normalisation"]["monitor"]404 m1_dict = monitor_dict["M1"]405 m1_dict["background"] = [100, 200]406 m1_dict["spectrum_number"] = 1407 a2_dict = monitor_dict["A2"]408 a2_dict["background"] = [400, 800]409 a2_dict["spectrum_number"] = 2410 top_level_dict["instrument"]["configuration"]["norm_monitor"] = "M1"411 parser = self._setup_parser(top_level_dict)412 norm_to_monitor = parser.get_state_normalize_to_monitor(None)413 self.assertEqual({'1': 100}, norm_to_monitor.background_TOF_monitor_start)414 self.assertEqual({'1': 200}, norm_to_monitor.background_TOF_monitor_stop)415 self.assertEqual(1, norm_to_monitor.incident_monitor)416 top_level_dict["instrument"]["configuration"]["norm_monitor"] = "A2"417 parser = self._setup_parser(top_level_dict)418 norm_to_monitor = parser.get_state_calculate_transmission()419 self.assertEqual({'2': 400}, norm_to_monitor.background_TOF_monitor_start)420 self.assertEqual({'2': 800}, norm_to_monitor.background_TOF_monitor_stop)421 self.assertEqual(2, norm_to_monitor.incident_monitor)422 top_level_dict["instrument"]["configuration"]["norm_monitor"] = "NotThere"423 with self.assertRaises(KeyError):424 self._setup_parser(top_level_dict)425 def test_parse_mask_spatial(self):426 top_level_dict = {"mask": {"spatial": {427 "beamstop_shadow": {},428 "front": {},429 "rear": {},430 "mask_pixels": [],431 }}}432 rear_spatial_dict = top_level_dict["mask"]["spatial"]["rear"]433 rear_spatial_dict["detector_columns"] = [101, 102]434 rear_spatial_dict["detector_rows"] = [201, 202]435 rear_spatial_dict["detector_column_ranges"] = [[0, 10], [20, 30]]436 rear_spatial_dict["detector_row_ranges"] = [[40, 50]]437 front_spatial_dict = top_level_dict["mask"]["spatial"]["front"]438 front_spatial_dict["detector_columns"] = [1, 2]439 front_spatial_dict["detector_rows"] = [2, 3]440 front_spatial_dict["detector_column_ranges"] = [[0, 10]]441 front_spatial_dict["detector_row_ranges"] = [[100, 400]]442 top_level_dict["mask"]["spatial"]["beamstop_shadow"] = {"width": 10, "angle": 180}443 mask_pixels_expected = [1, 2, 4, 17000] # 17000 is in HAB on LOQ444 top_level_dict["mask"]["spatial"]["mask_pixels"] = mask_pixels_expected445 mask_state = self._setup_parser(top_level_dict).get_state_mask(None)446 rear_result = mask_state.detectors[DetectorType.LAB.value]447 self.assertIsInstance(rear_result, StateMaskDetectors)448 self.assertEqual([101, 102], rear_result.single_vertical_strip_mask)449 self.assertEqual([201, 202], rear_result.single_horizontal_strip_mask)450 self.assertEqual([0, 20], rear_result.range_vertical_strip_start)451 self.assertEqual([10, 30], rear_result.range_vertical_strip_stop)452 self.assertEqual([40], rear_result.range_horizontal_strip_start)453 self.assertEqual([50], rear_result.range_horizontal_strip_stop)454 front_result = mask_state.detectors[DetectorType.HAB.value]455 self.assertIsInstance(front_result, StateMaskDetectors)456 self.assertEqual([1, 2], front_result.single_vertical_strip_mask)457 self.assertEqual([2, 3], front_result.single_horizontal_strip_mask)458 self.assertEqual([0], front_result.range_vertical_strip_start)459 self.assertEqual([10], front_result.range_vertical_strip_stop)460 self.assertEqual([100], front_result.range_horizontal_strip_start)461 self.assertEqual([400], front_result.range_horizontal_strip_stop)462 # Pixel masks463 self.assertEqual([1, 2, 4], mask_state.detectors[DetectorType.LAB.value].single_spectra)464 self.assertEqual([17000], mask_state.detectors[DetectorType.HAB.value].single_spectra)465 # Beamstop angle466 self.assertEqual(180, mask_state.beam_stop_arm_angle)467 self.assertEqual(10, mask_state.beam_stop_arm_width)468 def test_beamstop_masking_x_y_positions(self):469 for beamstop_values in [{"width": 0.1, "angle": 0.2},470 {"width": 0.1, "angle": 0.2, "x_pos": 0.3, "y_pos": 0.4}]:471 parser = self._setup_parser({"mask": {"spatial": {"beamstop_shadow": beamstop_values}}})472 masks = parser.get_state_mask(None)473 self.assertEqual(beamstop_values["width"], masks.beam_stop_arm_width)474 self.assertEqual(beamstop_values["angle"], masks.beam_stop_arm_angle)475 self.assertEqual(beamstop_values.get("x_pos", 0.0), masks.beam_stop_arm_pos1)476 self.assertEqual(beamstop_values.get("y_pos", 0.0), masks.beam_stop_arm_pos2)477 def test_parse_mask(self):478 top_level_dict = {"mask": {479 "prompt_peak": {},480 "mask_files": [],481 "time": {"tof": []}482 },483 "phi": {}}484 top_level_dict["mask"]["prompt_peak"] = {"start": 101, "stop": 102}485 mask_files_mock = [mock.NonCallableMock()]486 top_level_dict["mask"]["mask_files"] = mask_files_mock487 time_dict = top_level_dict["mask"]["time"]488 time_dict["tof"].extend([{"start": 100, "stop": 200},489 {"start": 300, "stop": 400}])490 top_level_dict["mask"]["phi"] = {"mirror": False,491 "start": -50, "stop": 50}492 parser_result = self._setup_parser(top_level_dict)493 masks = parser_result.get_state_mask(None)494 self.assertIsInstance(masks, StateMask)495 self.assertEqual(mask_files_mock, masks.mask_files)496 self.assertEqual([100, 300], masks.bin_mask_general_start)497 self.assertEqual([200, 400], masks.bin_mask_general_stop)498 self.assertEqual(False, masks.use_mask_phi_mirror)499 self.assertEqual(-50, masks.phi_min)500 self.assertEqual(50, masks.phi_max)501 # TODO split below into own test502 transmission_state = parser_result.get_state_calculate_transmission()503 self.assertEqual(101, transmission_state.prompt_peak_correction_min)504 self.assertEqual(102, transmission_state.prompt_peak_correction_max)505 self.assertTrue(transmission_state.prompt_peak_correction_enabled)506 norm_state = parser_result.get_state_normalize_to_monitor(None)...
test_cli.py
Source:test_cli.py
...183 c = cli.CLIConfigManager()184 c._reset()185 except:186 pass187 def _setup_parser(self):188 return _parser_from_dict({189 "arguments": [190 {"name": "foo"},191 {"name": "foo2", "default": "bar"}192 ],193 })194 def test_no_partial_def(self):195 c = cli.CLIConfigManager()196 p = self._setup_parser()197 config = vars(p.parse_args('--foo baz'))198 self.assertDictEqual(config, {'foo':'baz', 'foo2': 'bar', 'site': 'local'})199 config = vars(p.parse_args('--foo2 baz'))200 self.assertDictEqual(config, {'foo':None, 'foo2': 'baz','site':'local'})201 def test_partial_def_1(self):202 c = cli.CLIConfigManager()203 c.user_defaults = {'foo': 'XX', 'foo2': 'YY'}204 p = self._setup_parser()205 config = vars(p.parse_args('--foo baz'))206 self.assertDictEqual(config, {'foo':'baz', 'foo2': 'YY','site':'local'})207 c.user_defaults = {'foo': 'XX'}208 p = self._setup_parser()209 config = vars(p.parse_args('--foo baz'))210 self.assertDictEqual(config, {'foo':'baz', 'foo2': 'bar','site':'local'})211 c.user_defaults = {'foo2': 'YY'}212 p = self._setup_parser()213 config = vars(p.parse_args('--foo baz'))214 self.assertDictEqual(config, {'foo':'baz', 'foo2': 'YY','site':'local'})215 def test_partial_def_2(self):216 c = cli.CLIConfigManager()217 c.site_defaults = {'foo': 'XX'}218 p = self._setup_parser()219 config = vars(p.parse_args('--foo baz'))220 self.assertDictEqual(config, {'foo':'baz', 'foo2': 'bar','site':'local'})221 c.site_defaults = {'foo': 'XX', 'foo2': 'YY'}222 p = self._setup_parser()223 config = vars(p.parse_args('--foo2 baz'))224 self.assertDictEqual(config, {'foo':'XX', 'foo2': 'baz','site':'local'})225 c.site_defaults = {'foo': 'XX'}226 p = self._setup_parser()227 config = vars(p.parse_args('--foo2 baz'))228 self.assertDictEqual(config, {'foo':'XX', 'foo2': 'baz','site':'local'})229 c.site_defaults = {'foo2': 'YY'}230 p = self._setup_parser()231 config = vars(p.parse_args('--foo2 baz'))232 self.assertDictEqual(config, {'foo':None, 'foo2': 'baz','site':'local'})233 def test_partial_def_3(self):234 c = cli.CLIConfigManager()235 c.user_defaults = {'foo': 'XX', 'foo2': 'YY'}236 c.site_defaults = {'foo': 'XXQ', 'foo2': 'YYQ'}237 p = self._setup_parser()238 config = vars(p.parse_args('--foo baz'))239 self.assertDictEqual(config, {'foo':'baz', 'foo2': 'YY','site':'local'})240 c.user_defaults = {'foo': 'XX', 'foo2': 'YY'}241 c.site_defaults = {'foo': 'XXQ', 'foo2': 'YYQ'}242 p = self._setup_parser()243 config = vars(p.parse_args('--foo2 baz'))244 self.assertDictEqual(config, {'foo':'XX', 'foo2': 'baz','site':'local'})245 c.user_defaults = {'foo': 'XX'}246 c.site_defaults = {'foo': 'XXQ', 'foo2': 'YYQ'}247 p = self._setup_parser()248 config = vars(p.parse_args('--foo baz'))249 self.assertDictEqual(config, {'foo':'baz', 'foo2': 'YYQ','site':'local'})250 c.user_defaults = {'foo2': 'YY'}251 c.site_defaults = {'foo': 'XXQ', 'foo2': 'YYQ'}252 p = self._setup_parser()253 config = vars(p.parse_args('--foo2 baz'))254 self.assertDictEqual(config, {'foo':'XXQ', 'foo2': 'baz','site':'local'})255class TestParseDummyInput(unittest.TestCase):256 def tearDown(self):257 try:258 temp = cli.CLIConfigManager()259 temp._reset()260 except Exception:261 pass262 def test_parse_dummy_input(self):263 # get dir of currently executing script:264 cwd = os.path.dirname(os.path.realpath(__file__))265 code_root = os.path.dirname(os.path.dirname(cwd))266 cli_obj = cli.MDTFTopLevelArgParser(...
cli.py
Source:cli.py
...48class CLI(BaseCLI, metaclass=CLIMeta):49 def __init__(self, parent=None, argname=None, *args, **kwargs):50 self.parent = parent51 self.argname = argname52 self._setup_parser()53 self._parse_args()54 def _setup_parser(self):55 if self.parent:56 self.parser = self.parent.subparsers.add_parser(self.argname)57 else:58 self.parser = argparse.ArgumentParser()59 for name, arg in self._meta.arguments.items():60 self.parser.add_argument(61 name,62 type=arg.argtype,63 help=arg.help_text,64 )65 def _parse_args(self):66 if self.parent is None:67 self.parser.parse_args(namespace=self)68 else:69 for argname, _ in self._meta.arguments.items():70 # print(argname)71 argument = getattr(self.parent, argname, None)72 setattr(self, argname, argument)73class TieredCLI(BaseCLI, metaclass=TieredCLIMeta):74 def __init__(self, *args, **kwargs):75 self._setup_parser()76 self._setup_subcommands()77 self._parse_args()78 def _setup_subcommands(self):79 self.subcommands = Subcommands()80 for argname, arg in self._meta.subcommands.items():81 command = arg(parent=self, argname=argname)82 self.subcommands.add(argname, command)83 def _setup_parser(self):84 self.parser = argparse.ArgumentParser()85 self.subparsers = self.parser.add_subparsers(86 help='Commands',87 dest='command'88 )89 def _parse_args(self):90 self.parser.parse_args(namespace=self)91 for subcommand in self.subcommands:92 subcommand._parse_args()93 async def call(self):94 command = getattr(self.subcommands, self.command)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!