public inbox for passt-dev@passt.top
 help / color / mirror / code / Atom feed
blob e2c9b1eb3d39a47127cc71430e80bde71ea7a582 6836 bytes (raw)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
 
#! /usr/bin/python3

# SPDX-License-Identifier: GPL-2.0-or-later
#
# Copyright Red Hat
# Author: David Gibson <david@gibson.dropbear.id.au>

"""
Implementation of the Avocado resolver and runner for classless tests.
"""

import importlib
import multiprocessing
import os.path
import re
import sys
import time
import traceback


from avocado.core.extension_manager import PluginPriority
from avocado.core.test import Test, TestID
from avocado.core.nrunner.app import BaseRunnerApp
from avocado.core.nrunner.runnable import Runnable
from avocado.core.nrunner.runner import (
    RUNNER_RUN_CHECK_INTERVAL,
    RUNNER_RUN_STATUS_INTERVAL,
    BaseRunner,
)
from avocado.core.plugin_interfaces import Resolver
from avocado.core.resolver import (
    ReferenceResolution,
    ReferenceResolutionResult,
    check_file
)
from avocado.core.utils import messages

from .manifest import manifest

SHBANG = b'#! /usr/bin/env avocado-runner-avocado-classless'


def load_mod(path):
    """Load a module containing classless tests"""
    modname = os.path.basename(path)[:-3]
    moddir = os.path.abspath(os.path.dirname(path))

    try:
        sys.path.insert(0, moddir)
        return importlib.import_module(modname)
    finally:
        if moddir in sys.path:
            sys.path.remove(moddir)


class ClasslessResolver(Resolver):
    """Resolver plugin for classless tests"""
    # pylint: disable=R0903

    name = "avocado-classless"
    description = "Resolver for classless tests (not jUnit style)"
    priority = PluginPriority.HIGH

    def resolve(self, reference):
        if ':' in reference:
            path, pattern = reference.rsplit(':', 1)
        else:
            path, pattern = reference, ''

        # First check it looks like a Python file
        filecheck = check_file(path, reference)
        if filecheck is not True:
            return filecheck

        # Then check it looks like an avocado-classless file
        with open(path, 'rb') as testfile:
            shbang = testfile.readline()
        if shbang.strip() != SHBANG:
            return ReferenceResolution(
                reference,
                ReferenceResolutionResult.NOTFOUND,
                info=f'{path} does not have first line "{SHBANG}" line',
            )

        mod = load_mod(path)
        mfest = manifest(mod)

        pattern = re.compile(pattern)
        runnables = []
        for name in mfest.keys():
            if pattern.search(name):
                runnables.append(Runnable("avocado-classless",
                                          f"{path}:{name}"))

        return ReferenceResolution(
            reference,
            ReferenceResolutionResult.SUCCESS,
            runnables,
        )


def run_classless(runnable, testinfo, queue):
    """Invoked within isolating process, run classless tests"""
    try:
        class ClasslessTest(Test):
            """Shim class for classless tests"""
            def test(self):
                """Execute classless test"""
                testinfo.run_test()

        result_dir = runnable.output_dir
        instance = ClasslessTest(
            name=TestID(0, runnable.uri),
            config=runnable.config,
            base_logdir=result_dir,
        )

        messages.start_logging(runnable.config, queue)

        instance.run_avocado()

        state = instance.get_state()
        fail_reason = state.get("fail_reason")
        queue.put(
            messages.FinishedMessage.get(
                state["status"].lower(),
                fail_reason=fail_reason,
                fail_class=state.get("fail_class"),
                traceback=state.get("traceback"),
            )
        )
    except Exception as exc:  # pylint: disable=W0718
        queue.put(messages.StderrMessage.get(traceback.format_exc()))
        queue.put(
            messages.FinishedMessage.get(
                "error",
                fail_reason=str(exc),
                fail_class=exc.__class__.__name__,
                traceback=traceback.format_exc(),
            )
        )


class ClasslessRunner(BaseRunner):
    """Runner for classless tests

    When creating the Runnable, use the following attributes:

     * kind: should be 'avocado-classless';

     * uri: path to a test file, then ':' then a function name within that file

     * args: not used;

     * kwargs: not used;

    Example:

       runnable = Runnable(kind='avocado-classless',
                           uri='example.py:test_example')
    """

    name = "avocado-classless"
    description = "Runner for classless tests (not jUnit style)"

    CONFIGURATION_USED = [
        "core.show",
        "job.run.store_logging_stream",
    ]

    def run(self, runnable):
        yield messages.StartedMessage.get()

        try:
            path, testname = runnable.uri.rsplit(':', 1)
            mod = load_mod(path)
            testinfo = manifest(mod)[testname]

            queue = multiprocessing.SimpleQueue()
            process = multiprocessing.Process(
                target=run_classless, args=(runnable, testinfo, queue)
            )
            process.start()

            time_started = time.monotonic()
            next_status_time = None
            while True:
                time.sleep(RUNNER_RUN_CHECK_INTERVAL)
                now = time.monotonic()
                if queue.empty():
                    if (
                        next_status_time is None
                        or now > next_status_time
                    ):
                        next_status_time = now + RUNNER_RUN_STATUS_INTERVAL
                        yield messages.RunningMessage.get()
                    if (now - time_started) > testinfo.timeout():
                        process.terminate()
                        yield messages.FinishedMessage.get("interrupted",
                                                           "timeout")
                        break
                else:
                    message = queue.get()
                    yield message
                    if message.get("status") == "finished":
                        break
        except Exception as exc:  # pylint: disable=W0718
            yield messages.StderrMessage.get(traceback.format_exc())
            yield messages.FinishedMessage.get(
                "error",
                fail_reason=str(exc),
                fail_class=exc.__class__.__name__,
                traceback=traceback.format_exc(),
            )


class RunnerApp(BaseRunnerApp):
    """Runner app for classless tests"""
    PROG_NAME = "avocado-runner-avocado-classless"
    PROG_DESCRIPTION = "nrunner application for classless tests"
    RUNNABLE_KINDS_CAPABLE = ["avocado-classless"]


def main():
    """Run some avocado-classless tests"""
    app = RunnerApp(print)
    app.run()


if __name__ == "__main__":
    main()

debug log:

solving e2c9b1eb ...
found e2c9b1eb in https://archives.passt.top/passt-dev/20230627025429.2209702-12-david@gibson.dropbear.id.au/
found 442642d5 in https://archives.passt.top/passt-dev/20230627025429.2209702-7-david@gibson.dropbear.id.au/
found 48b89ce9 in https://archives.passt.top/passt-dev/20230627025429.2209702-5-david@gibson.dropbear.id.au/

applying [1/3] https://archives.passt.top/passt-dev/20230627025429.2209702-5-david@gibson.dropbear.id.au/
diff --git a/test/avocado_classless/avocado_classless/plugin.py b/test/avocado_classless/avocado_classless/plugin.py
new file mode 100644
index 00000000..48b89ce9


applying [2/3] https://archives.passt.top/passt-dev/20230627025429.2209702-7-david@gibson.dropbear.id.au/
diff --git a/test/avocado_classless/avocado_classless/plugin.py b/test/avocado_classless/avocado_classless/plugin.py
index 48b89ce9..442642d5 100644


applying [3/3] https://archives.passt.top/passt-dev/20230627025429.2209702-12-david@gibson.dropbear.id.au/
diff --git a/test/avocado_classless/avocado_classless/plugin.py b/test/avocado_classless/avocado_classless/plugin.py
index 442642d5..e2c9b1eb 100644

Checking patch test/avocado_classless/avocado_classless/plugin.py...
Applied patch test/avocado_classless/avocado_classless/plugin.py cleanly.
Checking patch test/avocado_classless/avocado_classless/plugin.py...
Applied patch test/avocado_classless/avocado_classless/plugin.py cleanly.
Checking patch test/avocado_classless/avocado_classless/plugin.py...
Applied patch test/avocado_classless/avocado_classless/plugin.py cleanly.

index at:
100644 e2c9b1eb3d39a47127cc71430e80bde71ea7a582	test/avocado_classless/avocado_classless/plugin.py

Code repositories for project(s) associated with this public inbox

	https://passt.top/passt

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for IMAP folder(s).