Esempio n. 1
0
    def _add_or_update_vars(self):
        """
        Create host and/or group vars and returns None.

        :returns: None
        """
        # Create the hosts extra inventory source (only if not empty)
        hosts_file = os.path.join(self.inventory_directory, "hosts")
        if self.hosts:
            util.write_file(hosts_file, util.safe_dump(self.hosts))
        # Create the host_vars and group_vars directories
        for target in ["host_vars", "group_vars"]:
            if target == "host_vars":
                vars_target = copy.deepcopy(self.host_vars)
                for instance_name, _ in self.host_vars.items():
                    instance_key = instance_name
                    vars_target[instance_key] = vars_target.pop(instance_name)

            elif target == "group_vars":
                vars_target = self.group_vars

            if vars_target:
                target_vars_directory = os.path.join(self.inventory_directory, target)

                if not os.path.isdir(util.abs_path(target_vars_directory)):
                    os.mkdir(util.abs_path(target_vars_directory))

                for target in vars_target.keys():
                    target_var_content = vars_target[target]
                    path = os.path.join(util.abs_path(target_vars_directory), target)
                    util.write_file(path, util.safe_dump(target_var_content))
Esempio n. 2
0
def test_get_config_with_multiple_base_configs(config_instance):
    config_instance.args = {"base_config": ["./foo.yml", "./foo2.yml"]}
    contents = {"foo": "bar", "foo2": "bar"}
    util.write_file(config_instance.args["base_config"][0], util.safe_dump(contents))
    contents = {"foo2": "bar2"}
    util.write_file(config_instance.args["base_config"][1], util.safe_dump(contents))
    result = config_instance._get_config()

    assert result["foo"] == "bar"
    assert result["foo2"] == "bar2"
Esempio n. 3
0
def test_command_init_scenario(temp_dir):
    with change_dir_to(temp_dir):
        os.makedirs(os.path.join(temp_dir, "molecule", "default"))
        scenario_directory = os.path.join(temp_dir, "molecule",
                                          "test-scenario")
        cmd = [
            "molecule",
            "init",
            "scenario",
            "test-scenario",
            "--driver-name",
            "vagrant",
        ]
        result = run_command(cmd)
        assert result.returncode == 0

        assert os.path.isdir(scenario_directory)
        confpath = os.path.join(scenario_directory, "molecule.yml")
        conf = util.safe_load_file(confpath)
        env = os.environ
        if "TESTBOX" in env:
            conf["platforms"][0]["box"] = env["TESTBOX"]
        if not os.path.exists("/dev/kvm"):
            conf["driver"]["provider"] = {"name": "libvirt"}
            for p in conf["platforms"]:
                p["provider_options"] = {"driver": '"qemu"'}
        util.write_file(confpath, util.safe_dump(conf))

        cmd = ["molecule", "--debug", "test", "-s", "test-scenario"]
        result = run_command(cmd)
        assert result.returncode == 0
Esempio n. 4
0
    def _add_or_update_vars(self):
        """
        Creates host and/or group vars and returns None.

        :returns: None
        """
        for target in ['host_vars', 'group_vars']:
            if target == 'host_vars':
                vars_target = copy.deepcopy(self.host_vars)
                for instance_name, _ in self.host_vars.items():
                    if instance_name == 'localhost':
                        instance_key = instance_name
                    else:
                        instance_key = instance_name

                    vars_target[instance_key] = vars_target.pop(instance_name)

            elif target == 'group_vars':
                vars_target = self.group_vars

            if vars_target:
                ephemeral_directory = self._config.scenario.ephemeral_directory
                target_vars_directory = os.path.join(ephemeral_directory,
                                                     target)

                if not os.path.isdir(util.abs_path(target_vars_directory)):
                    os.mkdir(util.abs_path(target_vars_directory))

                for target in vars_target.keys():
                    target_var_content = vars_target[target]
                    path = os.path.join(util.abs_path(target_vars_directory),
                                        target)
                    util.write_file(path, util.safe_dump(target_var_content))
Esempio n. 5
0
def test_safe_dump():
    x = """
---
foo: bar
""".lstrip()

    assert x == util.safe_dump({'foo': 'bar'})
Esempio n. 6
0
def test_safe_dump():
    x = """
---
foo: bar
""".lstrip()

    assert x == util.safe_dump({'foo': 'bar'})
Esempio n. 7
0
    def _add_or_update_vars(self):
        """
        Creates host and/or group vars and returns None.

        :returns: None
        """
        for target in ['host_vars', 'group_vars']:
            if target == 'host_vars':
                vars_target = copy.deepcopy(self.host_vars)
                for instance_name, _ in self.host_vars.items():
                    if instance_name == 'localhost':
                        instance_key = instance_name
                    else:
                        instance_key = instance_name

                    vars_target[instance_key] = vars_target.pop(instance_name)

            elif target == 'group_vars':
                vars_target = self.group_vars

            if vars_target:
                ephemeral_directory = self._config.scenario.ephemeral_directory
                target_vars_directory = os.path.join(ephemeral_directory,
                                                     target)

                if not os.path.isdir(util.abs_path(target_vars_directory)):
                    os.mkdir(util.abs_path(target_vars_directory))

                for target in vars_target.keys():
                    target_var_content = vars_target[target]
                    path = os.path.join(
                        util.abs_path(target_vars_directory), target)
                    util.write_file(path, util.safe_dump(target_var_content))
Esempio n. 8
0
def test_get_data_loads_existing_state_file(temp_dir, molecule_data):
    molecule_directory = pytest.helpers.molecule_directory()
    scenario_directory = os.path.join(molecule_directory, 'default')
    molecule_file = pytest.helpers.get_molecule_file(scenario_directory)
    ephemeral_directory = pytest.helpers.molecule_ephemeral_directory()
    state_file = os.path.join(ephemeral_directory, 'state.yml')

    os.makedirs(ephemeral_directory)

    data = {
        'converged': False,
        'created': True,
        'driver': None,
        'prepared': None,
    }
    util.write_file(state_file, util.safe_dump(data))

    pytest.helpers.write_molecule_file(molecule_file, molecule_data)
    c = config.Config(molecule_file)
    s = state.State(c)

    assert not s.converged
    assert s.created
    assert not s.driver
    assert not s.prepared
Esempio n. 9
0
def _print_yaml_data(headers, data):  # pragma: no cover
    l = [
        dict(zip(headers, [getattr(datum, field) for field in datum._fields]))
        for datum in data
    ]

    print(util.safe_dump(l))
Esempio n. 10
0
def test_safe_dump():
    x = """
---
foo: bar
""".lstrip()

    assert x == util.safe_dump({"foo": "bar"})
Esempio n. 11
0
    def add_or_update_vars(self, target):
        """
        Creates host and/or group vars and returns None.

        :param target: A string containing either `host_vars` or `group_vars`.
        :returns: None
        """
        if target == 'host_vars':
            vars_target = copy.deepcopy(self.host_vars)
            # Append the scenario-name
            for instance_name, _ in self.host_vars.items():
                if instance_name == 'localhost':
                    instance_key = instance_name
                else:
                    instance_key = util.instance_with_scenario_name(
                        instance_name, self._config.scenario.name)

                vars_target[instance_key] = vars_target.pop(instance_name)

        elif target == 'group_vars':
            vars_target = self.group_vars

        if not vars_target:
            return

        ephemeral_directory = self._config.ephemeral_directory
        target_vars_directory = os.path.join(ephemeral_directory, target)

        if not os.path.isdir(os.path.abspath(target_vars_directory)):
            os.mkdir(os.path.abspath(target_vars_directory))

        for target in vars_target.keys():
            target_var_content = vars_target[target]
            path = os.path.join(os.path.abspath(target_vars_directory), target)
            util.write_file(path, util.safe_dump(target_var_content))
Esempio n. 12
0
def test_get_config_with_base_config(config_instance):
    config_instance.args = {'base_config': './foo.yml'}
    contents = {'foo': 'bar'}
    util.write_file(config_instance.args['base_config'], util.safe_dump(contents))
    result = config_instance._get_config()

    assert result['foo'] == 'bar'
Esempio n. 13
0
def _print_yaml_data(headers, data):  # pragma: no cover
    l = [
        dict(zip(headers, [getattr(datum, field) for field in datum._fields]))
        for datum in data
    ]

    print(util.safe_dump(l))
Esempio n. 14
0
def test_print_environment_vars(capsys):
    env = {
        'ANSIBLE_FOO': 'foo',
        'ANSIBLE_BAR': 'bar',
        'ANSIBLE': None,
        'MOLECULE_FOO': 'foo',
        'MOLECULE_BAR': 'bar',
        'MOLECULE': None
    }
    util.print_environment_vars(env)
    result, _ = capsys.readouterr()

    # Ansible Environment
    title = [
        colorama.Back.WHITE, colorama.Style.BRIGHT, colorama.Fore.BLACK,
        'DEBUG: ANSIBLE ENVIRONMENT', colorama.Fore.RESET, colorama.Back.RESET,
        colorama.Style.RESET_ALL
    ]
    print(''.join(title))
    data = [
        colorama.Fore.BLACK, colorama.Style.BRIGHT,
        util.safe_dump({
            'ANSIBLE_FOO': 'foo',
            'ANSIBLE_BAR': 'bar'
        }), colorama.Style.RESET_ALL, colorama.Fore.RESET
    ]
    print(''.join(data))

    # Molecule Environment
    title = [
        colorama.Back.WHITE, colorama.Style.BRIGHT, colorama.Fore.BLACK,
        'DEBUG: MOLECULE ENVIRONMENT', colorama.Fore.RESET,
        colorama.Back.RESET, colorama.Style.RESET_ALL
    ]
    print(''.join(title))
    data = [
        colorama.Fore.BLACK, colorama.Style.BRIGHT,
        util.safe_dump({
            'MOLECULE_FOO': 'foo',
            'MOLECULE_BAR': 'bar'
        }), colorama.Style.RESET_ALL, colorama.Fore.RESET
    ]
    print(''.join(data))

    x, _ = capsys.readouterr()
    assert x == result
Esempio n. 15
0
def _print_yaml_data(headers, data):  # pragma: no cover
    l = [
        dict(zip(headers, [getattr(datum, field) for field in datum._fields]))
        for datum in data
    ]

    syntax = Syntax(util.safe_dump(l), "yaml")
    console.print(syntax)
Esempio n. 16
0
def test_print_environment_vars(capsys):
    env = {
        'ANSIBLE_FOO': 'foo',
        'ANSIBLE_BAR': 'bar',
        'ANSIBLE': None,
        'MOLECULE_FOO': 'foo',
        'MOLECULE_BAR': 'bar',
        'MOLECULE': None
    }
    util.print_environment_vars(env)
    result, _ = capsys.readouterr()

    # Ansible Environment
    title = [
        colorama.Back.WHITE, colorama.Style.BRIGHT, colorama.Fore.BLACK,
        'DEBUG: ANSIBLE ENVIRONMENT', colorama.Fore.RESET, colorama.Back.RESET,
        colorama.Style.RESET_ALL
    ]
    print(''.join(title))
    data = [
        colorama.Fore.BLACK, colorama.Style.BRIGHT,
        util.safe_dump({
            'ANSIBLE_FOO': 'foo',
            'ANSIBLE_BAR': 'bar'
        }), colorama.Style.RESET_ALL, colorama.Fore.RESET
    ]
    print(''.join(data))

    # Molecule Environment
    title = [
        colorama.Back.WHITE, colorama.Style.BRIGHT, colorama.Fore.BLACK,
        'DEBUG: MOLECULE ENVIRONMENT', colorama.Fore.RESET,
        colorama.Back.RESET, colorama.Style.RESET_ALL
    ]
    print(''.join(title))
    data = [
        colorama.Fore.BLACK, colorama.Style.BRIGHT,
        util.safe_dump({
            'MOLECULE_FOO': 'foo',
            'MOLECULE_BAR': 'bar'
        }), colorama.Style.RESET_ALL, colorama.Fore.RESET
    ]
    print(''.join(data))

    x, _ = capsys.readouterr()
    assert x == result
Esempio n. 17
0
def test_set_env_from_file(config_instance):
    config_instance.args = {'env_file': '.env'}
    contents = {'foo': 'bar', 'BAZ': 'zzyzx'}
    env_file = config_instance.args.get('env_file')
    util.write_file(env_file, util.safe_dump(contents))
    env = config.set_env_from_file({}, env_file)

    assert contents == env
Esempio n. 18
0
def test_set_env_from_file(config_instance):
    config_instance.args = {"env_file": ".env"}
    contents = {"foo": "bar", "BAZ": "zzyzx"}
    env_file = config_instance.args.get("env_file")
    util.write_file(env_file, util.safe_dump(contents))
    env = config.set_env_from_file({}, env_file)

    assert contents == env
Esempio n. 19
0
def test_get_config_with_base_config(config_instance):
    config_instance.args = {"base_config": "./foo.yml"}
    contents = {"foo": "bar"}
    util.write_file(config_instance.args["base_config"],
                    util.safe_dump(contents))
    result = config_instance._get_config()

    assert result["foo"] == "bar"
Esempio n. 20
0
def test_get_configs(config_instance):
    molecule_file = config_instance.molecule_file
    data = config_instance.config
    util.write_file(molecule_file, util.safe_dump(data))

    result = base.get_configs({}, {})
    assert 1 == len(result)
    assert isinstance(result, list)
    assert isinstance(result[0], config.Config)
Esempio n. 21
0
    def _write_inventory(self):
        """
        Writes the provisioner's inventory file to disk and returns None.

        :return: None
        """
        self._verify_inventory()

        util.write_file(self.inventory_file, util.safe_dump(self.inventory))
Esempio n. 22
0
def test_get_configs(config_instance):
    molecule_file = config_instance.molecule_file
    data = config_instance.config
    util.write_file(molecule_file, util.safe_dump(data))

    result = base.get_configs({}, {})
    assert 1 == len(result)
    assert isinstance(result, list)
    assert isinstance(result[0], config.Config)
Esempio n. 23
0
    def _write_inventory(self):
        """
        Writes the provisioner's inventory file to disk and returns None.

        :return: None
        """
        self._verify_inventory()

        util.write_file(self.inventory_file, util.safe_dump(self.inventory))
Esempio n. 24
0
def test_safe_dump_with_increase_indent():
    data = {'foo': [{'foo': 'bar', 'baz': 'zzyzx'}]}

    x = """
---
foo:
  - baz: zzyzx
    foo: bar
""".lstrip()
    assert x == util.safe_dump(data)
Esempio n. 25
0
def test_set_env(config_instance):
    config_instance.args = {'env_file': '.env'}
    contents = {
        'foo': 'bar',
        'BAZ': 'zzyzx',
    }
    util.write_file(config_instance.args['env_file'], util.safe_dump(contents))
    env = config_instance._set_env({})

    assert contents == env
Esempio n. 26
0
def test_safe_dump_with_increase_indent():
    data = {"foo": [{"foo": "bar", "baz": "zzyzx"}]}

    x = """
---
foo:
  - baz: zzyzx
    foo: bar
""".lstrip()
    assert x == util.safe_dump(data)
Esempio n. 27
0
 def print_debug(self):
     testaid_env = \
         {k: v for (k, v) in os.environ.items() if 'TESTVARS_' in k}
     if testaid_env:
         print('\n')
         util.print_debug('TESTVARS ENVIRONMENT',
                          util.safe_dump(testaid_env))
     log = self.get_log()
     if log:
         if not testaid_env:
             print('\n')
         util.print_debug('TESTVARS LOG', log)
Esempio n. 28
0
def test_safe_dump_with_increase_indent():
    data = {
        'foo': [{
            'foo': 'bar',
            'baz': 'zzyzx',
        }],
    }

    x = """
---
foo:
  - baz: zzyzx
    foo: bar
""".lstrip()
    assert x == util.safe_dump(data)
Esempio n. 29
0
def test_combine_raises_on_failed_interpolation(patched_logger_critical,
                                                config_instance):
    contents = {'foo': '$6$8I5Cfmpr$kGZB'}
    util.write_file(config_instance.molecule_file, util.safe_dump(contents))

    with pytest.raises(SystemExit) as e:
        config_instance._combine()

    assert 1 == e.value.code

    msg = ("parsing config file '{}'.\n\n"
           'Invalid placeholder in string: line 4, col 6\n'
           '# Molecule managed\n\n'
           '---\n'
           'foo: $6$8I5Cfmpr$kGZB\n').format(config_instance.molecule_file)
    patched_logger_critical.assert_called_once_with(msg)
Esempio n. 30
0
def test_get_data_loads_existing_state_file(_instance, molecule_data,
                                            config_instance):
    data = {
        "converged": False,
        "created": True,
        "driver": None,
        "prepared": None
    }
    util.write_file(_instance._state_file, util.safe_dump(data))

    s = state.State(config_instance)

    assert not s.converged
    assert s.created
    assert not s.driver
    assert not s.prepared
Esempio n. 31
0
def test_get_data_loads_existing_state_file(temp_dir, molecule_data):
    molecule_directory = pytest.helpers.molecule_directory()
    scenario_directory = os.path.join(molecule_directory, 'default')
    molecule_file = pytest.helpers.get_molecule_file(scenario_directory)
    ephemeral_directory = pytest.helpers.molecule_ephemeral_directory()
    state_file = os.path.join(ephemeral_directory, 'state.yml')

    os.makedirs(ephemeral_directory)

    data = {'converged': False, 'created': True, 'driver': None}
    util.write_file(state_file, util.safe_dump(data))

    pytest.helpers.write_molecule_file(molecule_file, molecule_data)
    c = config.Config(molecule_file)
    s = state.State(c)

    assert not s.converged
    assert s.created
    assert not s.driver
Esempio n. 32
0
 def write(self):
     util.write_file(self.config_file, util.safe_dump(self.config))
Esempio n. 33
0
def to_yaml(data):
    return str(util.safe_dump(data))
Esempio n. 34
0
def write_molecule_file(filename: str, data: Any) -> None:
    util.write_file(filename, util.safe_dump(data))
Esempio n. 35
0
def to_yaml(data):
    return str(util.safe_dump(data))
Esempio n. 36
0
 def _write_state_file(self):
     util.write_file(self.state_file, util.safe_dump(self._data))
Esempio n. 37
0
def write_molecule_file(filename, data):
    util.write_file(filename, util.safe_dump(data))
Esempio n. 38
0
def test_print_environment_vars(capsys):
    env = {
        "ANSIBLE_FOO": "foo",
        "ANSIBLE_BAR": "bar",
        "ANSIBLE": None,
        "MOLECULE_FOO": "foo",
        "MOLECULE_BAR": "bar",
        "MOLECULE": None,
    }
    util.print_environment_vars(env)
    result, _ = capsys.readouterr()

    # Ansible Environment
    title = [
        colorama.Back.WHITE,
        colorama.Style.BRIGHT,
        colorama.Fore.BLACK,
        "DEBUG: ANSIBLE ENVIRONMENT",
        colorama.Fore.RESET,
        colorama.Back.RESET,
        colorama.Style.RESET_ALL,
    ]
    print("".join(title))
    data = [
        colorama.Fore.BLACK,
        colorama.Style.BRIGHT,
        util.safe_dump({"ANSIBLE_FOO": "foo", "ANSIBLE_BAR": "bar"}),
        colorama.Style.RESET_ALL,
        colorama.Fore.RESET,
    ]
    print("".join(data))

    # Molecule Environment
    title = [
        colorama.Back.WHITE,
        colorama.Style.BRIGHT,
        colorama.Fore.BLACK,
        "DEBUG: MOLECULE ENVIRONMENT",
        colorama.Fore.RESET,
        colorama.Back.RESET,
        colorama.Style.RESET_ALL,
    ]
    print("".join(title))
    data = [
        colorama.Fore.BLACK,
        colorama.Style.BRIGHT,
        util.safe_dump({"MOLECULE_FOO": "foo", "MOLECULE_BAR": "bar"}),
        colorama.Style.RESET_ALL,
        colorama.Fore.RESET,
    ]
    print("".join(data))

    # Shell Replay
    title = [
        colorama.Back.WHITE,
        colorama.Style.BRIGHT,
        colorama.Fore.BLACK,
        "DEBUG: SHELL REPLAY",
        colorama.Fore.RESET,
        colorama.Back.RESET,
        colorama.Style.RESET_ALL,
    ]
    print("".join(title))
    data = [
        colorama.Fore.BLACK,
        colorama.Style.BRIGHT,
        "ANSIBLE_BAR=bar ANSIBLE_FOO=foo MOLECULE_BAR=bar MOLECULE_FOO=foo",
        colorama.Style.RESET_ALL,
        colorama.Fore.RESET,
    ]
    print("".join(data))
    print()

    x, _ = capsys.readouterr()
    assert x == result
Esempio n. 39
0
def write_molecule_file(filename, data):
    util.write_file(filename, util.safe_dump(data))
Esempio n. 40
0
def to_yaml(data):
    """Format data as YAML."""
    return str(util.safe_dump(data))