Beispiel #1
0
    def test_get_register(self):
        result = Result(Status.CHANGED)

        executor = get_executor(register='test')
        executor.host = Localhost()
        executor.result = result
        executor.register_result()

        self.assertEqual(config.get_registered(Localhost(), 'test'), result)
Beispiel #2
0
class ExecuteOnHostTest(unittest.TestCase):
    """
    Tests if the output paramiko returns is parsed correctly
    """

    host = Localhost()
    result = Result(Status.SUCCESS)

    def test_execute_success(self):
        executor = self.mock_executor()
        result = executor.execute()

        self.assertEqual(result, self.result)

    def test_throw_exception_on_fail(self):
        self.result = Result(status=Status.FAIL)
        executor = self.mock_executor()

        with self.assertRaises(SingleExecutorFailedException):
            executor.execute(True)

    def mock_executor(self, **kwargs):
        # Set executor
        executor = get_executor(**kwargs)

        # Mock run_command() on executor
        run_command_mock = Mock()
        run_command_mock.return_value = self.result
        executor.run_command = run_command_mock

        return executor

    def setUp(self):
        config.hosts = [self.host]
Beispiel #3
0
    def test_localhost(self):
        """
        If localhost is passed only localhost should be in the registry
        """

        cli.add_hosts('localhost')
        self.assertEqual([Localhost()], config.hosts)
Beispiel #4
0
    def test_user_exists(self):
        execute_mock = mock.Mock()
        execute_mock.return_value = Result(status=Status.SUCCESS)

        executor = UserExecutor(host=Localhost(),
                                username=self.username,
                                password=self.password,
                                groups=self.groups,
                                ssh_keys=self.ssh_keys)
        executor.execute_executor = execute_mock
        result = executor.execute()

        execute_mock.assert_has_calls([
            mock.call(
                UserAddExecutor(username=self.username,
                                password=self.password,
                                create_home=self.create_home,
                                shell='/bin/bash',
                                groups=self.groups,
                                **executor.get_base_attributes()))
        ])

        self.assertEqual(
            result, Result(status=Status.SUCCESS, message='User is created!'))
        self.assertEqual(execute_mock.call_count, 1)
Beispiel #5
0
    def test_command(self, clone, checkout, pull):
        repository = '[email protected]:jessielaf/effe'
        version = 'develop'
        force = True
        chdir = '/test'

        executor = GitExecutor(repository=repository,
                               version=version,
                               force=force,
                               chdir=chdir,
                               host=Localhost())

        executor.execute()

        clone.called_with(repository=repository,
                          name=f'Cloning {repository}',
                          **executor.get_base_attributes())

        checkout.called_with(version=version,
                             force=force,
                             name=f'Checking out {version} for {repository}',
                             **executor.get_base_attributes())

        pull.called_with(force=force,
                         name=f'Pulling {repository}',
                         **executor.get_base_attributes())
Beispiel #6
0
def get_host_by_name(url: str) -> Host:
    """
    Gets the hosts by url or name from the general config

    Args:
        url (str): The url that matches with the host

    Returns:
        Host: host that matches with the url
    """

    if url == 'localhost' or url == '127.0.0.1':
        return Localhost()

    host = [
        host for host in config.general_config.hosts
        if host.url == url or host.name == url
    ]

    if len(host) >= 2:
        raise MoreHostsWithSameUrlException
    elif len(host) == 0:
        raise HostNotFoundException

    return host[0]
Beispiel #7
0
    def test_create_template(self):
        config.registry['test'] = 'test2'
        executor = TemplateExecutor(src='tests/unit/helpers/template.txt',
                                    dest='test')
        executor.sequence = Sequence(executors=[])
        executor.host = Localhost()

        self.assertEqual(executor.commands(),
                         'printf \'test test2 localhost\' | tee test')
Beispiel #8
0
    def test_register_result(self):
        executor = get_executor(register='test')
        result = Result(Status.CHANGED, 'test', ['test'])
        host = Localhost()

        executor.host = host
        executor.result = result

        executor.register_result()

        self.assertEqual(config.registry[repr(host)]['test'], result)
Beispiel #9
0
    def test_without_ssh(self):
        execute_mock = mock.Mock()
        execute_mock.return_value = Result(status=Status.CHANGED)

        executor = UserExecutor(host=Localhost(),
                                username=self.username,
                                password=self.password,
                                groups=self.groups)
        executor.execute_executor = execute_mock
        executor.execute()

        execute_mock.assert_has_calls(
            self.user_call(executor) + self.calls_before_ssh_keys(executor) +
            self.calls_after_ssh_keys(executor))
Beispiel #10
0
    def mock_executor(self, client_mock, exec_return, **kwargs):
        # Set executor
        executor = get_executor(**kwargs)
        executor.host = Localhost()

        # Mock commands() on executor
        commands_mock = Mock()
        commands_mock.return_value = 'value'
        executor.commands = commands_mock

        # Mock get_client on executor
        client_mock.return_value.exec_command.return_value = exec_return
        executor.get_client = client_mock

        return executor
Beispiel #11
0
    def test_sequence_run(self, sequence_mock):
        """
        Test if the sequence runs correctly when everything is given properly
        """

        config.hosts = [Localhost()]

        run_function = Mock()
        sequence_mock.return_value.run = run_function

        self.assertFalse(config.sequence)
        cli.run_sequence(os.path.join(get_helper_directory(), 'test.py'))

        run_function.assert_called_with()
        self.assertTrue(config.sequence)
Beispiel #12
0
def add_hosts(hosts: Union[str, List[str]]):
    """
    Adding the hosts based on the url

    Args:
        hosts (Union[str, List[str]]): The hosts on which crit will run
    """

    if hosts == 'all':
        config_module.hosts = config_module.general_config.hosts
    else:
        for host in hosts.split(','):
            if host == 'localhost' or host == '127.0.0.1':
                config_module.hosts.append(Localhost())
            else:
                config_module.hosts.append(get_host_by_name(host))
Beispiel #13
0
    def test_command(self, command_executor, docker_apt_executor,
                     apt_executor):
        executor = DockerInstallExecutor(host=Localhost())
        executor.execute_executor = mock.Mock()
        executor.execute()

        command_executor.assert_has_calls([
            mock.call(command='apt-get update',
                      name='Update apt-get',
                      **executor.get_base_attributes()),
            mock.call(name='Upgrade apt-get',
                      command='apt-get -y upgrade',
                      env={'DEBIAN_FRONTEND': 'noninteractive'},
                      **executor.get_base_attributes(excluded=['env'])),
            mock.call(
                name='Add docker apt-key',
                command=
                'curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -',
                **executor.get_base_attributes()),
            mock.call(
                name='Add docker repository',
                command=
                'add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable"',
                **executor.get_base_attributes()),
            mock.call(name='Add apt-cache policy for docker-ce',
                      command='apt-cache policy docker-ce',
                      **executor.get_base_attributes())
        ])

        docker_apt_executor.assert_called_with(
            name='Install docker-ce', **executor.get_base_attributes())

        apt_calls = []

        for package in executor.packages_required:
            apt_calls += [
                mock.call(package=package,
                          name='install ' + package,
                          **executor.get_base_attributes())
            ]

        apt_executor.assert_has_calls(apt_calls)
Beispiel #14
0
    def test_with_everything(self):
        execute_mock = mock.Mock()
        execute_mock.return_value = Result(status=Status.CHANGED)

        executor = UserExecutor(host=Localhost(),
                                username=self.username,
                                password=self.password,
                                groups=self.groups,
                                ssh_keys=self.ssh_keys)
        executor.execute_executor = execute_mock
        executor.execute()

        execute_mock.assert_has_calls(
            self.user_call(executor) + self.calls_before_ssh_keys(executor) + [
                mock.call(
                    CommandExecutor(
                        command=
                        f'printf \'{self.ssh_keys}\' | sudo tee /home/{self.username}/.ssh/authorized_keys > /dev/null',
                        **executor.get_base_attributes()))
            ] + self.calls_after_ssh_keys(executor))
Beispiel #15
0
    def test_run(self):
        # Host and the empty mock
        host = Localhost()
        empty_mock = Mock()

        # Mock the result
        result = Result(Status.SUCCESS)
        result.print_line = empty_mock

        # Mock the execute function
        execute = Mock()
        execute.return_value = result

        # Mock the executor
        executor = CommandExecutor('ls')
        executor.execute = execute

        # Mock thread behaviour
        join = Mock()
        start = Mock()
        executor.start = start
        executor.join = join

        sequence = Sequence(
            hosts=[host],
            executors=[
                executor
            ]
        )

        sequence.print_title = empty_mock

        sequence.run()

        execute.called_with()
        join.called_with()
        start.called_with()
Beispiel #16
0
class GetBaseAttributesTests(unittest.TestCase):
    attributes = {
        'host': Localhost(),
        'tags': ['tes'],
        'sudo': True,
        'register': 'test',
        'env': {
            'TEST': 'test'
        },
        'chdir': '/test'
    }

    def test_all_attributes(self):
        self.assertEqual(
            get_executor(**self.attributes).get_base_attributes(),
            self.attributes)

    def test_exclude_attribute(self):
        attributes = self.attributes
        del attributes['tags']

        self.assertEqual(
            get_executor(**self.attributes).get_base_attributes(['tags']),
            attributes)
Beispiel #17
0
    def test_run(self):
        config.tags = []
        host = Localhost()

        executor = get_executor()
        executor.host = host

        not_in_config_hosts = MagicMock(return_value=False)
        executor.not_in_config_hosts = not_in_config_hosts

        result = Result(status=Status.CHANGED)
        execute = MagicMock(return_value=result)
        executor.execute = execute

        register_result = Mock()
        executor.register_result = register_result

        executor.run()

        self.assertTrue(not_in_config_hosts.called)
        self.assertTrue(execute.called)

        register_result.assert_called_with()
        self.assertEqual(result, executor.result)
Beispiel #18
0
from crit.config import Localhost
from crit.executors.docker import DockerInstallExecutor
from crit.executors.utils import CommandExecutor, TemplateExecutor
from crit.sequences import Sequence

sequence = Sequence(
    hosts=[Localhost()],
    executors=[
        DockerInstallExecutor(),
        CommandExecutor(command='usermod -a -G docker vagrant', sudo=True),
        TemplateExecutor(src='templates/docker_daemon.json', dest='/etc/docker/daemon.json', extra_vars={
            'docker_registry': 'localhost:5000'
        }, tags=['daemon_docker'], sudo=True)
    ]
)
Beispiel #19
0
    def test_localhost(self):
        config.hosts = []
        executor = get_executor()
        executor.host = Localhost()

        self.assertEqual(executor.not_in_config_hosts(), None)
Beispiel #20
0
from crit.config import Localhost
from crit.executors.docker import DockerBuildExecutor, DockerTagExecutor, DockerPushExecutor, DockerPullExecutor
from crit.executors.git import GitExecutor
from crit.sequences import Sequence

repo = 'effe'
registry_url = '192.168.200.101:5000'
registry_url_image = f'192.168.200.101:5000/{repo}'
directory = f'/vagrant/projects/{repo}'

executors = [
    GitExecutor(repository=f'[email protected]:jessielaf/{repo}',
                chdir=directory,
                force=True,
                hosts=[Localhost()]),
    DockerBuildExecutor(name='Build docker image',
                        tag=repo,
                        chdir=directory,
                        sudo=True,
                        hosts=[Localhost()]),
    DockerTagExecutor(name='Tag docker image',
                      tag=repo,
                      registry_url=registry_url_image,
                      sudo=True,
                      hosts=[Localhost()]),
    DockerPushExecutor(name='Push docker image to registry',
                       registry_url=registry_url_image,
                       sudo=True,
                       hosts=[Localhost()]),
    DockerPullExecutor(name='Pulls the image from the private repository',
                       registry_url=registry_url,
Beispiel #21
0
 def setUp(self):
     config.hosts = [Localhost()]
     config.registry = {}