How to use the testinfra.modules.base.InstanceModule function in testinfra

To help you get started, we’ve selected a few testinfra examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github philpep / testinfra / testinfra / modules / puppet.py View on Github external
current = None
    for line in data.splitlines():
        if not current:
            current = line.split("'")[1]
            state[current] = {}
        elif current and line == "}":
            current = None
        elif current:
            key, value = line.split(' => ')
            key = key.strip()
            value = value.split("'")[1]
            state[current][key] = value
    return state


class PuppetResource(InstanceModule):
    """Get puppet resources

    Run ``puppet resource --types`` to get a list of available types.

    >>> host.puppet_resource("user", "www-data")
    {
        'www-data': {
            'ensure': 'present',
            'comment': 'www-data',
            'gid': '33',
            'home': '/var/www',
            'shell': '/usr/sbin/nologin',
            'uid': '33',
        },
    }
    """
github philpep / testinfra / testinfra / modules / environment.py View on Github external
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import unicode_literals

from testinfra.modules.base import InstanceModule


class Environment(InstanceModule):
    """Get Environment variables

    Example:

     >>> host.environment()
    {
        "EDITOR": "vim",
        "SHELL": "/bin/bash",
        [...]
    }
    """

    def __call__(self):
        ret_val = dict(
            i.split('=', 1) for i in self.check_output('env -0').split(
                '\x00') if i
github philpep / testinfra / testinfra / modules / sudo.py View on Github external
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import
from __future__ import unicode_literals

import contextlib

from testinfra.modules.base import InstanceModule


class Sudo(InstanceModule):
    """Sudo module allow to run certain portion of code under another user.

    It is used as a context manager and can be nested.

    >>> Command.check_output("whoami")
    'phil'
    >>> with host.sudo():
    ...     host.check_output("whoami")
    ...     with host.sudo("www-data"):
    ...         host.check_output("whoami")
    ...
    'root'
    'www-data'

    """
    @contextlib.contextmanager
github philpep / testinfra / testinfra / modules / pip.py View on Github external
from __future__ import unicode_literals

import json
import re

from testinfra.modules.base import InstanceModule


def _re_match(line, regexp):
    match = regexp.match(line)
    if match is None:
        raise RuntimeError('could not parse {0}'.format(line))
    return match.groups()


class PipPackage(InstanceModule):
    """Test pip packages status and version"""

    def get_packages(self, pip_path="pip"):
        """Get all installed packages and versions returned by `pip list`:

        >>> host.pip_package.get_packages(pip_path='~/venv/website/bin/pip')
        {'Django': {'version': '1.10.2'},
         'mywebsite': {'version': '1.0a3', 'path': '/srv/website'},
         'psycopg2': {'version': '2.6.2'}}
        """
        out = self.run_expect(
            [0, 2], '{0} list --no-index --format=json'.format(pip_path))
        pkgs = {}
        if out.rc == 0:
            for pkg in json.loads(out.stdout):
                # XXX: --output=json does not return install path
github philpep / testinfra / testinfra / modules / base.py View on Github external
def get_module(cls, _host):
        klass = super(InstanceModule, cls).get_module(_host)
        return klass()
github philpep / testinfra / testinfra / modules / iptables.py View on Github external
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import unicode_literals

from testinfra.modules.base import InstanceModule


class Iptables(InstanceModule):
    """Test iptables rule exists"""

    def rules(self, table='filter', chain=None, version=4):
        """Returns list of iptables rules

           Based on ouput of `iptables -t TABLE -S CHAIN` command

             optionally takes takes the following arguments:
               - table: defaults to `filter`
               - chain: defaults to all chains
               - version: default 4 (iptables), optionally 6 (ip6tables)

        >>> host.iptables.rules()
        [
            '-P INPUT ACCEPT',
            '-P FORWARD ACCEPT',
github philpep / testinfra / testinfra / modules / command.py View on Github external
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import unicode_literals

from testinfra.modules.base import InstanceModule


class Command(InstanceModule):

    def __call__(self, command, *args, **kwargs):
        return self.run(command, *args, **kwargs)

    def exists(self, command):
        return self._host.exists(command)

    def __repr__(self):
        return ""
github philpep / testinfra / testinfra / modules / ansible.py View on Github external
"Unexpected error: {}".format(pprint.pformat(result)))


def need_ansible(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        # pylint: disable=protected-access
        if not self._host.backend.HAS_RUN_ANSIBLE:
            raise RuntimeError((
                "Ansible module is only available with ansible "
                "connection backend"))
        return func(self, *args, **kwargs)
    return wrapper


class Ansible(InstanceModule):
    """Run Ansible module functions

    This module is only available with the :ref:`ansible connection
    backend` connection backend.

    `Check mode
    `_ is
    enabled by default, you can disable it with `check=False`.

    `Become
    `_ is
    `False` by default. You can enable it with `become=True`.

    >>> host.ansible("apt", "name=nginx state=present")["changed"]
    False
    >>> host.ansible("apt", "name=nginx state=present", become=True)["changed"]
github philpep / testinfra / testinfra / modules / sysctl.py View on Github external
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import unicode_literals

from testinfra.modules.base import InstanceModule
from testinfra.utils import cached_property


class Sysctl(InstanceModule):
    """Test kernel parameters

    >>> host.sysctl("kernel.osrelease")
    "3.16.0-4-amd64"
    >>> host.sysctl("vm.dirty_ratio")
    20
    """
    @cached_property
    def _sysctl_command(self):
        return self.find_command('sysctl')

    def __call__(self, name):
        value = self.check_output("%s -n %s", self._sysctl_command, name)
        try:
            return int(value)
        except ValueError:
github philpep / testinfra / testinfra / modules / salt.py View on Github external
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import unicode_literals


import json

import six

from testinfra.modules.base import InstanceModule


class Salt(InstanceModule):
    """Run salt module functions


    >>> host.salt("pkg.version", "nginx")
    '1.6.2-5'
    >>> host.salt("pkg.version", ["nginx", "php5-fpm"])
    {'nginx': '1.6.2-5', 'php5-fpm': '5.6.7+dfsg-1'}
    >>> host.salt("grains.item", ["osarch", "mem_total", "num_cpus"])
    {'osarch': 'amd64', 'num_cpus': 4, 'mem_total': 15520}

    Run ``salt-call sys.doc`` to get a complete list of functions
    """

    def __call__(self, function, args=None, local=False, config=None):
        args = args or []
        if isinstance(args, six.string_types):