def test_ansible_no_host(): with tempfile.NamedTemporaryFile() as f: f.write(b'host\n') f.flush() assert AnsibleRunner(f.name).get_hosts() == ['host'] hosts = testinfra.get_hosts( [None], connection='ansible', ansible_inventory=f.name) assert [h.backend.get_pytest_id() for h in hosts] == ['ansible://host'] with tempfile.NamedTemporaryFile() as f: # empty or no inventory should not return any hosts except for # localhost assert AnsibleRunner(f.name).get_hosts() == [] assert AnsibleRunner(f.name).get_hosts('local*') == [] assert AnsibleRunner(f.name).get_hosts('localhost') == ['localhost']
def test_ansible_get_host(hostname, kwargs, inventory, expected): with tempfile.NamedTemporaryFile() as f: f.write(inventory + b'\n') f.flush() backend = AnsibleRunner(f.name).get_host(hostname, **kwargs).backend for attr, value in expected.items(): assert operator.attrgetter(attr)(backend) == value
def test_ansible_unhandled_connection(): with tempfile.NamedTemporaryFile() as f: f.write(b'host ansible_connection=winrm\n') f.flush() with pytest.raises(RuntimeError) as excinfo: AnsibleRunner(f.name).get_host('host') assert str(excinfo.value) == 'unhandled ansible_connection winrm'
def test_ansible_ssh_command(inventory, expected): with tempfile.NamedTemporaryFile() as f: f.write(inventory + b'\n') f.flush() backend = AnsibleRunner(f.name).get_host('host').backend cmd, cmd_args = backend._build_ssh_command('true') command = backend.quote(' '.join(cmd), *cmd_args) assert command == expected
def test_ansible_no_host(): with tempfile.NamedTemporaryFile() as f: f.write(b'host\n') f.flush() assert AnsibleRunner(f.name).get_hosts() == ['host'] hosts = testinfra.get_hosts([None], connection='ansible', ansible_inventory=f.name) assert [h.backend.get_pytest_id() for h in hosts] == ['ansible://host'] with tempfile.NamedTemporaryFile() as f: # empty or no inventory should not return any hosts except for # localhost nohost = ('No inventory was parsed (missing file ?), ' 'only implicit localhost is available') with pytest.raises(RuntimeError) as exc: assert AnsibleRunner(f.name).get_hosts() == [] assert str(exc.value) == nohost with pytest.raises(RuntimeError) as exc: assert AnsibleRunner(f.name).get_hosts('local*') == [] assert str(exc.value) == nohost assert AnsibleRunner(f.name).get_hosts('localhost') == ['localhost']
def notest_ssh_service(Ansible, Service, TestinfraBackend): host = TestinfraBackend.get_hostname() # svc_name = Ansible.get_variables()['basesys_ssh_service'] var = AnsibleRunner('.molecule/ansible_inventory').get_variables(host) print("VAR" + str(var)) svc_name = var['basesys_ssh_service'] assert svc_name print("SVSC " + svc_name) svc_name = 'sshd' assert svc_name svc = Service(svc_name) assert svc.is_running assert svc.is_enabled
def test_ansible_config(): # test testinfra use ANSIBLE_CONFIG tmp = tempfile.NamedTemporaryFile with tmp(suffix=".cfg") as cfg, tmp() as inventory: cfg.write((b"[defaults]\n" b"inventory=" + inventory.name.encode() + b"\n")) cfg.flush() inventory.write(b"h\n") inventory.flush() old = os.environ.get("ANSIBLE_CONFIG") os.environ["ANSIBLE_CONFIG"] = cfg.name try: assert AnsibleRunner(None).get_hosts("all") == ["h"] finally: if old is not None: os.environ["ANSIBLE_CONFIG"] = old else: del os.environ["ANSIBLE_CONFIG"]
def test_ansible_config(): # test testinfra use ANSIBLE_CONFIG tmp = tempfile.NamedTemporaryFile with tmp(suffix='.cfg') as cfg, tmp() as inventory: cfg.write((b'[defaults]\n' b'inventory=' + inventory.name.encode() + b'\n')) cfg.flush() inventory.write(b'h\n') inventory.flush() old = os.environ.get('ANSIBLE_CONFIG') os.environ['ANSIBLE_CONFIG'] = cfg.name try: assert AnsibleRunner(None).get_hosts('all') == ['h'] finally: if old is not None: os.environ['ANSIBLE_CONFIG'] = old else: del os.environ['ANSIBLE_CONFIG']
def test_host_topology(host): agent_hosts = AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('agent_linux_vm') for hostname in agent_hosts: def wait_for_components(): url = "http://localhost:7070/api/topic/sts_topo_process_agents?offset=0&limit=1000" data = host.check_output("curl \"%s\"" % url) json_data = json.loads(data) with open("./topic-topo-process-agents-topology-{}.json".format(hostname), 'w') as f: json.dump(json_data, f, indent=4) # assert that we get the host component host_match = re.compile("urn:host:/{}".format(hostname)) host_component = _find_component( json_data=json_data, type_name="host", external_id_assert_fn=lambda v: host_match.findall(v)) assert json.loads(host_component["data"])["host"] == hostname # assert that we get the disk integration host component url = "http://localhost:7070/api/topic/sts_topo_disk_agents?offset=0&limit=100" data = host.check_output("curl \"%s\"" % url) json_data = json.loads(data) with open("./topic-topo-disk-agents-topology-{}.json".format(hostname), 'w') as f: json.dump(json_data, f, indent=4) # assert that we get the host component with the list of devices host_match = re.compile("urn:host:/{}".format(hostname)) host_component = _find_component( json_data=json_data, type_name="host", external_id_assert_fn=lambda v: host_match.findall(v)) host_data = json.loads(host_component["data"]) assert host_data["host"] == hostname assert "devices" in host_data and isinstance(host_data["devices"], list) util.wait_until(wait_for_components, 120, 3)
from testinfra.utils.ansible_runner import AnsibleRunner runner = AnsibleRunner('.molecule/ansible_inventory') runner.options.connection = 'docker' testinfra_hosts = runner.get_hosts('yum_madison') def test_yum_madison(TestinfraBackend, Command): target = TestinfraBackend.get_hostname() expected_version = Command( "yum list | grep sudo | head -n 1 | awk '{ print $2'}") p = runner.run(target, 'yum_madison', 'name=sudo', check=False) assert p['versions'][0]['name'] == 'sudo' assert p['versions'][0]['version'] == expected_version.stdout.strip()
def ansible_runner(self): return AnsibleRunner.get_runner(self.ansible_inventory)
def get_hosts(cls, host, **kwargs): inventory = kwargs.get('ansible_inventory') return AnsibleRunner.get_runner(inventory).get_hosts(host)
def get_vars(host): return AnsibleRunner(f.name).get_variables(host)
""" Test suite for the Molecule 'default' scenario. """ from os import environ from testinfra.utils.ansible_runner import AnsibleRunner import pytest # Create the `host` fixture parametrized over all configured test platforms. # Each `host` is a Testinfra Host instance. The inventory is created by the # Molecule framework, so this test suite must be run via *e.g.* `molecule test` # and not `pytest`. runner = AnsibleRunner(environ["MOLECULE_INVENTORY_FILE"]) testinfra_hosts = runner.get_hosts("all") @pytest.mark.parametrize("cmd", ("python3", "pip3", "virtualenv")) def test_commands(host, cmd): """ Test for installed Python commands. """ # For now this is just a basic smoke test. assert host.command(f"{cmd:s} --version").rc == 0 return
"""Role tests default variables installation.""" import os import pytest from testinfra.utils.ansible_runner import AnsibleRunner TESTINFRA_HOSTS = AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_hosts_file(host): """ Tests general host is available with root """ hosts_file = host.file('/etc/hosts') assert hosts_file.exists assert hosts_file.user == 'root' assert hosts_file.group == 'root' def test_traefik_processes(host): """ Test traefik processes """ assert len(host.process.filter(user='******', comm='traefik')) == 1 def test_traefik_services(host): """ Test traefik services
import json import os import util from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('trace-java-demo') def test_container_metrics(host): url = "http://localhost:7070/api/topic/sts_multi_metrics?limit=1000" def wait_for_metrics(): data = host.check_output("curl \"%s\"" % url) json_data = json.loads(data) with open("./topic-sts-multi-metrics.json", 'w') as f: json.dump(json_data, f, indent=4) def get_keys(m_host): return next( set(message["message"]["MultiMetric"]["values"].keys()) for message in json_data["messages"] if message["message"]["MultiMetric"]["name"] == "containerMetrics" and message["message"]["MultiMetric"]["host"] == m_host) expected = { "netRcvdPs", "memCache", "totalPct", "wbps", "systemPct", "rbps", "memRss", "netSentBps", "netSentPs", "netRcvdBps", "userPct" } assert get_keys("trace-java-demo") == expected
def get_hosts(cls, host, **kwargs): from testinfra.utils.ansible_runner import AnsibleRunner return AnsibleRunner(kwargs.get("ansible_inventory")).get_hosts(host)
import os from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('agent_linux_vm') def test_stackstate_agent_is_installed(host, ansible_var): agent = host.package("stackstate-agent") print(agent) assert agent.is_installed expected_major_version = ansible_var("major_version") assert agent.version.startswith(expected_major_version + ".") def test_stackstate_agent_status_output_no_datadog(host): status_cmd = host.run("sudo -u stackstate-agent -- stackstate-agent status") print(status_cmd) # assert that the status command ran successfully and that datadog is not contained in the output assert status_cmd.rc == 0 assert "datadog" not in status_cmd.stdout assert "Datadog" not in status_cmd.stdout help_cmd = host.run("sudo -u stackstate-agent -- stackstate-agent --help") print(help_cmd) # assert that the help command ran successfully and that datadog is not contained in the output assert help_cmd.rc == 0 assert "datadog" not in help_cmd.stdout assert "Datadog" not in help_cmd.stdout def test_stackstate_agent_running_and_enabled(host):
def get_hosts(spec): return AnsibleRunner(f.name).get_hosts(spec)
def get_hosts(cls, host, **kwargs): inventory = kwargs.get('ansible_inventory') return AnsibleRunner.get_runner(inventory).get_hosts(host or "all")
import json import os import re from testinfra.utils.ansible_runner import AnsibleRunner import util testinfra_hosts = AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('agent-integrations') def _get_key_value(tag_list): for key, value in (pair.split(':', 1) for pair in tag_list): yield key, value def _component_data(json_data, type_name, external_id_assert_fn, tags_assert_fn): for message in json_data["messages"]: p = message["message"]["TopologyElement"]["payload"] if "TopologyComponent" in p and \ p["TopologyComponent"]["typeName"] == type_name and \ external_id_assert_fn(p["TopologyComponent"]["externalId"]): data = json.loads(p["TopologyComponent"]["data"]) if tags_assert_fn(dict(_get_key_value(data["tags"]))): return data return None def test_nagios_mysql(host):
from __future__ import unicode_literals from testinfra.utils.ansible_runner import AnsibleRunner import os import pytest import logging import testinfra.utils.ansible_runner import collections logging.basicConfig(level=logging.DEBUG) # # DEFAULT_HOST = 'all' VAR_FILE = "../../vars/main.yml" TESTINFRA_HOSTS = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') inventory = os.environ['MOLECULE_INVENTORY_FILE'] runner = AnsibleRunner(inventory) # runner.get_hosts(DEFAULT_HOST) @pytest.fixture() def ansible_os_family(Ansible): return Ansible("setup")["ansible_facts"]["ansible_os_family"] @pytest.fixture def ansible_variables(host, ansible_os_family): variables = runner.run(TESTINFRA_HOSTS, 'include_vars', VAR_FILE) return variables['ansible_facts'] @pytest.fixture
from testinfra.utils.ansible_runner import AnsibleRunner testinfra_ansible = AnsibleRunner('.molecule/ansible_inventory') testinfra_hosts = testinfra_ansible.get_hosts('test') def test_command(Command): assert Command('docker ps | grep docker_registry').rc == 0
def ansible_runner(self): return AnsibleRunner(self.ansible_inventory)
""" Role tests """ import os from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_packages(host): """ Ensure git package is installed """ assert host.package('git').is_installed
def get_hosts(cls, host, **kwargs): return AnsibleRunner(kwargs.get("ansible_inventory")).get_hosts(host)
def ansible_runner(self): if self._ansible_runner is None: from testinfra.utils.ansible_runner import AnsibleRunner self._ansible_runner = AnsibleRunner(self.ansible_inventory) return self._ansible_runner
import os import re import util from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner( os.environ["MOLECULE_INVENTORY_FILE"]).get_hosts("agent_win_vm") def test_stackstate_agent_is_installed(host, ansible_var): pkg = "StackState Agent" # res = host.ansible("win_shell", "Get-Package \"{}\"".format(pkg), check=False) res = host.ansible( "win_shell", " Get-WmiObject -Class Win32_Product | where name -eq \"{}\" | select Name, Version " .format(pkg), check=False) print(res) expected_major_version = ansible_var("major_version") assert re.search(".*{} {}\\.".format(pkg, expected_major_version), res["stdout"], re.I) def test_stackstate_agent_running_and_enabled(host): def check(name, deps, depended_by): service = host.ansible("win_service", "name={}".format(name)) print(service) assert service["exists"] assert not service["changed"] assert service["state"] == "running" assert service["dependencies"] == deps
#!/user/bin/env python from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner('.molecule/ansible_inventory').get_hosts('all') def test_directories(host): dirs = [ "/etc/alertmanager", "/etc/alertmanager/templates", "/var/lib/alertmanager" ] files = [ "/usr/local/bin/alertmanager", "/usr/local/bin/amtool", "/etc/alertmanager/alertmanager.yml", "/etc/systemd/system/alertmanager.service" ] for directory in dirs: d = host.file(directory) assert d.is_directory assert d.exists for file in files: f = host.file(file) assert f.exists assert f.is_file def test_service(host): s = host.service("alertmanager") assert s.is_enabled
import os import pytest from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = ["ansible://borgbackup_servers"] def test_client_parent_dir(host): parentdir = host.file("/var/backup/repos") assert parentdir.is_directory @pytest.mark.parametrize('client', AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts( 'all:!borgbackup_servers')) def test_client_dir(host, client): clientdir = host.file("/var/backup/repos/%s" % client) assert clientdir.is_directory @pytest.mark.parametrize('client', AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts( 'all:!borgbackup_servers')) def test_ssh_client_conf(host, client): sshconf = host.file("/var/backup/.ssh/authorized_keys") assert sshconf.is_file assert sshconf.contains("%s;borg serve" % client)
from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = \ AnsibleRunner('.molecule/ansible_inventory').get_hosts('test') def test_command(Command): assert Command('xclip -version').rc == 0
import os import util import pytest from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts( 'kubernetes-cluster-agent') kubeconfig_env = "KUBECONFIG=/home/ubuntu/deployment/aws-eks/tf-cluster/kubeconfig " @pytest.mark.first def test_receiver_healthy(host): def assert_healthy(): c = "curl -s -o /dev/null -w \"%{http_code}\" http://localhost:7077/health" assert host.check_output(c) == "200" util.wait_until(assert_healthy, 30, 5) @pytest.mark.second def test_node_agent_healthy(host, ansible_var): namespace = ansible_var("namespace") def assert_healthy(): c = kubeconfig_env + "kubectl wait --for=condition=ready --timeout=1s -l app=stackstate-agent pod --namespace={}".format( namespace) assert host.run(c).rc == 0 util.wait_until(assert_healthy, 30, 5)