Best Python code snippet using molecule_python
test_vagrant.py
Source:test_vagrant.py
1# Copyright (c) 2015-2018 Cisco Systems, Inc.2#3# Permission is hereby granted, free of charge, to any person obtaining a copy4# of this software and associated documentation files (the "Software"), to5# deal in the Software without restriction, including without limitation the6# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or7# sell copies of the Software, and to permit persons to whom the Software is8# furnished to do so, subject to the following conditions:9#10# The above copyright notice and this permission notice shall be included in11# all copies or substantial portions of the Software.12#13# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE16# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER17# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING18# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER19# DEALINGS IN THE SOFTWARE.20import os21import pytest22from molecule import config23from molecule.driver import vagrant24@pytest.fixture25def _driver_section_data():26 return {27 'driver': {28 'name': 'vagrant',29 'provider': {30 'name': 'virtualbox',31 },32 'options': {},33 'ssh_connection_options': ['-o foo=bar'],34 'safe_files': ['foo'],35 }36 }37# NOTE(retr0h): The use of the `patched_config_validate` fixture, disables38# config.Config._validate from executing. Thus preventing odd side-effects39# throughout patched.assert_called unit tests.40@pytest.fixture41def _instance(patched_config_validate, config_instance):42 return vagrant.Vagrant(config_instance)43def test_config_private_member(_instance):44 assert isinstance(_instance._config, config.Config)45def test_testinfra_options_property(_instance):46 x = {47 'connection': 'ansible',48 'ansible-inventory': _instance._config.provisioner.inventory_file49 }50 assert x == _instance.testinfra_options51def test_name_property(_instance):52 assert 'vagrant' == _instance.name53def test_options_property(_instance):54 x = {'managed': True}55 assert x == _instance.options56@pytest.mark.parametrize(57 'config_instance', ['_driver_section_data'], indirect=True)58def test_login_cmd_template_property(_instance):59 x = 'ssh {address} -l {user} -p {port} -i {identity_file} -o foo=bar'60 assert x == _instance.login_cmd_template61@pytest.mark.parametrize(62 'config_instance', ['_driver_section_data'], indirect=True)63def test_safe_files_property(_instance):64 x = [65 os.path.join(_instance._config.scenario.ephemeral_directory,66 'Vagrantfile'),67 os.path.join(_instance._config.scenario.ephemeral_directory,68 'vagrant.yml'),69 os.path.join(_instance._config.scenario.ephemeral_directory,70 'instance_config.yml'),71 os.path.join(_instance._config.scenario.ephemeral_directory,72 '.vagrant'),73 os.path.join(_instance._config.scenario.ephemeral_directory,74 'vagrant-*.out'),75 os.path.join(_instance._config.scenario.ephemeral_directory,76 'vagrant-*.err'),77 'foo',78 ]79 assert x == _instance.safe_files80def test_default_safe_files_property(_instance):81 x = [82 os.path.join(_instance._config.scenario.ephemeral_directory,83 'Vagrantfile'),84 os.path.join(_instance._config.scenario.ephemeral_directory,85 'vagrant.yml'),86 os.path.join(_instance._config.scenario.ephemeral_directory,87 'instance_config.yml'),88 os.path.join(_instance._config.scenario.ephemeral_directory,89 '.vagrant'),90 os.path.join(_instance._config.scenario.ephemeral_directory,91 'vagrant-*.out'),92 os.path.join(_instance._config.scenario.ephemeral_directory,93 'vagrant-*.err'),94 ]95 assert x == _instance.default_safe_files96def test_delegated_property(_instance):97 assert not _instance.delegated98def test_managed_property(_instance):99 assert _instance.managed100def test_default_ssh_connection_options_property(_instance):101 x = [102 '-o UserKnownHostsFile=/dev/null',103 '-o ControlMaster=auto',104 '-o ControlPersist=60s',105 '-o IdentitiesOnly=yes',106 '-o StrictHostKeyChecking=no',107 ]108 assert x == _instance.default_ssh_connection_options109def test_login_options(mocker, _instance):110 m = mocker.patch('molecule.driver.vagrant.Vagrant._get_instance_config')111 m.return_value = {112 'instance': 'foo',113 'address': '127.0.0.1',114 'user': 'vagrant',115 'port': 2222,116 'identity_file': '/foo/bar',117 }118 x = {119 'instance': 'foo',120 'address': '127.0.0.1',121 'user': 'vagrant',122 'port': 2222,123 'identity_file': '/foo/bar'124 }125 assert x == _instance.login_options('foo')126@pytest.mark.parametrize(127 'config_instance', ['_driver_section_data'], indirect=True)128def test_ansible_connection_options(mocker, _instance):129 m = mocker.patch('molecule.driver.vagrant.Vagrant._get_instance_config')130 m.return_value = {131 'instance': 'foo',132 'address': '127.0.0.1',133 'user': 'vagrant',134 'port': 2222,135 'identity_file': '/foo/bar',136 }137 x = {138 'ansible_host': '127.0.0.1',139 'ansible_port': 2222,140 'ansible_user': 'vagrant',141 'ansible_private_key_file': '/foo/bar',142 'connection': 'ssh',143 'ansible_ssh_common_args': '-o foo=bar',144 }145 assert x == _instance.ansible_connection_options('foo')146def test_ansible_connection_options_handles_missing_instance_config(147 mocker, _instance):148 m = mocker.patch('molecule.util.safe_load_file')149 m.side_effect = IOError150 assert {} == _instance.ansible_connection_options('foo')151def test_ansible_connection_options_handles_missing_results_key(152 mocker, _instance):153 m = mocker.patch('molecule.util.safe_load_file')154 m.side_effect = StopIteration155 assert {} == _instance.ansible_connection_options('foo')156def test_vagrantfile_property(_instance):157 x = os.path.join(_instance._config.scenario.ephemeral_directory,158 'Vagrantfile')159 assert x == _instance.vagrantfile160def test_vagrantfile_config_property(_instance):161 x = os.path.join(_instance._config.scenario.ephemeral_directory,162 'vagrant.yml')163 assert x == _instance.vagrantfile_config164def test_instance_config_property(_instance):165 x = os.path.join(_instance._config.scenario.ephemeral_directory,166 'instance_config.yml')167 assert x == _instance.instance_config168@pytest.mark.parametrize(169 'config_instance', ['_driver_section_data'], indirect=True)170def test_ssh_connection_options_property(_instance):171 x = ['-o foo=bar']172 assert x == _instance.ssh_connection_options173def test_status(mocker, _instance):174 result = _instance.status()175 assert 2 == len(result)176 assert result[0].instance_name == 'instance-1'177 assert result[0].driver_name == 'vagrant'178 assert result[0].provisioner_name == 'ansible'179 assert result[0].scenario_name == 'default'180 assert result[0].created == 'false'181 assert result[0].converged == 'false'182 assert result[1].instance_name == 'instance-2'183 assert result[1].driver_name == 'vagrant'184 assert result[1].provisioner_name == 'ansible'185 assert result[1].scenario_name == 'default'186 assert result[1].created == 'false'187 assert result[1].converged == 'false'188def test_get_instance_config(mocker, _instance):189 m = mocker.patch('molecule.util.safe_load_file')190 m.return_value = [{191 'instance': 'foo',192 }, {193 'instance': 'bar',194 }]195 x = {196 'instance': 'foo',197 }198 assert x == _instance._get_instance_config('foo')199def test_created(_instance):200 assert 'false' == _instance._created()201def test_converged(_instance):...
__init__.py
Source:__init__.py
1# -*- coding: utf-8 -*-2import os3import pytest4import testinfra5import testinfra.utils.ansible_runner6import yaml7from pathlib import Path8# https://medium.com/opsops/accessing-remote-host-at-test-discovery-stage-in-testinfra-pytest-7296235e804d9molecule_ephemeral_directory = os.environ.get('MOLECULE_EPHEMERAL_DIRECTORY')10if molecule_ephemeral_directory is None:11 raise RuntimeError(12 "[-] missing environment variable: 'MOLECULE_EPHEMERAL_DIRECTORY'"13 )14molecule_inventory_file = os.environ.get('MOLECULE_INVENTORY_FILE')15if molecule_inventory_file is None:16 raise RuntimeError(17 "[-] missing environment variable: 'MOLECULE_INVENTORY_FILE"18 )19def load_ansible_vars():20 """Load saved Ansible variables from `converge` stage."""21 ephemeral_directory = Path(molecule_ephemeral_directory)22 yaml_file = ephemeral_directory / 'ansible-vars.yml'23 ansible_vars = yaml.safe_load(yaml_file.read_bytes())24 print(f"[+] read runtime variables from '{yaml_file}'")25 return ansible_vars26ansible_vars = load_ansible_vars()27def in_roles(role, roles=None):28 """Return boolean for inclusion of role in a list of roles."""29 ansible_vars = load_ansible_vars()30 if roles is None:31 roles = ansible_vars.get('ansible_role_names', [])32 return role in roles33def skip_unless_role(role):34 """Decorator for skipping tests when related role is not involved."""35 if in_roles(role):36 return lambda func: func37 return pytest.mark.skipif(38 not in_roles(role),39 reason=f'role {role} only'40 )41def get_homedir(host=None, user=None):42 """Get user's home directory path in instance."""43 cmd = host.run(f'/usr/bin/getent passwd {user}')44 return cmd.stdout.split(':')[5]45def get_testinfra_hosts():46 """Get list of testinfra hosts."""47 testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(48 molecule_inventory_file49 ).get_hosts('all')50 print(f"[+] found testinfra_hosts: {testinfra_hosts}")51 # except RuntimeError:52 # print(f"[-] failed to get testinfra_hosts")53 # testinfra_hosts = []54 return testinfra_hosts...
conftest.py
Source:conftest.py
...48@pytest.helpers.register49def get_molecule_file(path):50 return config.molecule_file(path)51@pytest.helpers.register52def molecule_ephemeral_directory(_fixture_uuid):53 project_directory = "test-project-{}".format(_fixture_uuid)54 scenario_name = "test-instance"55 return ephemeral_directory(56 os.path.join("molecule_test", project_directory, scenario_name)...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!