def jsontest_function(self, test_name, test_data):
            if ('require_platform' in test_data
                    and PLATFORM_NAME not in test_data['require_platform']):
                return

            # 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))
                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

                op_is_idempotent = getattr(op._pyinfra_op, 'is_idempotent',
                                           True)
                test_second_output_commands = 'second_output_commands' in test_data

                if op_is_idempotent or test_second_output_commands:
                    second_output_commands = unroll_generators(
                        op._pyinfra_op(*test_data.get('args', []), **kwargs))

                    if op_is_idempotent:
                        if test_data.get('idempotent', True):
                            if second_output_commands:
                                raise Exception((
                                    'Operation not idempotent, second output commands: {0}'
                                ).format(second_output_commands))
                        else:
                            warnings.warn(
                                'Operation is not expected to be idempotent: {0}'
                                .format(test_name, ))

            commands = parse_commands(output_commands)
            assert_commands(commands, test_data['commands'])

            if test_second_output_commands:
                assert_commands(
                    parse_commands(second_output_commands),
                    test_data['second_output_commands'],
                )

            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,
                        ))
示例#2
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,
                        ))
示例#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', {}))
            pseudo_host.set(host)

            allowed_exception = test_data.get('exception')

            with patch_files(test_data.get('files', []),
                             test_data.get('directories', [])):
                try:
                    output_commands = unroll_generators(
                        op._pyinfra_op(pseudo_state, pseudo_host,
                                       *test_data.get('args', []),
                                       **test_data.get('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

                        self.assertEqual(e.args[0],
                                         allowed_exception['message'])
                        return

                    raise

            commands = []

            for command in output_commands:
                if isinstance(command, six.string_types):
                    commands.append(command.strip())

                elif isinstance(command, dict):
                    command['command'] = command['command'].strip()
                    commands.append(command)

                elif isinstance(command, tuple):
                    if command[0] == '__func__':
                        commands.append([
                            command[0],
                            list(command[1]),
                            command[2],
                        ])
                    elif isinstance(command[0], FunctionType):
                        commands.append([
                            command[0].__name__,
                            list(command[1]),
                            command[2],
                        ])
                    else:
                        if hasattr(command[0], 'read'):
                            command[0].seek(0)
                            data = command[0].read()
                        else:
                            data = command[0]

                        commands.append([data, command[1]])

                else:
                    commands.append(command)

            try:
                self.assertEqual(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