def testThreeLetters(self): """ An argument that has three letters must result in a ValueError. """ error = ("^btop string 'ABC' has a trailing query letter 'C' with no " "corresponding subject letter$") assertRaisesRegex(self, ValueError, error, list, parseBtop('ABC'))
def testSettingValidation(self): # Mounting and unmounting test valid use, so this just tests invalid # values. with six.assertRaisesRegex(self, ValidationException, 'must be a dict'): Setting().set(SettingKey.GIRDER_MOUNT_INFORMATION, 'not a dict') with six.assertRaisesRegex(self, ValidationException, 'with the "path" key'): Setting().set(SettingKey.GIRDER_MOUNT_INFORMATION, {'no path': 'key'})
def testEmptyString(self): """ An empty string must produce an empty set of indices. """ error = ("^Illegal range ''. Ranges must single numbers or " "number-number\\.$") assertRaisesRegex(self, ValueError, error, parseRangeString, '')
def testOneLetter(self): """ An argument with just one letter must result in a ValueError. """ error = ("^btop string 'F' has a trailing query letter 'F' with no " "corresponding subject letter$") assertRaisesRegex(self, ValueError, error, list, parseBtop('F'))
def test_fsm_illegal_strict_event(self): six.assertRaisesRegex(self, utils.NodeStateInvalidEvent, 'no defined transition', self.node_info.fsm_event, istate.Events.finish, strict=True) self.assertIn('no defined transition', self.node_info.error) self.assertEqual(self.node_info.state, istate.States.error)
def test_material_set_properties(self): bad_absorb = '-1' bad_scattering = 0 good_absorb = '1' good_scattering = 2.0 material_obj = sample_details._Material(chemical_formula='V') with assertRaisesRegex(self, ValueError, "absorption_cross_section was: -1 which is impossible for a physical " "object"): material_obj.set_material_properties(abs_cross_sect=bad_absorb, scattering_cross_sect=good_scattering) # Check the immutability flag has not been set on a failure self.assertFalse(material_obj._is_material_props_set) with assertRaisesRegex(self, ValueError, "scattering_cross_section was: 0"): material_obj.set_material_properties(abs_cross_sect=good_absorb, scattering_cross_sect=bad_scattering) # Check nothing has been set yet self.assertIsNone(material_obj.absorption_cross_section) self.assertIsNone(material_obj.scattering_cross_section) # Set the object this time material_obj.set_material_properties(abs_cross_sect=good_absorb, scattering_cross_sect=good_scattering) self.assertTrue(material_obj._is_material_props_set) self.assertEqual(material_obj.absorption_cross_section, float(good_absorb)) self.assertEqual(material_obj.scattering_cross_section, float(good_scattering)) # Check we cannot set it twice and fields do not change with assertRaisesRegex(self, RuntimeError, "The material properties have already been set"): material_obj.set_material_properties(abs_cross_sect=999, scattering_cross_sect=999) self.assertEqual(material_obj.absorption_cross_section, float(good_absorb)) self.assertEqual(material_obj.scattering_cross_section, float(good_scattering))
def test_datetime_field(self): schema = [ {'name': 'date', 'type': 'basic:datetime:'}, ] instance = {'date': '2000-06-21 00:00'} validate_schema(instance, schema) instance = {'date': '2000 06 21 24:00'} with self.assertRaises(ValidationError): validate_schema(instance, schema) instance = {'date': '2000/06/21 2:03'} with six.assertRaisesRegex(self, ValidationError, 'is not valid'): validate_schema(instance, schema) instance = {'date': '2000-06-21 2:3'} # XXX: Is this ok? validate_schema(instance, schema) instance = {'date': '2000-06-21'} with six.assertRaisesRegex(self, ValidationError, 'is not valid'): validate_schema(instance, schema) instance = {'date': '2000-06-21 12pm'} with six.assertRaisesRegex(self, ValidationError, 'is not valid'): validate_schema(instance, schema)
def test_rebin_workspace_list_x_start_end(self): new_start_x = 1 new_end_x = 5 new_bin_width = 0.5 number_of_ws = 10 ws_bin_widths = [new_bin_width] * number_of_ws start_x_list = [new_start_x] * number_of_ws end_x_list = [new_end_x] * number_of_ws ws_list = [] for i in range(number_of_ws): out_name = "test_rebin_workspace_list_defaults_" + str(i) ws_list.append(mantid.CreateSampleWorkspace(OutputWorkspace=out_name, Function='Flat background', NumBanks=1, BankPixelWidth=1, XMax=10, BinWidth=1)) # Are the lengths checked incorrect_length = [1] * (number_of_ws - 1) with assertRaisesRegex(self, ValueError, "The number of starting bin values"): common.rebin_workspace_list(workspace_list=ws_list, bin_width_list=ws_bin_widths, start_x_list=incorrect_length, end_x_list=end_x_list) with assertRaisesRegex(self, ValueError, "The number of ending bin values"): common.rebin_workspace_list(workspace_list=ws_list, bin_width_list=ws_bin_widths, start_x_list=start_x_list, end_x_list=incorrect_length) output_list = common.rebin_workspace_list(workspace_list=ws_list, bin_width_list=ws_bin_widths, start_x_list=start_x_list, end_x_list=end_x_list) self.assertEqual(len(output_list), number_of_ws) for ws in output_list: self.assertEqual(ws.readX(0)[0], new_start_x) self.assertEqual(ws.readX(0)[-1], new_end_x) mantid.DeleteWorkspace(ws)
def test_check_db_fails(self): with assertRaisesRegex(self, ValueError, 'no database'): dbcore.Model()._check_db() with assertRaisesRegex(self, ValueError, 'no id'): TestModel1(self.db)._check_db() dbcore.Model(self.db)._check_db(need_id=False)
def test_date_field(self): schema = [ {'name': 'date', 'type': 'basic:date:'}, ] instance = {'date': '2000-12-31'} validate_schema(instance, schema) instance = {'date': '2000/01/01'} with six.assertRaisesRegex(self, ValidationError, 'is not valid'): validate_schema(instance, schema) instance = {'date': '31 04 2000'} with six.assertRaisesRegex(self, ValidationError, 'is not valid'): validate_schema(instance, schema) instance = {'date': '21.06.2000'} with six.assertRaisesRegex(self, ValidationError, 'is not valid'): validate_schema(instance, schema) instance = {'date': '2000-1-1'} with six.assertRaisesRegex(self, ValidationError, 'is not valid'): validate_schema(instance, schema) instance = {'date': '2000 apr 8'} with six.assertRaisesRegex(self, ValidationError, 'is not valid'): validate_schema(instance, schema)
def test_mdraid_array_device_methods(self): """Test for method calls on initialized MDRaidDevices.""" with six.assertRaisesRegex(self, DeviceError, "invalid"): self.dev7.level = "junk" with six.assertRaisesRegex(self, DeviceError, "invalid"): self.dev7.level = None
def test_duplicate_keys(self): output_file = six.StringIO() utility = CSVJSON(['-k', 'a', 'examples/dummy3.csv'], output_file) six.assertRaisesRegex(self, ValueError, 'Value True is not unique in the key column.', utility.run) output_file.close()
def test_add_device(self, *args): # pylint: disable=unused-argument dt = DeviceTree() dev1 = StorageDevice("dev1", exists=False, uuid=sentinel.dev1_uuid, parents=[]) self.assertEqual(dt.devices, list()) # things are called, updated as expected when a device is added with patch("blivet.devicetree.callbacks") as callbacks: dt._add_device(dev1) self.assertTrue(callbacks.device_added.called) self.assertEqual(dt.devices, [dev1]) self.assertTrue(dev1 in dt.devices) self.assertTrue(dev1.name in dt.names) self.assertTrue(dev1.add_hook.called) # pylint: disable=no-member # adding an already-added device fails six.assertRaisesRegex(self, ValueError, "already in tree", dt._add_device, dev1) dev2 = StorageDevice("dev2", exists=False, parents=[]) dev3 = StorageDevice("dev3", exists=False, parents=[dev1, dev2]) # adding a device with one or more parents not already in the tree fails six.assertRaisesRegex(self, DeviceTreeError, "parent.*not in tree", dt._add_device, dev3) self.assertFalse(dev2 in dt.devices) self.assertFalse(dev2.name in dt.names) dt._add_device(dev2) self.assertTrue(dev2 in dt.devices) self.assertTrue(dev2.name in dt.names) dt._add_device(dev3) self.assertTrue(dev3 in dt.devices) self.assertTrue(dev3.name in dt.names)
def test_get(self, resq_mock): # User provides correct ID resq_mock.api = MagicMock() resq_mock.api.get = MagicMock(return_value=[{'id': 40}]) resq_mock.resolwe = MagicMock() resq_mock.resource = MagicMock(return_value="Some response") data = ResolweQuerry.get(resq_mock, 40) self.assertEqual(data, "Some response") # User provides wrong ID. message = r'Id: .* does not exist or you dont have access permission.' resq_mock.resource = MagicMock(side_effect=[slumber.exceptions.HttpNotFoundError(message)]) with six.assertRaisesRegex(self, slumber.exceptions.HttpNotFoundError, message): ResolweQuerry.get(resq_mock, 12345) # User provides correct slug. resq_mock.api = MagicMock() resq_mock.resolwe = MagicMock() resq_mock.resource = MagicMock(return_value="Some response") data = ResolweQuerry.get(resq_mock, "some-slug") self.assertEqual(data, "Some response") # User provides wrong slug. message = r'Slug: .* does not exist or you dont have access permission.' resq_mock.resource = MagicMock(side_effect=[IndexError(message)]) with six.assertRaisesRegex(self, IndexError, message): ResolweQuerry.get(resq_mock, "some-slug")
def test_json_field(self): schema = [ {'name': 'big_dict', 'type': 'basic:json:'} ] # json not saved in `Storage` instance = {'big_dict': {'foo': 'bar'}} with six.assertRaisesRegex(self, ValidationError, 'is not valid'): validate_schema(instance, schema) with patch('resolwe.flow.models.Storage') as storage_mock: filter_mock = MagicMock() filter_mock.exists.return_value = True storage_mock.objects.filter.return_value = filter_mock instance = {'big_dict': 5} validate_schema(instance, schema) self.assertEqual(filter_mock.exists.call_count, 1) # non existing `Storage` with patch('resolwe.flow.models.Storage') as storage_mock: filter_mock = MagicMock() filter_mock.exists.return_value = False storage_mock.objects.filter.return_value = filter_mock instance = {'big_dict': 5} with six.assertRaisesRegex(self, ValidationError, '`Storage` object does not exist'): validate_schema(instance, schema) self.assertEqual(filter_mock.exists.call_count, 1)
def test_rebin_workspace_list_defaults(self): new_bin_width = 0.5 number_of_ws = 10 ws_bin_widths = [new_bin_width] * number_of_ws ws_list = [] for i in range(number_of_ws): out_name = "test_rebin_workspace_list_defaults_" + str(i) ws_list.append(mantid.CreateSampleWorkspace(OutputWorkspace=out_name, Function='Flat background', NumBanks=1, BankPixelWidth=1, XMax=10, BinWidth=1)) # What if the item passed in is not a list err_msg_not_list = "was not a list" with assertRaisesRegex(self, RuntimeError, err_msg_not_list): common.rebin_workspace_list(workspace_list=ws_list, bin_width_list=None) with assertRaisesRegex(self, RuntimeError, err_msg_not_list): common.rebin_workspace_list(workspace_list=None, bin_width_list=[]) # What about if the lists aren't the same length with assertRaisesRegex(self, ValueError, "does not match the number of banks"): incorrect_number_bin_widths = [1] * (number_of_ws - 1) common.rebin_workspace_list(workspace_list=ws_list, bin_width_list=incorrect_number_bin_widths) # Does it return all the workspaces as a list - another unit test checks the implementation output = common.rebin_workspace_list(workspace_list=ws_list, bin_width_list=ws_bin_widths) self.assertEqual(len(output), number_of_ws) for ws in output: mantid.DeleteWorkspace(ws)
def test_run_number_not_found_gives_sane_err(self): expected_val = "yamlParserTest" file_handle = self.get_temp_file_handle() file_handle.write("10-20:\n") file_handle.write(" test_key: '" + expected_val + "'\n") file_handle.write("21-:\n") file_handle.write(" test_key: '" + expected_val + "'\n") file_path = file_handle.name file_handle.close() # Test a value in the middle of 1-10 with assertRaisesRegex(self, ValueError, "Run number 5 not recognised in cycle mapping file"): yaml_parser.get_run_dictionary(run_number_string="5", file_path=file_path) # Check on edge of invalid numbers with assertRaisesRegex(self, ValueError, "Run number 9 not recognised in cycle mapping file"): yaml_parser.get_run_dictionary(run_number_string=9, file_path=file_path) # What about a range of numbers with assertRaisesRegex(self, ValueError, "Run number 2 not recognised in cycle mapping file"): yaml_parser.get_run_dictionary(run_number_string="2-8", file_path=file_path) # Check valid number still works returned_dict = yaml_parser.get_run_dictionary(run_number_string="10", file_path=file_path) self.assertEqual(returned_dict["test_key"], expected_val)
def test_bad_descriptor_input(self, resolwe_mock): # Raise error is only one of deswcriptor/descriptor_schema is given: message = "Set both or neither descriptor and descriptor_schema." with six.assertRaisesRegex(self, ValueError, message): Resolwe.run(resolwe_mock, descriptor="a") with six.assertRaisesRegex(self, ValueError, message): Resolwe.run(resolwe_mock, descriptor_schema="a")
def test_get_pull_request(self): """Tests for _get_pull_request.""" # Simple case: get the existing PR from the existing repo. result = pss._get_pull_request(self.repo, "3") self.assertEqual(result.id, 3) # PR that doesn't exist. six.assertRaisesRegex( self, PagureEvException, r"Pull-Request '2' not found", pss._get_pull_request, self.repo, "2", ) # PR from a project with no PR tracker. six.assertRaisesRegex( self, PagureEvException, r"No pull-request tracker found", pss._get_pull_request, self.repo2, "1", )
def test(self): with six.assertRaisesRegex(self, AssertionError, '^Foo'): raise AssertionError('Foo') with self.assertRaises(AssertionError): with six.assertRaisesRegex(self, AssertionError, r'^Foo'): raise AssertionError('Bar')
def testSetContentDisposition(self): with six.assertRaisesRegex( self, rest.RestException, 'Error: Content-Disposition \(.*\) is not a recognized value.'): rest.setContentDisposition('filename', 'unknown', False) with six.assertRaisesRegex( self, rest.RestException, 'Error: Content-Disposition filename is empty.'): rest.setContentDisposition('', setHeader=False) self.assertEqual(rest.setContentDisposition( 'filename', setHeader=False), 'attachment; filename="filename"') self.assertEqual(rest.setContentDisposition( 'filename', 'inline', setHeader=False), 'inline; filename="filename"') self.assertEqual(rest.setContentDisposition( 'filename', 'form-data; name="chunk"', setHeader=False), 'form-data; name="chunk"; filename="filename"') self.assertEqual(rest.setContentDisposition( 'file "name"', setHeader=False), 'attachment; filename="file \\"name\\""') self.assertEqual(rest.setContentDisposition( 'file\\name', setHeader=False), 'attachment; filename="file\\\\name"') self.assertEqual(rest.setContentDisposition( u'\u043e\u0431\u0440\u0430\u0437\u0435\u0446', setHeader=False), 'attachment; filename=""; filename*=UTF-8\'\'' '%D0%BE%D0%B1%D1%80%D0%B0%D0%B7%D0%B5%D1%86') self.assertEqual(rest.setContentDisposition( u'\U0001f603', setHeader=False), 'attachment; filename=""; filename*=UTF-8\'\'%F0%9F%98%83')
def test_constructor_with_impossible_val(self): good_input = 1 good_center_input = [1, 2, 3] zero_value = 0 negative_value = -0.0000001 negative_int = -1 negative_string = "-1" # Check it handles zero with assertRaisesRegex(self, ValueError, "The value set for height was: 0"): sample_details.SampleDetails(height=zero_value, radius=good_input, center=good_center_input, shape="cylinder") # Very small negative with assertRaisesRegex(self, ValueError, "which is impossible for a physical object"): sample_details.SampleDetails(height=good_input, radius=negative_value, center=good_center_input, shape="cylinder") # Integer negative with assertRaisesRegex(self, ValueError, "The value set for height was: -1"): sample_details.SampleDetails(height=negative_int, radius=good_input, center=good_center_input, shape="cylinder") # String negative with assertRaisesRegex(self, ValueError, "The value set for radius was: -1"): sample_details.SampleDetails(height=good_input, radius=negative_string, center=good_center_input, shape="cylinder")
def test_metrics_raises(self): sp0 = _pos_neg_block([]) spn = _pos_neg_block([2]) block = {'foo': sp0, 'bar:': spn} >> tdb.Concat() six.assertRaisesRegex( self, TypeError, 'Metric [a-z]+tive has incompatible types', tdc.Compiler.create, block)
def test_unset_property(self, argument, value, ex_text): """Negative test for baremetal node unset command options.""" base_cmd = 'baremetal node unset' command = self.construct_cmd(base_cmd, argument, value, self.node['uuid']) six.assertRaisesRegex(self, exceptions.CommandFailed, ex_text, self.openstack, command)
def testValidators(self): settingModel = Setting() @setting_utilities.validator('test.key1') def key1v1(doc): raise ValidationException('key1v1') with six.assertRaisesRegex(self, ValidationException, '^key1v1$'): settingModel.set('test.key1', '') @setting_utilities.validator('test.key1') def key1v2(doc): raise ValidationException('key1v2') with six.assertRaisesRegex(self, ValidationException, '^key1v2$'): settingModel.set('test.key1', '') @setting_utilities.validator('test.key2') def key2v1(doc): raise ValidationException('key2v1') with six.assertRaisesRegex(self, ValidationException, '^key2v1$'): settingModel.set('test.key2', '') @setting_utilities.validator('test.key2', replace=True) def key2v2(doc): doc['value'] = 'modified' setting = settingModel.set('test.key2', 'original') self.assertEqual(setting['value'], 'modified')
def testConsecutiveGaps(self): """ An argument that has two consecutive gaps characters must result in a ValueError. """ error = "^btop string '36--' has two consecutive gaps at offset 2$" assertRaisesRegex(self, ValueError, error, list, parseBtop('36--'))
def test_volumes_from_unknown(self): config = self._get_config('test_volumes_from_unknown') six.assertRaisesRegex(self, exceptions.InvalidVolumeConfigurationException, 'Unknown container instance-2 to get volumes from ' 'for instance-1!', lambda: maestro.Conductor(config))
def test_get_plot_point_colors_invalid_input(self): # column provided without df with npt.assert_raises(ValueError): self.min_ord_results._get_plot_point_colors(None, 'numeric', ['B', 'C'], 'jet') # df provided without column with npt.assert_raises(ValueError): self.min_ord_results._get_plot_point_colors(self.df, None, ['B', 'C'], 'jet') # column not in df with six.assertRaisesRegex(self, ValueError, 'missingcol'): self.min_ord_results._get_plot_point_colors(self.df, 'missingcol', ['B', 'C'], 'jet') # id not in df with six.assertRaisesRegex(self, ValueError, 'numeric'): self.min_ord_results._get_plot_point_colors( self.df, 'numeric', ['B', 'C', 'missingid', 'A'], 'jet') # missing data in df with six.assertRaisesRegex(self, ValueError, 'nancolumn'): self.min_ord_results._get_plot_point_colors(self.df, 'nancolumn', ['B', 'C', 'A'], 'jet')
def test_cal_map_dict_helper(self): missing_key_name = "wrong_key" correct_key_name = "right_key" expected_val = 123 dict_with_key = {correct_key_name: expected_val} # Check it correctly raises with assertRaisesRegex(self, KeyError, "The field '" + missing_key_name + "' is required"): common.cal_map_dictionary_key_helper(dictionary=dict_with_key, key=missing_key_name) # Check it correctly appends the passed error message when raising appended_e_msg = "test append message" with assertRaisesRegex(self, KeyError, appended_e_msg): common.cal_map_dictionary_key_helper(dictionary=dict_with_key, key=missing_key_name, append_to_error_message=appended_e_msg) # Check that it correctly returns the key value where it exists self.assertEqual(common.cal_map_dictionary_key_helper(dictionary=dict_with_key, key=correct_key_name), expected_val) # Check it is not case sensitive different_case_name = "tEsT_key" dict_with_mixed_key = {different_case_name: expected_val} try: self.assertEqual(common.cal_map_dictionary_key_helper(dictionary=dict_with_mixed_key, key=different_case_name.lower()), expected_val) except KeyError: # It tried to use the key without accounting for the case difference self.fail("cal_map_dictionary_key_helper attempted to use a key without accounting for case")
def testParseBadIntValue(self, message_module): message = message_module.TestAllTypes() text = 'optional_int32: bork' six.assertRaisesRegex(self, text_format.ParseError, ('1:17 : Couldn\'t parse integer: bork'), text_format.Parse, text, message)
def test_not_numerical_offset(self): u = Unit('meter') with six.assertRaisesRegex(self, TypeError, 'unsupported operand type'): operator.add(u, 'not_a_number')