How to use _get_modules_directories method in molecule

Best Python code snippet using molecule_python

ansible.py

Source:ansible.py Github

copy

Full Screen

...351 "/etc/ansible/roles",352 ]353 ),354 "ANSIBLE_COLLECTIONS_PATHS": ":".join(collections_paths_list),355 "ANSIBLE_LIBRARY": ":".join(self._get_modules_directories()),356 "ANSIBLE_FILTER_PLUGINS": ":".join(357 [358 self._get_filter_plugin_directory(),359 util.abs_path(360 os.path.join(361 self._config.scenario.ephemeral_directory,362 "plugins",363 "filter",364 )365 ),366 util.abs_path(367 os.path.join(368 self._config.project_directory, "plugins", "filter"369 )370 ),371 util.abs_path(372 os.path.join(373 os.path.expanduser("~"), ".ansible", "plugins", "filter"374 )375 ),376 "/usr/share/ansible/plugins/filter",377 ]378 ),379 },380 )381 env = util.merge_dicts(env, self._config.env)382 return env383 @property384 def name(self):385 return self._config.config["provisioner"]["name"]386 @property387 def ansible_args(self):388 return self._config.config["provisioner"]["ansible_args"]389 @property390 def config_options(self):391 return util.merge_dicts(392 self.default_config_options,393 self._config.config["provisioner"]["config_options"],394 )395 @property396 def options(self):397 if self._config.action in ["create", "destroy"]:398 return self.default_options399 o = self._config.config["provisioner"]["options"]400 # NOTE(retr0h): Remove verbose options added by the user while in401 # debug.402 if self._config.debug:403 o = util.filter_verbose_permutation(o)404 return util.merge_dicts(self.default_options, o)405 @property406 def env(self):407 default_env = self.default_env408 env = self._config.config["provisioner"]["env"].copy()409 # ensure that all keys and values are strings410 env = {str(k): str(v) for k, v in env.items()}411 roles_path = default_env["ANSIBLE_ROLES_PATH"]412 library_path = default_env["ANSIBLE_LIBRARY"]413 filter_plugins_path = default_env["ANSIBLE_FILTER_PLUGINS"]414 try:415 path = self._absolute_path_for(env, "ANSIBLE_ROLES_PATH")416 roles_path = "{}:{}".format(roles_path, path)417 except KeyError:418 pass419 try:420 path = self._absolute_path_for(env, "ANSIBLE_LIBRARY")421 library_path = "{}:{}".format(library_path, path)422 except KeyError:423 pass424 try:425 path = self._absolute_path_for(env, "ANSIBLE_FILTER_PLUGINS")426 filter_plugins_path = "{}:{}".format(filter_plugins_path, path)427 except KeyError:428 pass429 env["ANSIBLE_ROLES_PATH"] = roles_path430 env["ANSIBLE_LIBRARY"] = library_path431 env["ANSIBLE_FILTER_PLUGINS"] = filter_plugins_path432 return util.merge_dicts(default_env, env)433 @property434 def hosts(self):435 return self._config.config["provisioner"]["inventory"]["hosts"]436 @property437 def host_vars(self):438 return self._config.config["provisioner"]["inventory"]["host_vars"]439 @property440 def group_vars(self):441 return self._config.config["provisioner"]["inventory"]["group_vars"]442 @property443 def links(self):444 return self._config.config["provisioner"]["inventory"]["links"]445 @property446 def inventory(self):447 """448 Create an inventory structure and returns a dict.449 .. code-block:: yaml450 ungrouped:451 vars:452 foo: bar453 hosts:454 instance-1:455 instance-2:456 children:457 $child_group_name:458 hosts:459 instance-1:460 instance-2:461 $group_name:462 hosts:463 instance-1:464 ansible_connection: docker465 instance-2:466 ansible_connection: docker467 :return: str468 """469 dd = self._vivify()470 for platform in self._config.platforms.instances:471 for group in platform.get("groups", ["ungrouped"]):472 instance_name = platform["name"]473 connection_options = self.connection_options(instance_name)474 molecule_vars = {475 "molecule_file": "{{ lookup('env', 'MOLECULE_FILE') }}",476 "molecule_ephemeral_directory": "{{ lookup('env', 'MOLECULE_EPHEMERAL_DIRECTORY') }}",477 "molecule_scenario_directory": "{{ lookup('env', 'MOLECULE_SCENARIO_DIRECTORY') }}",478 "molecule_yml": "{{ lookup('file', molecule_file) | molecule_from_yaml }}",479 "molecule_instance_config": "{{ lookup('env', 'MOLECULE_INSTANCE_CONFIG') }}",480 "molecule_no_log": "{{ lookup('env', 'MOLECULE_NO_LOG') or not "481 "molecule_yml.provisioner.log|default(False) | bool }}",482 }483 # All group484 dd["all"]["hosts"][instance_name] = connection_options485 dd["all"]["vars"] = molecule_vars486 # Named group487 dd[group]["hosts"][instance_name] = connection_options488 dd[group]["vars"] = molecule_vars489 # Ungrouped490 dd["ungrouped"]["vars"] = {}491 # Children492 for child_group in platform.get("children", []):493 dd[group]["children"][child_group]["hosts"][494 instance_name495 ] = connection_options496 return self._default_to_regular(dd)497 @property498 def inventory_directory(self):499 return self._config.scenario.inventory_directory500 @property501 def inventory_file(self):502 return os.path.join(self.inventory_directory, "ansible_inventory.yml")503 @property504 def config_file(self):505 return os.path.join(self._config.scenario.ephemeral_directory, "ansible.cfg")506 @property # type: ignore507 @util.lru_cache()508 def playbooks(self):509 return ansible_playbooks.AnsiblePlaybooks(self._config)510 @property511 def directory(self):512 return os.path.join(513 os.path.dirname(__file__),514 os.path.pardir,515 os.path.pardir,516 "molecule",517 "provisioner",518 "ansible",519 )520 def cleanup(self):521 """522 Execute `ansible-playbook` against the cleanup playbook and returns \523 None.524 :return: None525 """526 pb = self._get_ansible_playbook(self.playbooks.cleanup)527 pb.execute()528 def connection_options(self, instance_name):529 d = self._config.driver.ansible_connection_options(instance_name)530 return util.merge_dicts(531 d, self._config.config["provisioner"]["connection_options"]532 )533 def check(self):534 """535 Execute ``ansible-playbook`` against the converge playbook with the \536 ``--check`` flag and returns None.537 :return: None538 """539 pb = self._get_ansible_playbook(self.playbooks.converge)540 pb.add_cli_arg("check", True)541 pb.execute()542 def converge(self, playbook=None, **kwargs):543 """544 Execute ``ansible-playbook`` against the converge playbook unless \545 specified otherwise and returns a string.546 :param playbook: An optional string containing an absolute path to a547 playbook.548 :param kwargs: An optional keyword arguments.549 :return: str550 """551 pb = self._get_ansible_playbook(playbook or self.playbooks.converge, **kwargs)552 return pb.execute()553 def destroy(self):554 """555 Execute ``ansible-playbook`` against the destroy playbook and returns \556 None.557 :return: None558 """559 pb = self._get_ansible_playbook(self.playbooks.destroy)560 pb.execute()561 def side_effect(self):562 """563 Execute ``ansible-playbook`` against the side_effect playbook and \564 returns None.565 :return: None566 """567 pb = self._get_ansible_playbook(self.playbooks.side_effect)568 pb.execute()569 def create(self):570 """571 Execute ``ansible-playbook`` against the create playbook and returns \572 None.573 :return: None574 """575 pb = self._get_ansible_playbook(self.playbooks.create)576 pb.execute()577 def prepare(self):578 """579 Execute ``ansible-playbook`` against the prepare playbook and returns \580 None.581 :return: None582 """583 pb = self._get_ansible_playbook(self.playbooks.prepare)584 pb.execute()585 def syntax(self):586 """587 Execute ``ansible-playbook`` against the converge playbook with the \588 ``-syntax-check`` flag and returns None.589 :return: None590 """591 pb = self._get_ansible_playbook(self.playbooks.converge)592 pb.add_cli_arg("syntax-check", True)593 pb.execute()594 def verify(self):595 """596 Execute ``ansible-playbook`` against the verify playbook and returns \597 None.598 :return: None599 """600 if not self.playbooks.verify:601 LOG.warning("Skipping, verify playbook not configured.")602 return603 pb = self._get_ansible_playbook(self.playbooks.verify)604 pb.execute()605 def write_config(self):606 """607 Write the provisioner's config file to disk and returns None.608 :return: None609 """610 template = util.render_template(611 self._get_config_template(), config_options=self.config_options612 )613 util.write_file(self.config_file, template)614 def manage_inventory(self):615 """616 Manage inventory for Ansible and returns None.617 :returns: None618 """619 self._write_inventory()620 self._remove_vars()621 if not self.links:622 self._add_or_update_vars()623 else:624 self._link_or_update_vars()625 def abs_path(self, path):626 return util.abs_path(os.path.join(self._config.scenario.directory, path))627 def _add_or_update_vars(self):628 """629 Create host and/or group vars and returns None.630 :returns: None631 """632 # Create the hosts extra inventory source (only if not empty)633 hosts_file = os.path.join(self.inventory_directory, "hosts")634 if self.hosts:635 util.write_file(hosts_file, util.safe_dump(self.hosts))636 # Create the host_vars and group_vars directories637 for target in ["host_vars", "group_vars"]:638 if target == "host_vars":639 vars_target = copy.deepcopy(self.host_vars)640 for instance_name, _ in self.host_vars.items():641 instance_key = instance_name642 vars_target[instance_key] = vars_target.pop(instance_name)643 elif target == "group_vars":644 vars_target = self.group_vars645 if vars_target:646 target_vars_directory = os.path.join(self.inventory_directory, target)647 if not os.path.isdir(util.abs_path(target_vars_directory)):648 os.mkdir(util.abs_path(target_vars_directory))649 for target in vars_target.keys():650 target_var_content = vars_target[target]651 path = os.path.join(util.abs_path(target_vars_directory), target)652 util.write_file(path, util.safe_dump(target_var_content))653 def _write_inventory(self):654 """655 Write the provisioner's inventory file to disk and returns None.656 :return: None657 """658 self._verify_inventory()659 util.write_file(self.inventory_file, util.safe_dump(self.inventory))660 def _remove_vars(self):661 """662 Remove hosts/host_vars/group_vars and returns None.663 :returns: None664 """665 for name in ("hosts", "group_vars", "host_vars"):666 d = os.path.join(self.inventory_directory, name)667 if os.path.islink(d) or os.path.isfile(d):668 os.unlink(d)669 elif os.path.isdir(d):670 shutil.rmtree(d)671 def _link_or_update_vars(self):672 """673 Create or updates the symlink to group_vars and returns None.674 :returns: None675 """676 for d, source in self.links.items():677 target = os.path.join(self.inventory_directory, d)678 source = os.path.join(self._config.scenario.directory, source)679 if not os.path.exists(source):680 msg = "The source path '{}' does not exist.".format(source)681 util.sysexit_with_message(msg)682 msg = "Inventory {} linked to {}".format(source, target)683 LOG.info(msg)684 os.symlink(source, target)685 def _get_ansible_playbook(self, playbook, **kwargs):686 """687 Get an instance of AnsiblePlaybook and returns it.688 :param playbook: A string containing an absolute path to a689 provisioner's playbook.690 :param kwargs: An optional keyword arguments.691 :return: object692 """693 return ansible_playbook.AnsiblePlaybook(playbook, self._config, **kwargs)694 def _verify_inventory(self):695 """696 Verify the inventory is valid and returns None.697 :return: None698 """699 if not self.inventory:700 msg = "Instances missing from the 'platform' " "section of molecule.yml."701 util.sysexit_with_message(msg)702 def _get_config_template(self):703 """704 Return a config template string.705 :return: str706 """707 return """708{% for section, section_dict in config_options.items() -%}709[{{ section }}]710{% for k, v in section_dict.items() -%}711{{ k }} = {{ v }}712{% endfor -%}713{% endfor -%}714""".strip()715 def _vivify(self):716 """717 Return an autovivification default dict.718 :return: dict719 """720 return collections.defaultdict(self._vivify)721 def _default_to_regular(self, d):722 if isinstance(d, collections.defaultdict):723 d = {k: self._default_to_regular(v) for k, v in d.items()}724 return d725 def _get_plugin_directory(self):726 return os.path.join(self.directory, "plugins")727 def _get_modules_directories(self):728 """Return list of ansilbe module includes directories.729 Adds modules directory from molecule and its plugins.730 """731 paths = [util.abs_path(os.path.join(self._get_plugin_directory(), "modules"))]732 for d in drivers():733 p = d.modules_dir()734 if p:735 paths.append(p)736 paths.extend(737 [738 util.abs_path(739 os.path.join(self._config.scenario.ephemeral_directory, "library")740 ),741 util.abs_path(os.path.join(self._config.project_directory, "library")),...

Full Screen

Full Screen

test_ansible.py

Source:test_ansible.py Github

copy

Full Screen

...176 # molecule could decide to add extra paths, so we only want to check177 # that those that we need are kept inside the list with exact order178 roles_path_list = _instance.env["ANSIBLE_ROLES_PATH"].split(":")179 assert roles_path_list == expected180 x = _instance._get_modules_directories()181 x.append(182 util.abs_path(os.path.join(_instance._config.scenario.directory, "foo", "bar"))183 )184 assert x == _instance.env["ANSIBLE_LIBRARY"].split(":")185 x = [186 _instance._get_filter_plugin_directory(),187 util.abs_path(188 os.path.join(189 _instance._config.scenario.ephemeral_directory, "plugins", "filter"190 )191 ),192 util.abs_path(193 os.path.join(_instance._config.project_directory, "plugins", "filter")194 ),195 util.abs_path(196 os.path.join(os.path.expanduser("~"), ".ansible", "plugins", "filter")197 ),198 "/usr/share/ansible/plugins/filter",199 util.abs_path(os.path.join(_instance._config.scenario.directory, "foo", "bar")),200 ]201 assert x == _instance.env["ANSIBLE_FILTER_PLUGINS"].split(":")202@pytest.mark.parametrize(203 "config_instance", ["_provisioner_section_data"], indirect=True204)205def test_env_appends_env_property_with_os_env(_instance):206 os.environ["ANSIBLE_ROLES_PATH"] = "/foo/bar:/foo/baz"207 expected = [208 util.abs_path(os.path.join(_instance._config.runtime.cache_dir, "roles")),209 util.abs_path(210 os.path.join(_instance._config.scenario.ephemeral_directory, "roles")211 ),212 util.abs_path(213 os.path.join(_instance._config.project_directory, os.path.pardir)214 ),215 util.abs_path(os.path.join(os.path.expanduser("~"), ".ansible", "roles")),216 "/usr/share/ansible/roles",217 "/etc/ansible/roles",218 "/foo/bar",219 "/foo/baz",220 util.abs_path(os.path.join(_instance._config.scenario.directory, "foo", "bar")),221 ]222 # molecule could decide to add extra paths, so we only want to check223 # that those that we need are kept inside the list224 roles_path_list = _instance.env["ANSIBLE_ROLES_PATH"].split(":")225 assert roles_path_list == expected226@pytest.mark.parametrize(227 "config_instance", ["_provisioner_section_data"], indirect=True228)229def test_host_vars_property(_instance):230 x = {"instance-1": [{"foo": "bar"}], "localhost": [{"foo": "baz"}]}231 assert x == _instance.host_vars232@pytest.mark.parametrize(233 "config_instance", ["_provisioner_section_data"], indirect=True234)235def test_group_vars_property(_instance):236 x = {"example_group1": [{"foo": "bar"}], "example_group2": [{"foo": "bar"}]}237 assert x == _instance.group_vars238@pytest.mark.parametrize(239 "config_instance", ["_provisioner_section_data"], indirect=True240)241def test_hosts_property(_instance):242 hosts = {243 "all": {244 "hosts": {"extra-host-01": {}},245 "children": {"extra-group": {"hosts": ["extra-host-01"]}},246 }247 }248 assert hosts == _instance.hosts249def test_links_property(_instance):250 assert {} == _instance.links251def test_inventory_directory_property(_instance):252 x = os.path.join(_instance._config.scenario.ephemeral_directory, "inventory")253 assert x == _instance.inventory_directory254def test_inventory_file_property(_instance):255 x = os.path.join(256 _instance._config.scenario.inventory_directory, "ansible_inventory.yml"257 )258 assert x == _instance.inventory_file259def test_config_file_property(_instance):260 x = os.path.join(_instance._config.scenario.ephemeral_directory, "ansible.cfg")261 assert x == _instance.config_file262def test_playbooks_property(_instance):263 assert isinstance(_instance.playbooks, ansible_playbooks.AnsiblePlaybooks)264def test_directory_property(_instance):265 result = _instance.directory266 parts = os_split(result)267 assert ("molecule", "provisioner", "ansible") == parts[-3:]268def test_playbooks_cleaned_property_is_optional(_instance):269 assert _instance.playbooks.cleanup is None270def test_playbooks_converge_property(_instance):271 x = os.path.join(_instance._config.scenario.directory, "converge.yml")272 assert x == _instance.playbooks.converge273def test_playbooks_side_effect_property(_instance):274 assert _instance.playbooks.side_effect is None275def test_check(_instance, mocker, _patched_ansible_playbook):276 _instance.check()277 _patched_ansible_playbook.assert_called_once_with(278 _instance._config.provisioner.playbooks.converge, _instance._config, False279 )280 _patched_ansible_playbook.return_value.add_cli_arg.assert_called_once_with(281 "check", True282 )283 _patched_ansible_playbook.return_value.execute.assert_called_once_with()284def test_converge(_instance, mocker, _patched_ansible_playbook):285 result = _instance.converge()286 _patched_ansible_playbook.assert_called_once_with(287 _instance._config.provisioner.playbooks.converge, _instance._config, False288 )289 # NOTE(retr0h): This is not the true return type. This is a mock return290 # which didn't go through str.decode().291 assert result == b"patched-ansible-playbook-stdout"292 _patched_ansible_playbook.return_value.execute.assert_called_once_with()293def test_converge_with_playbook(_instance, mocker, _patched_ansible_playbook):294 result = _instance.converge("playbook")295 _patched_ansible_playbook.assert_called_once_with(296 "playbook", _instance._config, False297 )298 # NOTE(retr0h): This is not the true return type. This is a mock return299 # which didn't go through str.decode().300 assert result == b"patched-ansible-playbook-stdout"301 _patched_ansible_playbook.return_value.execute.assert_called_once_with()302def test_cleanup(_instance, mocker, _patched_ansible_playbook):303 _instance.cleanup()304 _patched_ansible_playbook.assert_called_once_with(305 _instance._config.provisioner.playbooks.cleanup, _instance._config, False306 )307 _patched_ansible_playbook.return_value.execute.assert_called_once_with()308def test_destroy(_instance, mocker, _patched_ansible_playbook):309 _instance.destroy()310 _patched_ansible_playbook.assert_called_once_with(311 _instance._config.provisioner.playbooks.destroy, _instance._config, False312 )313 _patched_ansible_playbook.return_value.execute.assert_called_once_with()314def test_side_effect(_instance, mocker, _patched_ansible_playbook):315 _instance.side_effect()316 _patched_ansible_playbook.assert_called_once_with(317 _instance._config.provisioner.playbooks.side_effect, _instance._config, False318 )319 _patched_ansible_playbook.return_value.execute.assert_called_once_with()320def test_create(_instance, mocker, _patched_ansible_playbook):321 _instance.create()322 _patched_ansible_playbook.assert_called_once_with(323 _instance._config.provisioner.playbooks.create, _instance._config, False324 )325 _patched_ansible_playbook.return_value.execute.assert_called_once_with()326def test_prepare(_instance, mocker, _patched_ansible_playbook):327 _instance.prepare()328 _patched_ansible_playbook.assert_called_once_with(329 _instance._config.provisioner.playbooks.prepare, _instance._config, False330 )331 _patched_ansible_playbook.return_value.execute.assert_called_once_with()332def test_syntax(_instance, mocker, _patched_ansible_playbook):333 _instance.syntax()334 _patched_ansible_playbook.assert_called_once_with(335 _instance._config.provisioner.playbooks.converge, _instance._config, False336 )337 _patched_ansible_playbook.return_value.add_cli_arg.assert_called_once_with(338 "syntax-check", True339 )340 _patched_ansible_playbook.return_value.execute.assert_called_once_with()341def test_verify(_instance, mocker, _patched_ansible_playbook):342 _instance.verify()343 if _instance._config.provisioner.playbooks.verify:344 _patched_ansible_playbook.assert_called_once_with(345 _instance._config.provisioner.playbooks.verify, _instance._config346 )347 _patched_ansible_playbook.return_value.execute.assert_called_once_with()348def test_write_config(temp_dir, _instance):349 _instance.write_config()350 assert os.path.isfile(_instance.config_file)351def test_manage_inventory(352 _instance,353 _patched_write_inventory,354 _patched_remove_vars,355 patched_add_or_update_vars,356 _patched_link_or_update_vars,357):358 _instance.manage_inventory()359 _patched_write_inventory.assert_called_once_with()360 _patched_remove_vars.assert_called_once_with()361 patched_add_or_update_vars.assert_called_once_with()362 assert not _patched_link_or_update_vars.called363def test_manage_inventory_with_links(364 _instance,365 _patched_write_inventory,366 _patched_remove_vars,367 patched_add_or_update_vars,368 _patched_link_or_update_vars,369):370 c = _instance._config.config371 c["provisioner"]["inventory"]["links"] = {"foo": "bar"}372 _instance.manage_inventory()373 _patched_write_inventory.assert_called_once_with()374 _patched_remove_vars.assert_called_once_with()375 assert not patched_add_or_update_vars.called376 _patched_link_or_update_vars.assert_called_once_with()377@pytest.mark.parametrize(378 "config_instance", ["_provisioner_section_data"], indirect=True379)380def test_add_or_update_vars(_instance):381 inventory_dir = _instance._config.scenario.inventory_directory382 host_vars_directory = os.path.join(inventory_dir, "host_vars")383 host_vars = os.path.join(host_vars_directory, "instance-1")384 _instance._add_or_update_vars()385 assert os.path.isdir(host_vars_directory)386 assert os.path.isfile(host_vars)387 host_vars_localhost = os.path.join(host_vars_directory, "localhost")388 assert os.path.isfile(host_vars_localhost)389 group_vars_directory = os.path.join(inventory_dir, "group_vars")390 group_vars_1 = os.path.join(group_vars_directory, "example_group1")391 group_vars_2 = os.path.join(group_vars_directory, "example_group2")392 assert os.path.isdir(group_vars_directory)393 assert os.path.isfile(group_vars_1)394 assert os.path.isfile(group_vars_2)395 hosts = os.path.join(inventory_dir, "hosts")396 assert os.path.isfile(hosts)397 assert util.safe_load_file(hosts) == _instance.hosts398@pytest.mark.parametrize(399 "config_instance", ["_provisioner_section_data"], indirect=True400)401def test_add_or_update_vars_without_host_vars(_instance):402 c = _instance._config.config403 c["provisioner"]["inventory"]["host_vars"] = {}404 inventory_dir = _instance._config.scenario.inventory_directory405 host_vars_directory = os.path.join(inventory_dir, "host_vars")406 host_vars = os.path.join(host_vars_directory, "instance-1")407 _instance._add_or_update_vars()408 assert not os.path.isdir(host_vars_directory)409 assert not os.path.isfile(host_vars)410 host_vars_localhost = os.path.join(host_vars_directory, "localhost")411 assert not os.path.isfile(host_vars_localhost)412 group_vars_directory = os.path.join(inventory_dir, "group_vars")413 group_vars_1 = os.path.join(group_vars_directory, "example_group1")414 group_vars_2 = os.path.join(group_vars_directory, "example_group2")415 assert os.path.isdir(group_vars_directory)416 assert os.path.isfile(group_vars_1)417 assert os.path.isfile(group_vars_2)418 hosts = os.path.join(inventory_dir, "hosts")419 assert os.path.isfile(hosts)420 assert util.safe_load_file(hosts) == _instance.hosts421def test_add_or_update_vars_does_not_create_vars(_instance):422 c = _instance._config.config423 c["provisioner"]["inventory"]["hosts"] = {}424 c["provisioner"]["inventory"]["host_vars"] = {}425 c["provisioner"]["inventory"]["group_vars"] = {}426 inventory_dir = _instance._config.scenario.inventory_directory427 hosts = os.path.join(inventory_dir, "hosts")428 host_vars_directory = os.path.join(inventory_dir, "host_vars")429 group_vars_directory = os.path.join(inventory_dir, "group_vars")430 _instance._add_or_update_vars()431 assert not os.path.isdir(host_vars_directory)432 assert not os.path.isdir(group_vars_directory)433 assert not os.path.isfile(hosts)434@pytest.mark.parametrize(435 "config_instance", ["_provisioner_section_data"], indirect=True436)437def test_remove_vars(_instance):438 inventory_dir = _instance._config.scenario.inventory_directory439 hosts = os.path.join(inventory_dir, "hosts")440 host_vars_directory = os.path.join(inventory_dir, "host_vars")441 host_vars = os.path.join(host_vars_directory, "instance-1")442 _instance._add_or_update_vars()443 assert os.path.isfile(hosts)444 assert os.path.isdir(host_vars_directory)445 assert os.path.isfile(host_vars)446 host_vars_localhost = os.path.join(host_vars_directory, "localhost")447 assert os.path.isfile(host_vars_localhost)448 group_vars_directory = os.path.join(inventory_dir, "group_vars")449 group_vars_1 = os.path.join(group_vars_directory, "example_group1")450 group_vars_2 = os.path.join(group_vars_directory, "example_group2")451 assert os.path.isdir(group_vars_directory)452 assert os.path.isfile(group_vars_1)453 assert os.path.isfile(group_vars_2)454 _instance._remove_vars()455 assert not os.path.isfile(hosts)456 assert not os.path.isdir(host_vars_directory)457 assert not os.path.isdir(group_vars_directory)458def test_remove_vars_symlinks(_instance):459 inventory_dir = _instance._config.scenario.inventory_directory460 source_group_vars = os.path.join(inventory_dir, os.path.pardir, "group_vars")461 target_group_vars = os.path.join(inventory_dir, "group_vars")462 os.mkdir(source_group_vars)463 os.symlink(source_group_vars, target_group_vars)464 _instance._remove_vars()465 assert not os.path.lexists(target_group_vars)466def test_link_vars(_instance):467 c = _instance._config.config468 c["provisioner"]["inventory"]["links"] = {469 "hosts": "../hosts",470 "group_vars": "../group_vars",471 "host_vars": "../host_vars",472 }473 inventory_dir = _instance._config.scenario.inventory_directory474 scenario_dir = _instance._config.scenario.directory475 source_hosts = os.path.join(scenario_dir, os.path.pardir, "hosts")476 target_hosts = os.path.join(inventory_dir, "hosts")477 source_group_vars = os.path.join(scenario_dir, os.path.pardir, "group_vars")478 target_group_vars = os.path.join(inventory_dir, "group_vars")479 source_host_vars = os.path.join(scenario_dir, os.path.pardir, "host_vars")480 target_host_vars = os.path.join(inventory_dir, "host_vars")481 open(source_hosts, "w").close() # pylint: disable=consider-using-with482 os.mkdir(source_group_vars)483 os.mkdir(source_host_vars)484 _instance._link_or_update_vars()485 assert os.path.lexists(target_hosts)486 assert os.path.lexists(target_group_vars)487 assert os.path.lexists(target_host_vars)488def test_link_vars_raises_when_source_not_found(_instance, patched_logger_critical):489 c = _instance._config.config490 c["provisioner"]["inventory"]["links"] = {"foo": "../bar"}491 with pytest.raises(SystemExit) as e:492 _instance._link_or_update_vars()493 assert 1 == e.value.code494 source = os.path.join(_instance._config.scenario.directory, os.path.pardir, "bar")495 msg = f"The source path '{source}' does not exist."496 patched_logger_critical.assert_called_once_with(msg)497def test_verify_inventory(_instance):498 _instance._verify_inventory()499def test_verify_inventory_raises_when_missing_hosts(500 temp_dir, patched_logger_critical, _instance501):502 _instance._config.config["platforms"] = []503 with pytest.raises(SystemExit) as e:504 _instance._verify_inventory()505 assert 1 == e.value.code506 msg = "Instances missing from the 'platform' section of molecule.yml."507 patched_logger_critical.assert_called_once_with(msg)508def test_vivify(_instance):509 d = _instance._vivify()510 d["bar"]["baz"] = "qux"511 assert "qux" == str(d["bar"]["baz"])512def test_default_to_regular(_instance):513 d = collections.defaultdict()514 assert isinstance(d, collections.defaultdict)515 d = _instance._default_to_regular(d)516 assert isinstance(d, dict)517def test_get_plugin_directory(_instance):518 result = _instance._get_plugin_directory()519 parts = os_split(result)520 assert ("molecule", "provisioner", "ansible", "plugins") == parts[-4:]521def test_get_modules_directories_default(_instance, monkeypatch):522 monkeypatch.delenv("ANSIBLE_LIBRARY", raising=False)523 paths = _instance._get_modules_directories()524 assert len(paths) == 5525 assert re.search(r"molecule/provisioner/ansible/plugins/modules$", paths[0])526 assert re.search(r"\.cache/molecule/[^/]+/default/library$", paths[1])527 assert re.search(r"/library$", paths[2])528 assert re.search(r"\.ansible/plugins/modules$", paths[3])529 assert re.search(r"/usr/share/ansible/plugins/modules$", paths[4])530def test_get_modules_directories_single_ansible_library(_instance, monkeypatch):531 monkeypatch.setenv("ANSIBLE_LIBRARY", "/abs/path/lib")532 paths = _instance._get_modules_directories()533 assert len(paths) == 6534 assert paths[0] == "/abs/path/lib"535def test_get_modules_directories_multi_ansible_library(_instance, monkeypatch):536 monkeypatch.setenv("ANSIBLE_LIBRARY", "relpath/lib:/abs/path/lib")537 paths = _instance._get_modules_directories()538 assert len(paths) == 7539 assert paths[0].endswith("relpath/lib")540 assert paths[1] == "/abs/path/lib"541def test_get_filter_plugin_directory(_instance):542 result = _instance._get_filter_plugin_directory()543 parts = os_split(result)544 x = ("molecule", "provisioner", "ansible", "plugins", "filter")545 assert x == parts[-5:]546def test_absolute_path_for(_instance):547 env = {"foo": "foo:bar"}548 x = ":".join(549 [550 os.path.join(_instance._config.scenario.directory, "foo"),551 os.path.join(_instance._config.scenario.directory, "bar"),...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run molecule automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful