Beispiel #1
0
 def test_add_key_destination_required_valid_value(self):
     # Tests add_key with a key, destination (and validation_method) given that the key is
     # required
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     # Returning nothing from a validation_method means that the key's value is valid
     # TODO Don't be magical with the return values
     mock_validate_method.return_value = None
     # The below should not blow up
     config.add_key(key='test_key',
                    validation_method=mock_validate_method,
                    destination='test_key_dest',
                    required=True)
     test_values = {'test_key': 'test_key_value'}
     config.update(**test_values)
     config.validate()
     mock_validate_method.assert_called_once_with('test_key')
     self.assertNotIn(
         'test_key', config, "The config contains the original test_key, "
         "should be removed post validate")
     self.assertIn(
         'test_key_dest', config,
         "The config does not contain a value at the "
         "destination specified in the add_key call")
     self.assertEqual(config['test_key_dest'], test_values['test_key'])
     self.assertEqual(config.state, ValidationState.VALID)
Beispiel #2
0
 def test_add_key_required(self):
     # Tests add_key with a key, destination (and validation_method) given
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     # Returning nothing from a validation_method means that the key's value is valid
     # TODO Don't be magical with the return values
     mock_validate_method.return_value = None
     # The below should not blow up
     config.add_key(key='test_key',
                    validation_method=mock_validate_method,
                    required=True)
     test_values = {'test_key': 'test_key_value'}
     config.update(**test_values)
     config.validate()
     # The validate_method should have been called with the key (bound methods would also have
     #  been passed the config section as the first arg)
     # FIXME This seems broken, we should let folks add functions that are not bound to the
     # class instance as validation_methods
     mock_validate_method.assert_called_once_with('test_key')
     self.assertIn(
         'test_key', config,
         "The config does not contain the test_key, deleted by "
         "accident?")
     self.assertEqual(config['test_key'], test_values['test_key'])
     self.assertEqual(config.state, ValidationState.VALID)
Beispiel #3
0
    def test_satellite_config_file(self):
        # Username and password are required for a valid sat5 destination
        with open(os.path.join(self.config_dir, "test.conf"), "w") as f:
            f.write("""
[test]
type=libvirt
sat_server=sat.example.com
sat_username=sat_username
sat_password=sat_password
""")
        conf = parse_file(os.path.join(self.config_dir, "test.conf"))
        effective_config = EffectiveConfig()
        conf_values = conf.pop("test")
        effective_config["test"] = ConfigSection.from_dict(
            conf_values,
            "test",
            effective_config
        )
        config_manager = DestinationToSourceMapper(effective_config)
        self.assertEqual(len(config_manager.configs), 1)
        # There should only be one destination detected
        self.assertEqual(len(config_manager.dests), 1)
        # Which should be a Satellite5DestinationInfo
        dest_info = config_manager.dests.pop()
        self.assertTrue(isinstance(dest_info, Satellite5DestinationInfo), 'The destination info '
                                                                          'we got was not of the '
                                                                          'expected type')
        manager = Manager.fromInfo(self.logger, effective_config, dest_info)
        self.assertTrue(isinstance(manager, Satellite))
        self.assertEqual(dest_info.sat_server, 'sat.example.com')
 def test_add_key_default_no_value_provided(self):
     # Tests that a key added with a default uses that default, when not provided a value for
     # the same.
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     # Returning nothing from a validation_method means that the key's value is valid
     # TODO Don't be magical with the return values
     mock_validate_method.return_value = None
     config.add_key(key='test_key', validation_method=mock_validate_method,
                    default="test_key_default")
     config.validate()
     # We only run the validation_methods on keys that are set (not on the defaults)
     mock_validate_method.assert_not_called()
     self.assertIn('test_key', config, "The default value was not added (check "
                                       "reset_to_defaults?)")
     # The value returned by the config should be that set as the default
     self.assertEqual(config['test_key'], "test_key_default")
 def test_add_key_default_required_no_value_provided(self):
     # Tests that the config is still considered valid when a required key is not provided (
     # but has a default)
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     mock_validate_method.return_value = None
     config.add_key(key='test_key', validation_method=mock_validate_method, required=True,
                    default='test_key_default')
     config.validate()
     # Not given a value to chew on, don't try to chew on it
     mock_validate_method.assert_not_called()
     self.assertIn('test_key', config, "The config is missing the required, defaulted value ("
                                       "check reset_to_defaults?)")
     self.assertEqual(config['test_key'], 'test_key_default')
     self.assertEqual(config.state, ValidationState.VALID, "Check _unvalidated_keys, "
                                                           "_invalid_keys, _missing_required, "
                                                           "and _update_state()")
Beispiel #6
0
 def test_add_key_required_missing(self):
     # Tests add_key with a key, destination (and validation_method) given
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     # Returning nothing from a validation_method means that the key's value is valid
     # TODO Don't be magical with the return values
     mock_validate_method.return_value = None
     # The below should not blow up
     config.add_key(key='test_key', validation_method=mock_validate_method, required=True)
     test_values = {'test_key_different': 'test_key_different_value'}
     config.update(**test_values)
     config.validate()
     # The validate_method should not have been called (the associated key was not included)
     mock_validate_method.assert_not_called()
     self.assertNotIn('test_key', config, "The 'test_key' was added mistakenly somehow")
     self.assertEqual(config.state, ValidationState.INVALID)
Beispiel #7
0
 def test_add_key_destination_invalid_value(self):
     # Tests add_key with a key, destination (and validation_method) given that the key is
     # required
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     # TODO Don't be magical with the return values
     mock_validate_method.return_value = ('error', 'THIS IS A TERRIBLE IDEA...')
     # The below should not blow up
     config.add_key(key='test_key', validation_method=mock_validate_method,
                    destination='test_key_dest')
     test_values = {'test_key': 'test_key_value'}
     config.update(**test_values)
     config.validate()
     mock_validate_method.assert_called_once_with('test_key')
     self.assertNotIn('test_key_dest', config, "The config has a value for the destination, "
                                               "despite the value being invalid")
     self.assertEqual(config.state, ValidationState.INVALID)
 def test_read_effective_config_from_file(self):
     config_dir = tempfile.mkdtemp()
     self.addCleanup(shutil.rmtree, config_dir)
     with open(os.path.join(config_dir, "test.conf"), "w") as f:
         f.write(CONFIG_SECTION_TEXT)
     conf = parse_file(os.path.join(config_dir, "test.conf"))
     effective_config = EffectiveConfig()
     conf_values = conf.pop(CUSTOM_SECTION_NAME)
     effective_config[CUSTOM_SECTION_NAME] = ConfigSection.from_dict(
         conf_values, CUSTOM_SECTION_NAME, effective_config)
     self.assertEqual(type(effective_config[CUSTOM_SECTION_NAME]),
                      CustomConfigSection)
     self.assertEqual(effective_config[CUSTOM_SECTION_NAME]['my_str'],
                      'foo')
     validate_messages = effective_config.validate()
     self.assertEqual(validate_messages, [])
Beispiel #9
0
 def test_add_key_default_valid_value_provided(self):
     # Tests that a key added with a default DOES NOT USE that default, when the provided
     # value is valid
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     # Returning nothing from a validation_method means that the key's value is valid
     # TODO Don't be magical with the return values
     mock_validate_method.return_value = None
     config.add_key(key='test_key', validation_method=mock_validate_method,
                    default="test_key_default")
     values = {'test_key': 'test_key_value'}
     config.update(values)
     config.validate()
     mock_validate_method.assert_called_once_with('test_key')
     self.assertIn('test_key', config)
     # The value returned by the config should still be the valid one given it
     self.assertEqual(config['test_key'], "test_key_value")
     self.assertEqual(config.state, ValidationState.VALID)
Beispiel #10
0
 def test_read_sam_effective_config_from_file(self):
     config_dir = tempfile.mkdtemp()
     self.addCleanup(shutil.rmtree, config_dir)
     with open(os.path.join(config_dir, "test.conf"), "w") as f:
         f.write(LIBVIRT_SECTION_TEXT)
     conf = parse_file(os.path.join(config_dir, "test.conf"))
     self.init_effective_config()
     conf_values = conf.pop(MY_SECTION_NAME)
     self.effective_config[MY_SECTION_NAME] = ConfigSection.from_dict(
         conf_values, MY_SECTION_NAME, self.effective_config)
     self.assertEqual(type(self.effective_config[MY_SECTION_NAME]),
                      LibvirtdConfigSection)
     self.assertEqual(self.effective_config[MY_SECTION_NAME]['server'],
                      'ssh://192.168.122.10')
     validate_messages = self.effective_config.validate()
     self.assertIsNotNone(validate_messages)
     del self.effective_config[MY_SECTION_NAME]
 def test_add_key_required_missing(self):
     # Tests add_key with a key, destination (and validation_method) given
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     # Returning nothing from a validation_method means that the key's value is valid
     # TODO Don't be magical with the return values
     mock_validate_method.return_value = None
     # The below should not blow up
     config.add_key(key='test_key', validation_method=mock_validate_method, required=True)
     test_values = {'test_key_different': 'test_key_different_value'}
     config.update(**test_values)
     config.validate()
     # The validate_method should not have been called (the associated key was not included)
     mock_validate_method.assert_not_called()
     self.assertNotIn('test_key', config, "The 'test_key' was added mistakenly somehow")
     self.assertEqual(config.state, ValidationState.INVALID)
 def test_read_sam_effective_config_from_file(self):
     config_dir = tempfile.mkdtemp()
     self.addCleanup(shutil.rmtree, config_dir)
     with open(os.path.join(config_dir, "test.conf"), "w") as f:
         f.write(LIBVIRT_SECTION_TEXT)
     conf = parse_file(os.path.join(config_dir, "test.conf"))
     self.init_effective_config()
     conf_values = conf.pop(MY_SECTION_NAME)
     self.effective_config[MY_SECTION_NAME] = ConfigSection.from_dict(
         conf_values,
         MY_SECTION_NAME,
         self.effective_config
     )
     self.assertEqual(type(self.effective_config[MY_SECTION_NAME]), LibvirtdConfigSection)
     self.assertEqual(self.effective_config[MY_SECTION_NAME]['server'], 'ssh://192.168.122.10')
     validate_messages = self.effective_config.validate()
     self.assertIsNotNone(validate_messages)
     del self.effective_config[MY_SECTION_NAME]
Beispiel #13
0
    def _run_add_key_test(self, key, input_value=__marker, expected_value=__marker, add_key_kwargs=None,
                          expected_in=True,
                          expected_state=ValidationState.VALID,
                          validation_return_val=None,
                          expected_present_in_messages=True):
        if not add_key_kwargs:
            add_key_kwargs = {}

        # Provide mock validation_method if one is not given
        if 'validation_method' not in add_key_kwargs:
            add_key_kwargs['validation_method'] = Mock()
            add_key_kwargs['validation_method'].return_value = validation_return_val

        config = ConfigSection('test', None)

        config.add_key(key, **add_key_kwargs)

        # Only update the values in the config section if we've been given an input value
        if input_value is not self.__marker:
            test_values = {key: input_value}
            config.update(**test_values)

        messages = config.validate()

        # Assert the mock was called, if it was a mock (and we passed in an input_value
        if input_value is not self.__marker and \
                hasattr(add_key_kwargs['validation_method'], 'assert_called_once_with'):
            add_key_kwargs['validation_method'].assert_called_once_with(key)

        if expected_in:
            self.assertIn(key, config, "The config does not contain the expected key")

        if expected_value is not self.__marker:
            self.assertEqual(config[key], expected_value, 'Expected key "%s" to be "%s" found "%s"' % (key, expected_value, config[key]))

        if expected_present_in_messages:
            self.assertTrue(any(key in message[1] for message in messages), 'Expected at least one mention of key "%s" in validation messages' % key)
        else:
            bad_messages = []
            for message in messages:
                if key in message[1]:
                    bad_messages.append(message)
            if bad_messages:
                self.fail("Expected no mention of key '%s' in messages found: %s" % (key, bad_messages))

        self.assertEqual(config.state, expected_state)
        return config, messages
Beispiel #14
0
 def test_add_key_validation_method(self):
     # The most minimal use of add_key
     # Verifies that the standard validate method does what is dictated by add_key in
     # the minimal case.
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     # Returning nothing from a validation_method means that the key's value is valid
     # TODO Don't be magical with the return values
     mock_validate_method.return_value = None
     # The below should not blow up
     config.add_key(key='test_key', validation_method=mock_validate_method)
     test_values = {'test_key': 'test_key_value'}
     config.update(**test_values)
     config.validate()
     # The validate_method should have been called with the ConfigSection and the key
     mock_validate_method.assert_called_once_with('test_key')
     self.assertIn('test_key', config, "The config does not contain the test_key, deleted by "
                                       "accident?")
     self.assertEqual(config['test_key'], test_values['test_key'])
     self.assertEqual(config.state, ValidationState.VALID)
 def test_add_key_destination_invalid_value(self):
     # Tests add_key with a key, destination (and validation_method) given that the key is
     # required
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     # TODO Don't be magical with the return values
     mock_validate_method.return_value = ('error', 'THIS IS A TERRIBLE IDEA...')
     # The below should not blow up
     config.add_key(key='test_key', validation_method=mock_validate_method,
                    destination='test_key_dest')
     test_values = {'test_key': 'test_key_value'}
     config.update(**test_values)
     config.validate()
     mock_validate_method.assert_called_once_with('test_key')
     self.assertNotIn('test_key_dest', config, "The config has a value for the destination, "
                                               "despite the value being invalid")
     self.assertEqual(config.state, ValidationState.INVALID)
Beispiel #16
0
 def test_add_key_default_invalid_value_provided(self):
     # Tests that a key added with a default DOES NOT USE that default
     # when an invalid value is given as the value to be validated
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     # Returning something (normally a tuple of (log_level, error_message)) from a validation
     # method with the log_level of 'error' means that the key is invalid
     # TODO Create a more meaningful way of validating values (and presenting messages about
     # validation to the user)
     mock_validate_method.return_value = ('error', 'THIS IS A BAD WAY TO GO...')
     config.add_key(key='test_key', validation_method=mock_validate_method,
                    default="test_key_default")
     values = {'test_key': 'PRETEND_BAD_VALUE'}
     config.update(values)
     config.validate()
     mock_validate_method.assert_called_once_with('test_key')
     self.assertIn('test_key', config)
     # The value that the invalid config holds on to should be the one that was provided,
     # NOT the default (which we assume is good to use)
     self.assertEqual(config['test_key'], values['test_key'])
     self.assertEqual(config.state, ValidationState.INVALID)
 def test_add_key_default_valid_value_provided(self):
     # Tests that a key added with a default DOES NOT USE that default, when the provided
     # value is valid
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     # Returning nothing from a validation_method means that the key's value is valid
     # TODO Don't be magical with the return values
     mock_validate_method.return_value = None
     config.add_key(key='test_key', validation_method=mock_validate_method,
                    default="test_key_default")
     values = {'test_key': 'test_key_value'}
     config.update(values)
     config.validate()
     mock_validate_method.assert_called_once_with('test_key')
     self.assertIn('test_key', config)
     # The value returned by the config should still be the valid one given it
     self.assertEqual(config['test_key'], "test_key_value")
     self.assertEqual(config.state, ValidationState.VALID)
    def _run_add_key_test(self, key, input_value=__marker, expected_value=__marker, add_key_kwargs=None,
                          expected_in=True,
                          expected_state=ValidationState.VALID,
                          validation_return_val=None,
                          expected_present_in_messages=True):
        if not add_key_kwargs:
            add_key_kwargs = {}

        # Provide mock validation_method if one is not given
        if 'validation_method' not in add_key_kwargs:
            add_key_kwargs['validation_method'] = Mock()
            add_key_kwargs['validation_method'].return_value = validation_return_val

        config = ConfigSection('test', None)

        config.add_key(key, **add_key_kwargs)

        # Only update the values in the config section if we've been given an input value
        if input_value is not self.__marker:
            test_values = {key: input_value}
            config.update(**test_values)

        messages = config.validate()

        # Assert the mock was called, if it was a mock (and we passed in an input_value
        if input_value is not self.__marker and \
                hasattr(add_key_kwargs['validation_method'], 'assert_called_once_with'):
            add_key_kwargs['validation_method'].assert_called_once_with(key)

        if expected_in:
            self.assertIn(key, config, "The config does not contain the expected key")

        if expected_value is not self.__marker:
            self.assertEqual(config[key], expected_value, 'Expected key "%s" to be "%s" found "%s"' % (key, expected_value, config[key]))

        if expected_present_in_messages:
            self.assertTrue(any(key in message[1] for message in messages), 'Expected at least one mention of key "%s" in validation messages' % key)
        else:
            bad_messages = []
            for message in messages:
                if key in message[1]:
                    bad_messages.append(message)
            if bad_messages:
                self.fail("Expected no mention of key '%s' in messages found: %s" % (key, bad_messages))

        self.assertEqual(config.state, expected_state)
        return config, messages
 def test_add_key_validation_method(self):
     # The most minimal use of add_key
     # Verifies that the standard validate method does what is dictated by add_key in
     # the minimal case.
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     # Returning nothing from a validation_method means that the key's value is valid
     # TODO Don't be magical with the return values
     mock_validate_method.return_value = None
     # The below should not blow up
     config.add_key(key='test_key', validation_method=mock_validate_method)
     test_values = {'test_key': 'test_key_value'}
     config.update(**test_values)
     config.validate()
     # The validate_method should have been called with the ConfigSection and the key
     mock_validate_method.assert_called_once_with('test_key')
     self.assertIn('test_key', config, "The config does not contain the test_key, deleted by "
                                       "accident?")
     self.assertEqual(config['test_key'], test_values['test_key'])
     self.assertEqual(config.state, ValidationState.VALID)
Beispiel #20
0
 def test_add_key_default_no_value_provided(self):
     # Tests that a key added with a default uses that default, when not provided a value for
     # the same.
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     # Returning nothing from a validation_method means that the key's value is valid
     # TODO Don't be magical with the return values
     mock_validate_method.return_value = None
     config.add_key(key='test_key', validation_method=mock_validate_method,
                    default="test_key_default")
     config.validate()
     # We only run the validation_methods on keys that are set (not on the defaults)
     mock_validate_method.assert_not_called()
     self.assertIn('test_key', config, "The default value was not added (check "
                                       "reset_to_defaults?)")
     # The value returned by the config should be that set as the default
     self.assertEqual(config['test_key'], "test_key_default")
Beispiel #21
0
 def test_add_key_default_required_no_value_provided(self):
     # Tests that the config is still considered valid when a required key is not provided (
     # but has a default)
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     mock_validate_method.return_value = None
     config.add_key(key='test_key', validation_method=mock_validate_method, required=True,
                    default='test_key_default')
     config.validate()
     # Not given a value to chew on, don't try to chew on it
     mock_validate_method.assert_not_called()
     self.assertIn('test_key', config, "The config is missing the required, defaulted value ("
                                       "check reset_to_defaults?)")
     self.assertEqual(config['test_key'], 'test_key_default')
     self.assertEqual(config.state, ValidationState.VALID, "Check _unvalidated_keys, "
                                                           "_invalid_keys, _missing_required, "
                                                           "and _update_state()")
 def test_add_key_required(self):
     # Tests add_key with a key, destination (and validation_method) given
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     # Returning nothing from a validation_method means that the key's value is valid
     # TODO Don't be magical with the return values
     mock_validate_method.return_value = None
     # The below should not blow up
     config.add_key(key='test_key', validation_method=mock_validate_method, required=True)
     test_values = {'test_key': 'test_key_value'}
     config.update(**test_values)
     config.validate()
     # The validate_method should have been called with the key (bound methods would also have
     #  been passed the config section as the first arg)
     # FIXME This seems broken, we should let folks add functions that are not bound to the
     # class instance as validation_methods
     mock_validate_method.assert_called_once_with('test_key')
     self.assertIn('test_key', config, "The config does not contain the test_key, deleted by "
                                       "accident?")
     self.assertEqual(config['test_key'], test_values['test_key'])
     self.assertEqual(config.state, ValidationState.VALID)
 def test_add_key_destination_required_valid_value(self):
     # Tests add_key with a key, destination (and validation_method) given that the key is
     # required
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     # Returning nothing from a validation_method means that the key's value is valid
     # TODO Don't be magical with the return values
     mock_validate_method.return_value = None
     # The below should not blow up
     config.add_key(key='test_key', validation_method=mock_validate_method,
                    destination='test_key_dest', required=True)
     test_values = {'test_key': 'test_key_value'}
     config.update(**test_values)
     config.validate()
     mock_validate_method.assert_called_once_with('test_key')
     self.assertNotIn('test_key', config, "The config contains the original test_key, "
                                          "should be removed post validate")
     self.assertIn('test_key_dest', config, "The config does not contain a value at the "
                                            "destination specified in the add_key call")
     self.assertEqual(config['test_key_dest'], test_values['test_key'])
     self.assertEqual(config.state, ValidationState.VALID)
 def test_add_key_default_invalid_value_provided(self):
     # Tests that a key added with a default DOES NOT USE that default
     # when an invalid value is given as the value to be validated
     config = ConfigSection('test', None)
     mock_validate_method = Mock()
     # Returning something (normally a tuple of (log_level, error_message)) from a validation
     # method with the log_level of 'error' means that the key is invalid
     # TODO Create a more meaningful way of validating values (and presenting messages about
     # validation to the user)
     mock_validate_method.return_value = ('error', 'THIS IS A BAD WAY TO GO...')
     config.add_key(key='test_key', validation_method=mock_validate_method,
                    default="test_key_default")
     values = {'test_key': 'PRETEND_BAD_VALUE'}
     config.update(values)
     config.validate()
     mock_validate_method.assert_called_once_with('test_key')
     self.assertIn('test_key', config)
     # The value that the invalid config holds on to should be the one that was provided,
     # NOT the default (which we assume is good to use)
     self.assertEqual(config['test_key'], values['test_key'])
     self.assertEqual(config.state, ValidationState.INVALID)
Beispiel #25
0
 def test_add_key_no_validation_method(self):
     # Tests that given a key and nothing else, add_key fails
     config = ConfigSection('test', None)
     self.assertRaises(AttributeError, config.add_key, key='test')