def test_get_charm_config(self):
        self.patch("builtins.open",
                   new_callable=mock.mock_open(),
                   name="_open")
        self.patch_object(lc_utils, 'yaml')
        _yaml = "testconfig: someconfig"
        _yaml_dict = {'test_config': 'someconfig'}
        self.yaml.safe_load.return_value = _yaml_dict
        _filename = "filename"
        _fileobj = mock.MagicMock()
        _fileobj.__enter__.return_value = _yaml
        self._open.return_value = _fileobj

        self.assertEqual(lc_utils.get_charm_config(yaml_file=_filename),
                         _yaml_dict)
        self._open.assert_called_once_with(_filename, "r")
        self.yaml.safe_load.assert_called_once_with(_yaml)
        self._open.side_effect = FileNotFoundError
        self.patch_object(lc_utils.os, 'getcwd')
        self.getcwd.return_value = '/absoulte/path/to/fakecwd'
        with self.assertRaises(FileNotFoundError):
            lc_utils.get_charm_config()
        self.assertEqual(lc_utils.get_charm_config(fatal=False),
                         {'charm_name': 'fakecwd'})
        self.getcwd.return_value = '/absoulte/path/to/charm-fakecwd'
        self.assertEqual(lc_utils.get_charm_config(fatal=False),
                         {'charm_name': 'fakecwd'})
Beispiel #2
0
    def test_get_charm_config(self):
        self.patch("builtins.open",
                   new_callable=mock.mock_open(),
                   name="_open")
        self.patch_object(lc_utils, 'yaml')
        self.patch_object(lc_utils, '_charm_config', new={})
        self.patch("zaza.global_options.merge", name="merge_mock")
        self.patch_object(lc_utils.logging, 'warning')
        _yaml = "testconfig: someconfig"
        _yaml_dict = {'test_config': 'someconfig'}
        self.yaml.safe_load.return_value = _yaml_dict
        _filename = "filename"
        _fileobj = mock.MagicMock()
        _fileobj.__enter__.return_value = _yaml
        self._open.return_value = _fileobj

        self.assertEqual(
            lc_utils.get_charm_config(yaml_file=_filename, cached=False),
            _yaml_dict)
        self._open.assert_called_once_with(_filename, "r")
        self.yaml.safe_load.assert_called_once_with(_yaml)
        self._open.side_effect = FileNotFoundError
        self.patch_object(lc_utils.os, 'getcwd')
        self.getcwd.return_value = '/absoulte/path/to/fakecwd'
        with self.assertRaises(FileNotFoundError):
            lc_utils.get_charm_config(cached=False)
        self.assertEqual(lc_utils.get_charm_config(fatal=False, cached=False),
                         {'charm_name': 'fakecwd'})
        self.getcwd.return_value = '/absoulte/path/to/charm-fakecwd'
        self.assertEqual(lc_utils.get_charm_config(fatal=False, cached=False),
                         {'charm_name': 'fakecwd'})
        # verify caching; note the patch above restores this to whatever it was
        # before this test_function was called.
        _bigger_yaml_dict = {
            "test_config": "someconfig",
            "tests_options": {
                "key1": 1,
                "key2": "two",
            },
        }
        self.yaml.safe_load.return_value = _bigger_yaml_dict
        _bigger_yaml = yaml.safe_dump(_bigger_yaml_dict)
        _fileobj.__enter__.return_value = _bigger_yaml
        self._open.side_effect = None
        self._open.return_value = _fileobj
        lc_utils._charm_config = {}
        self.merge_mock.reset_mock()
        lc_utils.get_charm_config(yaml_file=_filename)
        self.assertEqual(lc_utils._charm_config[_filename], _bigger_yaml_dict)
        self.merge_mock.assert_called_once_with(
            _bigger_yaml_dict["tests_options"], override=True)
        self._open.reset_mock()
        self.merge_mock.reset_mock()
        lc_utils.get_charm_config(yaml_file=_filename)
        self.assertEqual(lc_utils._charm_config[_filename], _bigger_yaml_dict)
        self._open.assert_not_called()
        self.merge_mock.assert_not_called()
Beispiel #3
0
def deploy(bundle, model, wait=True, model_ctxt=None, force=False):
    """Run all steps to complete deployment.

    :param bundle: Path to bundle file
    :type bundle: str
    :param model: Name of model to deploy bundle in
    :type model: str
    :param wait: Whether to wait until deployment completes
    :type wait: bool
    :param model_ctxt: Additional context to be used when rendering bundle
                       templates.
    :type model_ctxt: {}
    :param force: Pass the force parameter if True
    :type force: Boolean
    """
    run_report.register_event_start('Deploy Bundle')
    deploy_bundle(bundle, model, model_ctxt=model_ctxt, force=force)
    run_report.register_event_finish('Deploy Bundle')
    if wait:
        run_report.register_event_start('Wait for Deployment')
        test_config = utils.get_charm_config()
        logging.info("Waiting for environment to settle")
        zaza.model.set_juju_model(model)
        zaza.model.wait_for_application_states(
            model,
            test_config.get('target_deploy_status', {}))
        run_report.register_event_finish('Wait for Deployment')
Beispiel #4
0
def should_render_local_overlay(bundle):
    """Determine if the local overlay should be rendered.

    Check if an overlay file exists, then check if the bundle overrides
    LOCAL_OVERLAY_ENABLED_KEY with a False value. If no file exists, determine
    if the LOCAL_OVERLAY_TEMPLATE should be rendered by checking for the
    charm_name setting in the tests.yaml file.

    :param bundle: Name of bundle being deployed
    :type bundle: str
    :returns: Whether to render a local overlay
    :rtype: bool
    """
    # Is there a local overlay file?
    if os.path.isfile(
            os.path.join(
                DEFAULT_OVERLAY_TEMPLATE_DIR,
                "{}.j2".format(LOCAL_OVERLAY_TEMPLATE_NAME))):
        # Check for an override in the bundle.
        # Note: the default is True if the LOCAL_OVERLAY_ENABLED_KEY
        # is not present.
        return is_local_overlay_enabled_in_bundle(bundle)
    # Should we render the LOCAL_OVERLAY_TEMPLATE?
    elif utils.get_charm_config().get('charm_name', None):
        # Need to convert to boolean
        return True
    return False
Beispiel #5
0
    def test_102_keystone_ldap_group_membership(self):
        """Validate basic functionality of keystone API with ldap."""
        application_name = 'keystone-ldap'
        intended_cfg = self._get_ldap_config()
        current_cfg, non_string_cfg = (
            self.config_current_separate_non_string_type_keys(
                self.non_string_type_keys, intended_cfg, application_name))

        with self.config_change({},
                                non_string_cfg,
                                application_name=application_name,
                                reset_to_charm_default=True):
            with self.config_change(current_cfg,
                                    intended_cfg,
                                    application_name=application_name):
                logging.info(
                    'Waiting for groups to become available in keystone...')
                test_config = lifecycle_utils.get_charm_config(fatal=False)
                zaza.model.wait_for_application_states(
                    states=test_config.get("target_deploy_status", {}))

                with self.v3_keystone_preferred():
                    # NOTE(arif-ali): Test fixture should have openstack and
                    #                 admin groups
                    openstack_group = self._find_keystone_v3_user(
                        'john doe', 'userdomain', group='openstack')
                    self.assertIsNotNone(
                        openstack_group,
                        "john doe was not in group 'openstack'")
                    admin_group = self._find_keystone_v3_user('john doe',
                                                              'userdomain',
                                                              group='admin')
                    self.assertIsNotNone(
                        admin_group, "'john doe' was not in group 'admin'")
Beispiel #6
0
    def test_100_keystone_ldap_users(self):
        """Validate basic functionality of keystone API with ldap."""
        application_name = 'keystone-ldap'
        intended_cfg = self._get_ldap_config()
        current_cfg, non_string_cfg = (
            self.config_current_separate_non_string_type_keys(
                self.non_string_type_keys, intended_cfg, application_name))

        with self.config_change({},
                                non_string_cfg,
                                application_name=application_name,
                                reset_to_charm_default=True):
            with self.config_change(current_cfg,
                                    intended_cfg,
                                    application_name=application_name):
                logging.info(
                    'Waiting for users to become available in keystone...')
                test_config = lifecycle_utils.get_charm_config(fatal=False)
                zaza.model.wait_for_application_states(
                    states=test_config.get("target_deploy_status", {}))

                with self.v3_keystone_preferred():
                    # NOTE(jamespage): Test fixture should have
                    #                  johndoe and janedoe accounts
                    johndoe = self._find_keystone_v3_user(
                        'john doe', 'userdomain')
                    self.assertIsNotNone(johndoe,
                                         "user 'john doe' was unknown")
                    janedoe = self._find_keystone_v3_user(
                        'jane doe', 'userdomain')
                    self.assertIsNotNone(janedoe,
                                         "user 'jane doe' was unknown")
Beispiel #7
0
def validate_ca(cacertificate, application="keystone", port=5000):
    """Validate Certificate Authority against application.

    :param cacertificate: PEM formatted CA certificate
    :type cacertificate: str
    :param application: Which application to validate against.
    :type application: str
    :param port: Port to validate against.
    :type port: int
    :returns: None
    :rtype: None
    """
    zaza.model.block_until_file_has_contents(
        application, zaza.openstack.utilities.openstack.KEYSTONE_REMOTE_CACERT,
        cacertificate.decode().strip())
    test_config = lifecycle_utils.get_charm_config()
    zaza.model.wait_for_application_states(
        states=test_config.get('target_deploy_status', {}))
    vip = (
        zaza.model.get_application_config(application).get("vip").get("value"))
    if vip:
        ip = vip
    else:
        ip = zaza.model.get_app_ips(application)[0]
    with tempfile.NamedTemporaryFile(mode='w') as fp:
        fp.write(cacertificate.decode())
        fp.flush()
        requests.get('https://{}:{}'.format(ip, str(port)), verify=fp.name)
def auto_initialize(cacert=None, validation_application='keystone', wait=True):
    """Auto initialize vault for testing.

    Generate a csr and uploading a signed certificate.
    In a stack that includes and relies on certificates in vault, initialize
    vault by unsealing and creating a certificate authority.

    :param cacert: Path to CA cert used for vault's api cert.
    :type cacert: str
    :param validation_application: Name of application to be used as a
                                   client for validation.
    :type validation_application: str
    :returns: None
    :rtype: None
    """
    logging.info('Running auto_initialize')
    basic_setup(cacert=cacert, unseal_and_authorize=True)

    action = vault_utils.run_get_csr()
    intermediate_csr = action.data['results']['output']
    (cakey, cacertificate) = zaza.openstack.utilities.cert.generate_cert(
        'DivineAuthority',
        generate_ca=True)
    intermediate_cert = zaza.openstack.utilities.cert.sign_csr(
        intermediate_csr,
        cakey.decode(),
        cacertificate.decode(),
        generate_ca=True)
    action = vault_utils.run_upload_signed_csr(
        pem=intermediate_cert,
        root_ca=cacertificate,
        allowed_domains='openstack.local')

    if wait:
        zaza.model.wait_for_agent_status()
        test_config = lifecycle_utils.get_charm_config(fatal=False)
        zaza.model.wait_for_application_states(
            states=test_config.get('target_deploy_status', {}),
            timeout=7200)

    if validation_application:
        validate_ca(cacertificate, application=validation_application)
        # Once validation has completed restart nova-compute to work around
        # bug #1826382
        cmd_map = {
            'nova-cloud-controller': ('systemctl restart '
                                      'nova-scheduler nova-conductor'),
            'nova-compute': 'systemctl restart nova-compute',
        }
        for app in ('nova-compute', 'nova-cloud-controller',):
            try:
                for unit in zaza.model.get_units(app):
                    result = zaza.model.run_on_unit(
                        unit.entity_id, cmd_map[app])
                    assert int(result['Code']) == 0, (
                        'Restart of services on {} failed'.format(
                            unit.entity_id))
            except KeyError:
                # Nothing todo if there are no app units
                pass
Beispiel #9
0
 def test_get_charm_config(self):
     f = tempfile.NamedTemporaryFile(delete=False, mode='w')
     f.write(yaml.dump({'test_config': 'someconfig'}))
     f.close()
     charm_config = lc_utils.get_charm_config(yaml_file=f.name)
     os.unlink(f.name)
     self.assertEqual(charm_config, {'test_config': 'someconfig'})
    def setUpClass(cls, application_name=None, model_alias=None):
        """Run setup for test class to create common resources."""
        cls.model_aliases = model.get_juju_model_aliases()
        if model_alias:
            cls.model_name = cls.model_aliases[model_alias]
        else:
            cls.model_name = model.get_juju_model()
        cls.test_config = lifecycle_utils.get_charm_config(fatal=False)

        if application_name:
            cls.application_name = application_name
        else:
            charm_under_test_name = cls.test_config['charm_name']
            deployed_app_names = model.sync_deployed(model_name=cls.model_name)
            if charm_under_test_name in deployed_app_names:
                # There is an application named like the charm under test.
                # Let's consider it the application under test:
                cls.application_name = charm_under_test_name
            else:
                # Let's search for any application whose name starts with the
                # name of the charm under test and assume it's the application
                # under test:
                for app_name in deployed_app_names:
                    if app_name.startswith(charm_under_test_name):
                        cls.application_name = app_name
                        break
                else:
                    logging.warning('Could not find application under test')
                    return

        cls.lead_unit = model.get_lead_unit_name(cls.application_name,
                                                 model_name=cls.model_name)
        logging.debug('Leader unit is {}'.format(cls.lead_unit))
Beispiel #11
0
def main():
    """Run the tests defined by the command line args or if none were provided
       read the tests from the charms tests.yaml config file"""
    logging.basicConfig(level=logging.INFO)
    args = parse_args(sys.argv[1:])
    tests = args.tests or utils.get_charm_config()['tests']
    test(args.model_name, tests)
    asyncio.get_event_loop().close()
Beispiel #12
0
 def setUpClass(cls):
     """Run setup for test class to create common resourcea."""
     cls.keystone_session = openstack_utils.get_overcloud_keystone_session()
     cls.model_name = model.get_juju_model()
     cls.test_config = lifecycle_utils.get_charm_config()
     cls.application_name = cls.test_config['charm_name']
     cls.lead_unit = model.get_lead_unit_name(cls.application_name,
                                              model_name=cls.model_name)
     logging.debug('Leader unit is {}'.format(cls.lead_unit))
Beispiel #13
0
 def setUpClass(cls):
     """Run class setup for running Keystone SAML Mellon charm tests."""
     super(CharmKeystoneSAMLMellonTest, cls).setUpClass()
     # Note: The BaseKeystoneTest class sets the application_name to
     # "keystone" which breaks keystone-saml-mellon actions. Explicitly set
     # application name here.
     cls.test_config = lifecycle_utils.get_charm_config()
     cls.application_name = cls.test_config['charm_name']
     cls.action = "get-sp-metadata"
Beispiel #14
0
def main():
    """Run the configuration defined by the command line args or if none were
       provided read the configuration functions  from the charms tests.yaml
       config file"""
    logging.basicConfig(level=logging.INFO)
    args = parse_args(sys.argv[1:])
    funcs = args.configfuncs or utils.get_charm_config()['configure']
    configure(args.model_name, funcs)
    asyncio.get_event_loop().close()
Beispiel #15
0
    def setUpClass(cls, application_name=None, model_alias=None):
        """Run setup for test class to create common resources.

        Note: the derived class may not use the application_name; if it's set
        to None then this setUpClass() method will attempt to extract the
        application name from the charm_config (essentially the test.yaml)
        using the key 'charm_name' in the test_config.  If that isn't present,
        then there will be no application_name set, and this is considered a
        generic scenario of a whole model rather than a particular charm under
        test.

        :param application_name: the name of the applications that the derived
            class is testing.  If None, then it's a generic test not connected
            to any single charm.
        :type application_name: Optional[str]
        :param model_alias: the alias to use if needed.
        :type model_alias: Optional[str]
        """
        cls.model_aliases = model.get_juju_model_aliases()
        if model_alias:
            cls.model_name = cls.model_aliases[model_alias]
        else:
            cls.model_name = model.get_juju_model()
        cls.test_config = lifecycle_utils.get_charm_config(fatal=False)

        if application_name:
            cls.application_name = application_name
        else:
            try:
                charm_under_test_name = cls.test_config['charm_name']
            except KeyError:
                logging.warning("No application_name and no charm config so "
                                "not setting the application_name. Likely a "
                                "scenario test.")
                return
            deployed_app_names = model.sync_deployed(model_name=cls.model_name)
            if charm_under_test_name in deployed_app_names:
                # There is an application named like the charm under test.
                # Let's consider it the application under test:
                cls.application_name = charm_under_test_name
            else:
                # Let's search for any application whose name starts with the
                # name of the charm under test and assume it's the application
                # under test:
                for app_name in deployed_app_names:
                    if app_name.startswith(charm_under_test_name):
                        cls.application_name = app_name
                        break
                else:
                    logging.warning('Could not find application under test')
                    return

        cls.lead_unit = model.get_lead_unit_name(
            cls.application_name,
            model_name=cls.model_name)
        logging.debug('Leader unit is {}'.format(cls.lead_unit))
def s3_setup():
    """Run setup of s3 options for Trilio."""
    session = openstack_utils.get_overcloud_keystone_session()
    ks_client = openstack_utils.get_keystone_session_client(session)

    # Get token data so we can glean our user_id and project_id
    token_data = ks_client.tokens.get_token_data(session.get_token())
    project_id = token_data['token']['project']['id']
    user_id = token_data['token']['user']['id']

    # Store URL to service providing S3 compatible API
    for entry in token_data['token']['catalog']:
        if entry['type'] == 's3':
            for endpoint in entry['endpoints']:
                if endpoint['interface'] == 'public':
                    s3_region = endpoint['region']
                    s3_endpoint = endpoint['url']

    # Create AWS compatible application credentials in Keystone
    ec2_creds = ks_client.ec2.create(user_id, project_id)
    cacert = openstack_utils.get_cacert()
    kwargs = {
        'region_name': s3_region,
        'aws_access_key_id': ec2_creds.access,
        'aws_secret_access_key': ec2_creds.secret,
        'endpoint_url': s3_endpoint,
        'verify': cacert,
    }
    s3 = boto3.resource('s3', **kwargs)

    # Create bucket
    bucket_name = 'zaza-trilio'
    logging.info("Creating bucket: {}".format(bucket_name))
    bucket = s3.Bucket(bucket_name)
    bucket.create()

    s3_config = {
        'tv-s3-secret-key': ec2_creds.secret,
        'tv-s3-access-key': ec2_creds.access,
        'tv-s3-region-name': s3_region,
        'tv-s3-bucket': bucket_name,
        'tv-s3-endpoint-url': s3_endpoint
    }
    for app in ['trilio-wlm', 'trilio-data-mover']:
        logging.info("Setting s3 config for {}".format(app))
        zaza_model.set_application_config(app, s3_config)
    test_config = lifecycle_utils.get_charm_config(fatal=False)
    states = test_config.get('target_deploy_status', {})
    states['trilio-wlm'] = {
        'workload-status': 'blocked',
        'workload-status-message': 'application not trusted'
    }
    zaza_model.wait_for_application_states(states=test_config.get(
        'target_deploy_status', {}),
                                           timeout=7200)
    zaza_model.block_until_all_units_idle()
Beispiel #17
0
def get_charm_config_context():
    """Return settings from charm config file.

    :returns: Context for template rendering
    :rtype: dict
    """
    test_config = utils.get_charm_config()
    ctxt = {
        'charm_name': test_config['charm_name'],
        'charm_location': '../../../{}'.format(test_config['charm_name'])}
    return ctxt
    def test_unseal(self, test_config=None):
        """Unseal Vault.

        :param test_config: (Optional) Zaza test config
        :type test_config: charm_lifecycle.utils.get_charm_config()
        """
        vault_utils.run_charm_authorize(self.vault_creds['root_token'])
        if not test_config:
            test_config = lifecycle_utils.get_charm_config()
        del test_config['target_deploy_status']['vault']
        zaza.model.wait_for_application_states(
            states=test_config.get('target_deploy_status', {}))
Beispiel #19
0
 def class_decorator(cls):
     """Add tests based on input yaml to `cls`."""
     files = utils.get_charm_config('./files.yaml')
     deployed_applications = model.sync_deployed()
     for name, attributes in files.items():
         # Lets make sure to only add tests for deployed applications
         if name in deployed_applications:
             for file in attributes['files']:
                 test_func = _make_test_function(name, file)
                 setattr(cls, 'test_{}_{}'.format(name, file['path']),
                         test_func)
     return cls
Beispiel #20
0
def main():
    """Run the tests defined by the command line args.

    Run the tests defined by the command line args or if none were provided
    read the tests from the charms tests.yaml config file
    """
    args = parse_args(sys.argv[1:])
    cli_utils.setup_logging(log_level=args.loglevel.upper())
    tests = args.tests or utils.get_charm_config()['tests']
    test(args.model_name, tests)
    run_report.output_event_report()
    asyncio.get_event_loop().close()
Beispiel #21
0
def main():
    """Run the configuration defined by the command line args.

    Run the configuration defined by the command line args or if none were
    provided read the configuration functions  from the charms tests.yaml
    config file
    """
    args = parse_args(sys.argv[1:])
    cli_utils.setup_logging(log_level=args.loglevel.upper())
    funcs = args.configfuncs or utils.get_charm_config()['before_deploy']
    before_deploy(args.model_name, funcs)
    run_report.output_event_report()
    asyncio.get_event_loop().close()
Beispiel #22
0
def basic_overcloud_network(limit_gws=None):
    """Run setup for neutron networking.

    Configure the following:
        The overcloud network using subnet pools

    :param limit_gws: Limit the number of gateways that get a port attached
    :type limit_gws: int
    """
    cli_utils.setup_logging()

    # Get network configuration settings
    network_config = {}
    # Declared overcloud settings
    network_config.update(OVERCLOUD_NETWORK_CONFIG)
    # Default undercloud settings
    network_config.update(DEFAULT_UNDERCLOUD_NETWORK_CONFIG)
    # Environment specific settings
    network_config.update(generic_utils.get_undercloud_env_vars())

    # Get keystone session
    keystone_session = openstack_utils.get_overcloud_keystone_session()

    # Get optional use_juju_wait for network option
    options = (lifecycle_utils.get_charm_config(fatal=False).get(
        'configure_options', {}))
    use_juju_wait = options.get('configure_gateway_ext_port_use_juju_wait',
                                True)

    # Handle network for OpenStack-on-OpenStack scenarios
    provider_type = juju_utils.get_provider_type()
    if provider_type == "openstack":
        undercloud_ks_sess = openstack_utils.get_undercloud_keystone_session()
        network.setup_gateway_ext_port(network_config,
                                       keystone_session=undercloud_ks_sess,
                                       limit_gws=limit_gws,
                                       use_juju_wait=use_juju_wait)
    elif provider_type == "maas":
        # NOTE(fnordahl): After validation of the MAAS+Netplan Open vSwitch
        # integration support, we would most likely want to add multiple modes
        # of operation with MAAS.
        #
        # Perform charm based OVS configuration
        openstack_utils.configure_charmed_openstack_on_maas(
            network_config, limit_gws=limit_gws)
    else:
        logging.warning('Unknown Juju provider type, "{}", will not perform'
                        ' charm network configuration.'.format(provider_type))

    # Confugre the overcloud network
    network.setup_sdn(network_config, keystone_session=keystone_session)
Beispiel #23
0
def main():
    """Run the tests defined by the command line args.

    Run the tests defined by the command line args or if none were provided
    read the tests from the charms tests.yaml config file
    """
    args = parse_args(sys.argv[1:])
    level = getattr(logging, args.loglevel.upper(), None)
    if not isinstance(level, int):
        raise ValueError('Invalid log level: "{}"'.format(args.loglevel))
    logging.basicConfig(level=level)
    tests = args.tests or utils.get_charm_config()['tests']
    test(args.model_name, tests)
    asyncio.get_event_loop().close()
Beispiel #24
0
def wait_for_cacert(model_name=None):
    """Wait for keystone to install a cacert.

    :param model_name: Name of model to query.
    :type model_name: str
    """
    logging.info("Waiting for cacert")
    zaza.openstack.utilities.openstack.block_until_ca_exists(
        'keystone', 'CERTIFICATE', model_name=model_name)
    zaza.model.block_until_all_units_idle(model_name=model_name)
    test_config = lifecycle_utils.get_charm_config(fatal=False)
    zaza.model.wait_for_application_states(states=test_config.get(
        'target_deploy_status', {}),
                                           model_name=model_name)
Beispiel #25
0
    def test_200_config_flags_precedence(self):
        """Validates precedence when the same config options are used."""
        application_name = 'keystone-ldap'
        intended_cfg = self._get_ldap_config()
        current_cfg, non_string_cfg = (
            self.config_current_separate_non_string_type_keys(
                self.non_string_type_keys, intended_cfg, application_name)
        )

        with self.config_change(
                {},
                non_string_cfg,
                application_name=application_name,
                reset_to_charm_default=True):
            with self.config_change(
                    current_cfg,
                    intended_cfg,
                    application_name=application_name):
                logging.info(
                    'Performing LDAP settings validation in keystone.conf...'
                )
                test_config = lifecycle_utils.get_charm_config(fatal=False)
                zaza.model.wait_for_application_states(
                    states=test_config.get("target_deploy_status", {})
                )
                units = zaza.model.get_units("keystone-ldap",
                                             model_name=self.model_name)
                result = zaza.model.run_on_unit(
                    units[0].name,
                    "cat /etc/keystone/domains/keystone.userdomain.conf")
                # not present in charm config, but present in config flags
                self.assertIn("use_pool = True", result['stdout'],
                              "use_pool value is expected to be present and "
                              "set to True in the config file")
                # ldap-config-flags overriding empty charm config value
                self.assertIn("group_objectclass = posixGroup",
                              result['stdout'],
                              "group_objectclass is expected to be present and"
                              " set to posixGroup in the config file")
                # overridden by charm config, not written to file
                self.assertNotIn(
                    "group_tree_dn_foobar",
                    result['stdout'],
                    "user_tree_dn ldap-config-flags value needs to be "
                    "overridden by ldap-user-tree-dn in config file")
                # complementing the above, value used is from charm setting
                self.assertIn("group_tree_dn = ou=groups", result['stdout'],
                              "user_tree_dn value is expected to be present "
                              "and set to dc=test,dc=com in the config file")
Beispiel #26
0
 def setUpClass(cls, application_name=None, model_alias=None):
     """Run setup for test class to create common resources."""
     cls.model_aliases = model.get_juju_model_aliases()
     if model_alias:
         cls.model_name = cls.model_aliases[model_alias]
     else:
         cls.model_name = model.get_juju_model()
     cls.test_config = lifecycle_utils.get_charm_config(fatal=False)
     if application_name:
         cls.application_name = application_name
     else:
         cls.application_name = cls.test_config['charm_name']
     cls.lead_unit = model.get_lead_unit_name(cls.application_name,
                                              model_name=cls.model_name)
     logging.debug('Leader unit is {}'.format(cls.lead_unit))
Beispiel #27
0
def func_test_runner():
    """Deploy the bundles and run the tests as defined by the charms tests.yaml
    """
    test_config = utils.get_charm_config()
    for t in test_config['gate_bundles']:
        model_name = generate_model_name(test_config['charm_name'], t)
        # Prepare
        prepare.prepare(model_name)
        # Deploy
        deploy.deploy(os.path.join(utils.BUNDLE_DIR, '{}.yaml'.format(t)),
                      model_name)
        # Configure
        configure.configure(model_name, test_config['configure'])
        # Test
        test.test(model_name, test_config['tests'])
        # Destroy
        destroy.destroy(model_name)
Beispiel #28
0
def deploy(bundle, model, wait=True):
    """Run all steps to complete deployment.

    :param bundle: Path to bundle file
    :type bundle: str
    :param model: Name of model to deploy bundle in
    :type model: str
    :param wait: Whether to wait until deployment completes
    :type model: bool
    """
    deploy_bundle(bundle, model)
    if wait:
        test_config = utils.get_charm_config()
        logging.info("Waiting for environment to settle")
        zaza.model.set_juju_model(model)
        zaza.model.wait_for_application_states(
            model, test_config.get('target_deploy_status', {}))
Beispiel #29
0
    def test_get_charm_config(self):
        self.patch("builtins.open",
                   new_callable=mock.mock_open(),
                   name="_open")
        self.patch_object(lc_utils, 'yaml')
        _yaml = "testconfig: someconfig"
        _yaml_dict = {'test_config': 'someconfig'}
        self.yaml.safe_load.return_value = _yaml_dict
        _filename = "filename"
        _fileobj = mock.MagicMock()
        _fileobj.__enter__.return_value = _yaml
        self._open.return_value = _fileobj

        self.assertEqual(lc_utils.get_charm_config(yaml_file=_filename),
                         _yaml_dict)
        self._open.assert_called_once_with(_filename, "r")
        self.yaml.safe_load.assert_called_once_with(_yaml)
Beispiel #30
0
def render_local_overlay(target_dir):
    """Render the local overlay template in the directory supplied.

    :param target_dir: Directory to render overlay in
    :type overlay_name: str
    :returns: Path to rendered overlay
    :rtype: str
    """
    template = get_template(LOCAL_OVERLAY_TEMPLATE_NAME)
    if not template:
        template = jinja2.Environment(
            loader=jinja2.BaseLoader).from_string(LOCAL_OVERLAY_TEMPLATE)
    rendered_template_file = os.path.join(
        target_dir, os.path.basename(LOCAL_OVERLAY_TEMPLATE_NAME))
    if utils.get_charm_config().get('charm_name', None):
        render_template(template, rendered_template_file)
        return rendered_template_file