def parse_commands(commands):
    json_commands = []

    for command in commands:
        if isinstance(command,
                      six.string_types):  # matches pyinfra/api/operation.py
            command = StringCommand(command.strip())

        if isinstance(command, StringCommand):
            json_command = get_command_string(command)

        elif isinstance(command, dict):
            command['command'] = get_command_string(command['command']).strip()
            json_command = command

        elif isinstance(command, FunctionCommand):
            func_name = (command.function if command.function == '__func__'
                         else command.function.__name__)
            json_command = [
                func_name,
                list(command.args),
                command.kwargs,
            ]

        elif isinstance(command, FileUploadCommand):
            if hasattr(command.src, 'read'):
                command.src.seek(0)
                data = command.src.read()
            else:
                data = command.src
            json_command = ['upload', data, command.dest]

        elif isinstance(command, FileDownloadCommand):
            json_command = ['download', command.src, command.dest]

        else:
            raise Exception('{0} is not a valid command!'.format(command))

        if command.executor_kwargs:
            command.executor_kwargs['command'] = json_command
            json_command = command.executor_kwargs

        json_commands.append(json_command)
    return json_commands
Exemple #2
0
def parse_commands(commands):
    json_commands = []

    for command in commands:
        if isinstance(command, str):  # matches pyinfra/api/operation.py
            command = StringCommand(command.strip())

        if isinstance(command, StringCommand):
            json_command = get_command_string(command)

        elif isinstance(command, dict):
            command["command"] = get_command_string(command["command"]).strip()
            json_command = command

        elif isinstance(command, FunctionCommand):
            func_name = (command.function if command.function == "__func__"
                         else command.function.__name__)
            json_command = [
                func_name,
                list(command.args),
                command.kwargs,
            ]

        elif isinstance(command, FileUploadCommand):
            if hasattr(command.src, "read"):
                command.src.seek(0)
                data = command.src.read()
            else:
                data = str(command.src)
            json_command = ["upload", data, str(command.dest)]

        elif isinstance(command, FileDownloadCommand):
            json_command = ["download", str(command.src), str(command.dest)]

        else:
            raise Exception("{0} is not a valid command!".format(command))

        if command.executor_kwargs:
            command.executor_kwargs["command"] = json_command
            json_command = command.executor_kwargs

        json_commands.append(json_command)
    return json_commands
Exemple #3
0
        def jsontest_function(self, test_name, test_data):
            # Create a host with this tests facts and attach to pseudo host
            host = create_host(facts=test_data.get('facts', {}))

            allowed_exception = test_data.get('exception')

            kwargs = test_data.get('kwargs', {})
            kwargs['state'] = self.state
            kwargs['host'] = host

            with patch_files(test_data.get('files', []),
                             test_data.get('directories', [])):
                try:
                    output_commands = unroll_generators(
                        op._pyinfra_op(*test_data.get('args', []), **
                                       kwargs)) or []
                except Exception as e:
                    if allowed_exception:
                        allowed_exception_names = allowed_exception.get(
                            'names')
                        if not allowed_exception_names:
                            allowed_exception_names = [
                                allowed_exception['name']
                            ]

                        if e.__class__.__name__ not in allowed_exception_names:
                            print('Wrong execption raised!')
                            raise

                        assert e.args[0] == allowed_exception['message']
                        return

                    raise

            commands = []

            for command in output_commands:
                if isinstance(
                        command,
                        six.string_types):  # matches pyinfra/api/operation.py
                    command = StringCommand(command.strip())

                if isinstance(command, StringCommand):
                    json_command = get_command_string(command)

                elif isinstance(command, dict):
                    command['command'] = get_command_string(
                        command['command']).strip()
                    json_command = command

                elif isinstance(command, FunctionCommand):
                    func_name = (command.function if command.function
                                 == '__func__' else command.function.__name__)
                    json_command = [
                        func_name,
                        list(command.args),
                        command.kwargs,
                    ]

                elif isinstance(command, FileUploadCommand):
                    if hasattr(command.src, 'read'):
                        command.src.seek(0)
                        data = command.src.read()
                    else:
                        data = command.src
                    json_command = ['upload', data, command.dest]

                elif isinstance(command, FileDownloadCommand):
                    json_command = ['download', command.src, command.dest]

                else:
                    raise Exception(
                        '{0} is not a valid command!'.format(command))

                if command.executor_kwargs:
                    command.executor_kwargs['command'] = json_command
                    json_command = command.executor_kwargs

                commands.append(json_command)

            try:
                assert commands == test_data['commands']
            except AssertionError as e:
                print()
                print('--> COMMANDS OUTPUT:')
                print(json.dumps(commands, indent=4, default=json_encode))

                print('--> TEST WANTS:')
                print(
                    json.dumps(
                        test_data['commands'],
                        indent=4,
                        default=json_encode,
                    ))

                raise e

            noop_description = test_data.get('noop_description')
            if len(commands) == 0 or noop_description:
                if noop_description is not None:
                    assert host.noop_description == noop_description
                else:
                    assert host.noop_description is not None, 'no noop description was set'
                    warnings.warn(
                        'No noop_description set for test: {0} (got "{1}")'.
                        format(
                            test_name,
                            host.noop_description,
                        ))