From nobody Mon Nov 23 04:34:10 2026 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass(p=none dis=none) header.from=linux.microsoft.com ARC-Seal: i=1; a=rsa-sha256; t=1792972219; cv=none; d=zohomail.com; s=zohoarc; b=lnRMiAI3/svm3esMU3o4hF9M8AYM6KnrJYj8XMtbJ8vkLP8W7B5U7Vsmq/MzCJ2Qp3s27wXkUNZ/mMTmZ2J1LYUDoQ6WwERUIQ5HybFID7YWWTNMK049psSGqfXxDU7c1Lpm+ykuHIx5A60qbPXdRZX5Tai3E3Y40Ox4fVfl+AQ= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1792972219; h=Content-Transfer-Encoding:Cc:Cc:Date:Date:From:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:Sender:Subject:Subject:To:To:Message-Id:Reply-To; bh=H97DeHU0zpPACNUC7KM7hA7STiQOSCg1TqagfayGfWg=; b=oAAi5pbV9w4oeaMbX78vSYjolC6rsNIR8TLQG5AtI33JnvV8aFPwzYC0tiwegh80Jp4Albt5jFrkPgXHKipFXsNjhD4001M4b3/Iix+trtgZp5slsGYoyaNxyOemhktDAx0vklMa9PisM5TmfOpjslb7YybtPaK3xRaxDizmMSY= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from lists1p.gnu.org (lists1p.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1792972219521169.46570956207063; Sun, 25 Oct 2026 16:50:19 -0700 (PDT) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists1p.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1xL7yZ-0001Wp-6u; Sun, 25 Oct 2026 19:50:09 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists1p.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1xL7yA-0001W8-NN for qemu-devel@nongnu.org; Sun, 25 Oct 2026 19:49:48 -0400 Received: from linux.microsoft.com ([13.77.154.182]) by eggs.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1xL7y6-0004a6-Ly for qemu-devel@nongnu.org; Sun, 25 Oct 2026 19:49:42 -0400 Received: from frill.fritz.box (p5dd8e171.dip0.t-ipconnect.de [93.216.225.113]) by linux.microsoft.com (Postfix) with ESMTPSA id 7F1A720B7166; Sun, 25 Oct 2026 16:49:23 -0700 (PDT) DKIM-Filter: OpenDKIM Filter v2.11.0 linux.microsoft.com 7F1A720B7166 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linux.microsoft.com; s=default; t=1792972165; bh=H97DeHU0zpPACNUC7KM7hA7STiQOSCg1TqagfayGfWg=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=gYkI07ZL2HXJMqBFzOsVtE7zD81x2fNbU9+Ac4iI45cDis4NyfRTNgPCuaC6fuXhV UNruei91HmRlixEBI3+5SLn79spgjAvr5LF3zU343eDimbwSZ1Y8+lqIWww7LnxJqh egDtC1QP9QS0TT5umbxnQeCSF7qB/7LB2xHTsxyY= From: Anatol Belski To: qemu-devel@nongnu.org Cc: th.huth+qemu@posteo.eu, berrange@redhat.com, mvaralar@redhat.com, philmd@oss.qualcomm.com, pbonzini@redhat.com, zhao1.liu@intel.com Subject: [PATCH v2] tests: Add virtio-villain fault injection suite Date: Mon, 26 Oct 2026 00:49:22 +0100 Message-ID: <20261025234922.1766842-1-anbelski@linux.microsoft.com> X-Mailer: git-send-email 2.56.0 In-Reply-To: <20261001210916.1907716-1-anbelski@linux.microsoft.com> References: <20261001210916.1907716-1-anbelski@linux.microsoft.com> MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists1p.gnu.org; Received-SPF: pass client-ip=13.77.154.182; envelope-from=anbelski@linux.microsoft.com; helo=linux.microsoft.com X-Spam_score_int: -19 X-Spam_score: -2.0 X-Spam_bar: -- X-Spam_report: (-2.0 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, SPF_HELO_PASS=-0.001, SPF_PASS=-0.001 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: qemu development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: qemu-devel-bounces+importer=patchew.org@nongnu.org X-ZohoMail-DKIM: pass (identity @linux.microsoft.com) X-ZM-MESSAGEID: 1792972221493158500 Content-Type: text/plain; charset="utf-8" Add a test suite that drives the virtio-villain harness against QEMU. virtio-villain is a guest side fault injection tool that boots a separate guest for each case. Each case supplies invalid virtio driver input to test how the device model handles it. The harness is added as a git submodule under tests/virtio-villain. Case IDs are discovered from source filenames during configuration and each case is registered as a Meson test. Meson controls parallel execution and timeouts, with one case per runner invocation. The suite builds the static guest initramfs and fetches kernels on demand for native Linux x86_64 and aarch64 hosts. Generated artifacts stay in the build directory and kernel downloads use the QEMU asset cache. The virtio-villain and check-virtio-villain make targets build and run the suite without adding it to the default check target. Each case retains readable logs and JSON reports, with skipped cases reported separately from successful tests. Embedded helper tests and documentation are included. Signed-off-by: Anatol Belski --- Thanks for the review. I reworked the integration as a standalone optional Meson suite with one test per case, parallel execution and individual logs and JSON reports. virtio-villain has been adapted to accept guest artifacts from the QEMU build directory while preserving sidecar lookup and avoiding vsock CID collisions between parallel runners. .gitmodules | 3 + MAINTAINERS | 7 + docs/devel/testing/index.rst | 1 + docs/devel/testing/virtio-villain.rst | 102 +++++++++ scripts/mtest2make.py | 3 +- tests/Makefile.include | 7 + tests/meson.build | 46 ++++ tests/virtio-villain | 1 + tests/virtio-villain-build.py | 64 ++++++ tests/virtio-villain-list.py | 53 +++++ tests/virtio-villain-test.py | 314 ++++++++++++++++++++++++++ 11 files changed, 600 insertions(+), 1 deletion(-) create mode 100644 docs/devel/testing/virtio-villain.rst create mode 160000 tests/virtio-villain create mode 100644 tests/virtio-villain-build.py create mode 100644 tests/virtio-villain-list.py create mode 100644 tests/virtio-villain-test.py diff --git a/.gitmodules b/.gitmodules index c307216d17..fd3083ca4b 100644 --- a/.gitmodules +++ b/.gitmodules @@ -45,3 +45,6 @@ [submodule "tests/lcitool/libvirt-ci"] path =3D tests/lcitool/libvirt-ci url =3D https://gitlab.com/libvirt/libvirt-ci.git +[submodule "tests/virtio-villain"] + path =3D tests/virtio-villain + url =3D https://github.com/weltling/virtio-villain.git diff --git a/MAINTAINERS b/MAINTAINERS index 4ca1751e30..d87fc958cb 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -4681,6 +4681,13 @@ F: tests/functional/generic/test_linters.py F: tests/functional/pylintrc F: tests/functional/qemu_test/ =20 +virtio-villain fault injection test +M: Anatol Belski +S: Maintained +F: tests/virtio-villain +F: tests/virtio-villain-*.py +F: docs/devel/testing/virtio-villain.rst + Windows Hosted Continuous Integration M: Yonggang Luo S: Maintained diff --git a/docs/devel/testing/index.rst b/docs/devel/testing/index.rst index ccc2fc6cbc..875ef92128 100644 --- a/docs/devel/testing/index.rst +++ b/docs/devel/testing/index.rst @@ -10,6 +10,7 @@ testing infrastructure. main qtest functional + virtio-villain acpi-bits ci fuzzing diff --git a/docs/devel/testing/virtio-villain.rst b/docs/devel/testing/vir= tio-villain.rst new file mode 100644 index 0000000000..a4a100f49d --- /dev/null +++ b/docs/devel/testing/virtio-villain.rst @@ -0,0 +1,102 @@ +.. SPDX-License-Identifier: GPL-2.0-or-later + +virtio-villain +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +The virtio-villain suite tests how QEMU handles invalid virtio driver +input. The harness boots a separate guest for each case to isolate +crashes. Meson registers each case individually and controls parallel +execution, timeouts and results. + +Requirements +------------ + +The suite supports native Linux x86_64 and aarch64 hosts with the +matching system emulator enabled and access to ``/dev/kvm``. +Cross compilation is not supported. +Building the static guest init requires make, strip, cpio, gzip and +a compiler with static C library support. The build prefers musl-gcc +when available and otherwise uses the native compiler recorded by +Meson, including its compiler arguments. + +Meson initializes the submodule at ``tests/virtio-villain`` during +configuration. +With automatic downloads disabled, initialize the submodule manually +before configuring QEMU:: + + git submodule update --init tests/virtio-villain + +Running the suite +----------------- + +From the QEMU checkout, run:: + + make -C build-release virtio-villain + +Replace ``build-release`` with your build directory. Use ``make -jN`` +to control how many cases Meson runs concurrently:: + + make -C build-release -j16 virtio-villain + +The ``virtio-villain`` target invokes ``check-virtio-villain``. +The target builds the guest initramfs and fetches kernels on demand. +Neither operation runs during a normal QEMU build. Generated files +stay under the build directory. Kernel downloads +reuse the QEMU asset cache and verify the SHA256 checksum. Set +``QEMU_TEST_CACHE_DIR`` to override the cache location or +``QEMU_TEST_NO_DOWNLOAD=3D1`` to require cached kernels. + +This standalone suite is not part of the functional tests or the +default ``make check`` selection. Its Meson suite name is +``virtio-villain-optional``, following the QEMU optional suite convention. +To run one case directly through Meson:: + + build-release/pyvenv/bin/meson test -C build-release RNG0001-basic + +Filtering cases +--------------- + +Meson test names combine the case ID with a description from the source +filename, for example ``RNG0001-basic``. The suite identifies them as +virtio-villain tests without repeating that prefix in every name. + +Pass Meson name filters through ``MTESTARGS`` to run one case by ID:: + + make -C build-release virtio-villain MTESTARGS=3D'RNG0001-*' + +Use a wildcard to run a group of cases:: + + make -C build-release -j16 virtio-villain MTESTARGS=3D'RNG*' + +Multiple filters select the union of their matches:: + + make -C build-release -j16 virtio-villain \ + MTESTARGS=3D'RNG* B0196-*' + +List matching cases without running them:: + + build-release/pyvenv/bin/meson test -C build-release \ + --suite virtio-villain-optional --list 'RNG*' + +Quote wildcard filters to prevent shell expansion. These are Meson +test name filters, not the directory filters of the villain runner. + +Results and logs +---------------- + +Each invocation runs one case with the QEMU binary from the build. + +PASS and REJECT pass. SKIP and XFAIL are reported as skipped. +FAIL, WEDGED and XPASS fail. Runner errors and missing reports fail +rather than appearing as successful tests. Unsupported devices and +unavailable host services are skipped by the harness. + +Meson reports each case separately and writes its standard text and +JUnit reports under ``/meson-logs/``. Full readable case logs +and JSON reports are retained under +``/tests/virtio-villain-build/logs/.log`` and ``.json``. +The test output always points to its case log. + +The reporting helper has embedded unit tests that run without a VM:: + + python3 tests/virtio-villain-test.py --self-test diff --git a/scripts/mtest2make.py b/scripts/mtest2make.py index 383ea68b16..696c41e9f4 100644 --- a/scripts/mtest2make.py +++ b/scripts/mtest2make.py @@ -80,7 +80,8 @@ def emit_prolog(suites, prefix): print(f'all-{prefix}-targets =3D {all_targets}') print(f'all-{prefix}-xml =3D {all_xml}') print(f'.PHONY: {prefix} do-meson-{prefix} {prefix}-report.junit.xml $= (all-{prefix}-targets) $(all-{prefix}-xml)') - print(f'ninja-cmd-goals +=3D $(foreach s, $(.{prefix}.mtest-suites), $= (.{prefix}-$s.deps))') + print(f'ninja-cmd-goals +=3D $(foreach s, $(.{prefix}.mtest-suites), ' + f'$(.{prefix}-$(patsubst %-optional,%,$s).deps))') print(f'{prefix}-build: run-ninja') print(f'{prefix} $(all-{prefix}-targets): do-meson-{prefix}') print(f'do-meson-{prefix}: run-ninja; $(if $(MAKE.n),,+)$(MESON) test = $(.{prefix}.mtestargs)') diff --git a/tests/Makefile.include b/tests/Makefile.include index 9f82552ab5..d5cca6a0d1 100644 --- a/tests/Makefile.include +++ b/tests/Makefile.include @@ -16,6 +16,7 @@ check-help: @echo " $(MAKE) check-tracetool Run tracetool generator tes= ts" @echo " $(MAKE) check-block Run block tests (all format= s/protocols)" @echo " $(MAKE) check-block-DRIVER Run block tests (only for f= ormat/protocol 'DRIVER')" + @echo " $(MAKE) virtio-villain Run the standalone virtio = fault injection suite" ifneq ($(filter $(all-check-targets), check-softfloat),) @echo " $(MAKE) check-softfloat Run FPU emulation tests" @echo " $(MAKE) check-tcg Run TCG tests" @@ -55,6 +56,10 @@ check-functional: .PHONY: check-func check-func-quick check-func check-func-quick: =20 +.PHONY: virtio-villain +virtio-villain: + @$(MAKE) check-virtio-villain + # Consolidated targets =20 .PHONY: check check-clean @@ -64,6 +69,8 @@ check-build: run-ninja =20 check-clean: rm -rf $(BUILD_DIR)/tests/functional + rm -rf $(BUILD_DIR)/tests/virtio-villain-build + rm -f $(BUILD_DIR)/tests/virtio-villain-initramfs.stamp =20 clean: check-clean =20 diff --git a/tests/meson.build b/tests/meson.build index 5877d2f60b..619e24c78c 100644 --- a/tests/meson.build +++ b/tests/meson.build @@ -1,6 +1,52 @@ subdir('bench') subdir('qemu-iotests') =20 +if host_os =3D=3D 'linux' and not meson.is_cross_build() and \ + cpu in ['x86_64', 'aarch64'] and \ + emulators.has_key('qemu-system-' + cpu) + villain_make =3D find_program('make', required: false) + villain_strip =3D find_program('strip', required: false) + villain_cpio =3D find_program('cpio', required: false) + villain_gzip =3D find_program('gzip', required: false) + if villain_make.found() and villain_strip.found() and \ + villain_cpio.found() and villain_gzip.found() + villain_list =3D files('virtio-villain-list.py') + villain_list_args =3D get_option('wrap_mode') =3D=3D 'nodownload' ? ['= --no-download'] : [] + villain_names =3D run_command( + python, villain_list, villain_list_args, check: true + ).stdout().strip().split() + villain_sources =3D run_command( + python, villain_list, villain_list_args, '--sources', check: true + ).stdout().strip().split('\n') + villain_musl =3D find_program('musl-gcc', required: false) + villain_cc =3D villain_musl.found() ? [villain_musl.full_path()] : \ + meson.get_compiler('c', native: true= ).cmd_array() + villain_build_dir =3D meson.current_build_dir() / 'virtio-villain-buil= d' + villain_initramfs =3D custom_target( + 'virtio-villain-initramfs', + output: 'virtio-villain-initramfs.stamp', + command: [python, files('virtio-villain-build.py'), + '--source', meson.current_source_dir() / 'virtio-villain', + '--build', villain_build_dir, '--arch', cpu, + '--stamp', '@OUTPUT@', '--make', villain_make.full_path(), + '--'] + villain_cc, + depend_files: files(villain_sources + ['functional/qemu_test/asset.p= y']), + build_by_default: false) + foreach name : villain_names + test(name, python, + args: [files('virtio-villain-test.py'), + '--build', villain_build_dir, + '--source', meson.current_source_dir() / 'virtio-villain= ', + '--qemu', emulators['qemu-system-' + cpu].full_path(), + name.split('-')[0]], + depends: [villain_initramfs, emulators['qemu-system-' + cpu]], + suite: ['virtio-villain-optional'], timeout: 90) + endforeach + else + message('virtio-villain requires make, strip, cpio and gzip') + endif +endif + test_qapi_outputs =3D [ 'qapi-builtin-types.c', 'qapi-builtin-types.h', diff --git a/tests/virtio-villain b/tests/virtio-villain new file mode 160000 index 0000000000..b5f73dbf24 --- /dev/null +++ b/tests/virtio-villain @@ -0,0 +1 @@ +Subproject commit b5f73dbf242f78e72c6b1fdbe8d528f54cba3e90 diff --git a/tests/virtio-villain-build.py b/tests/virtio-villain-build.py new file mode 100644 index 0000000000..9816980b69 --- /dev/null +++ b/tests/virtio-villain-build.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-or-later + +import argparse +from pathlib import Path +import runpy +import shlex +import shutil +import subprocess + + +KERNELS =3D { + 'x86_64': ( + 'vmlinux-x86_64', + '9d3570b47d5abb069ca00edfbfcef4c68306a9c3d078a01f10082b258f1001b8'= ), + 'aarch64': ( + 'Image-arm64', + '69d1b1235381ec50f1b45cf771a7dff4a9013d452833ab34682d6283e2114010'= ), +} +KERNEL_URL =3D ('https://github.com/cloud-hypervisor/linux/releases/downlo= ad/' + 'ch-release-v6.16.9-20260508/') +MMIO_KERNEL =3D ( + 'bzImage-x86_64', + '58088758f601a04ef85b09cf23db5530d51edc039ed47afbf2264c5b762cb568') + + +def main(): + parser =3D argparse.ArgumentParser() + parser.add_argument('--source', type=3DPath, required=3DTrue) + parser.add_argument('--build', type=3DPath, required=3DTrue) + parser.add_argument('--arch', choices=3DKERNELS, required=3DTrue) + parser.add_argument('--stamp', type=3DPath, required=3DTrue) + parser.add_argument('--make', required=3DTrue) + parser.add_argument('compiler', nargs=3Dargparse.REMAINDER) + args =3D parser.parse_args() + compiler =3D args.compiler + if compiler[:1] =3D=3D ['--']: + compiler =3D compiler[1:] + if not compiler: + parser.error('a guest compiler is required') + + args.build.mkdir(parents=3DTrue, exist_ok=3DTrue) + subprocess.run( + [args.make, '-C', str(args.source), 'initramfs', + f'TARGET=3D{args.build / "target"}', + f'CC=3D{shlex.join(compiler)}'], check=3DTrue) + # Load the cache helper without importing the functional test runner. + asset_path =3D (Path(__file__).resolve().parent + / 'functional/qemu_test/asset.py') + asset_type =3D runpy.run_path(str(asset_path))['Asset'] + filename, digest =3D KERNELS[args.arch] + kernel =3D asset_type(KERNEL_URL + filename, digest).fetch() + shutil.copyfile(kernel, args.build / 'kernel') + if args.arch =3D=3D 'x86_64': + filename, digest =3D MMIO_KERNEL + kernel =3D asset_type(KERNEL_URL + filename, digest).fetch() + shutil.copyfile(kernel, args.build / 'mmio-kernel') + else: + shutil.copyfile(args.build / 'kernel', args.build / 'mmio-kernel') + args.stamp.touch() + + +if __name__ =3D=3D '__main__': + main() diff --git a/tests/virtio-villain-list.py b/tests/virtio-villain-list.py new file mode 100644 index 0000000000..5e58bd209c --- /dev/null +++ b/tests/virtio-villain-list.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-or-later + +import argparse +from pathlib import Path +import re +import subprocess +import sys + + +def test_names(source): + names =3D [] + ids =3D set() + for path in sorted((source / 'tests').glob('*/*.c')): + parts =3D path.stem.split('_', 1) + name =3D parts[0].upper() + if not re.fullmatch(r'[A-Z]+[0-9]+', name): + continue + if name in ids: + raise ValueError(f'Duplicate virtio-villain test ID: {name}') + ids.add(name) + description =3D parts[1].replace('_', '-') if len(parts) =3D=3D 2 = else '' + names.append(f'{name}-{description}' if description else name) + if not names: + raise ValueError('Missing or duplicate virtio-villain test names') + return names + + +def main(): + parser =3D argparse.ArgumentParser() + parser.add_argument('--no-download', action=3D'store_true') + parser.add_argument('--sources', action=3D'store_true') + args =3D parser.parse_args() + root =3D Path(__file__).resolve().parent.parent + source =3D root / 'tests/virtio-villain' + if not (source / 'Makefile').exists(): + if args.no_download or not (root / '.git').exists(): + parser.error('Initialize tests/virtio-villain with ' + 'git submodule update --init tests/virtio-villain= ') + subprocess.run(['git', 'submodule', 'update', '--init', + 'tests/virtio-villain'], cwd=3Droot, check=3DTrue, + stdout=3Dsys.stderr) + if args.sources: + paths =3D [source / 'Makefile', source / 'run'] + paths +=3D sorted(source.glob('**/*.c')) + paths +=3D sorted(source.glob('**/*.h')) + print('\n'.join(str(path) for path in paths)) + else: + print('\n'.join(test_names(source))) + + +if __name__ =3D=3D '__main__': + main() diff --git a/tests/virtio-villain-test.py b/tests/virtio-villain-test.py new file mode 100644 index 0000000000..717e2394d0 --- /dev/null +++ b/tests/virtio-villain-test.py @@ -0,0 +1,314 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-or-later + +import argparse +import contextlib +import importlib.machinery +import importlib.util +import io +import json +import os +from pathlib import Path +import re +import runpy +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock + + +ANSI =3D re.compile( + r'\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|' + r'\x1b\[[0-?]*[ -/]*[@-~]|\x1b[ -/]*[@-Z\\-_a-z]') + + +def clean(text): + return ANSI.sub('', text.replace('\r\n', '\n').replace('\r', '\n')) + + +def outcome(report, name, returncode): + cases =3D report['tests'] + if not cases and returncode =3D=3D 0: + return 77 + if len(cases) !=3D 1 or cases[0]['name'] !=3D name: + raise ValueError(f'Expected exactly one result for {name}') + status =3D cases[0]['status'] + if status in ('FAIL', 'WEDGED', 'XPASS'): + return 1 + if returncode !=3D 0: + return 1 + if status in ('SKIP', 'XFAIL'): + return 77 + if status in ('PASS', 'REJECT'): + return 0 + raise ValueError(f'Unknown virtio-villain status: {status}') + + +def kernel_path(build, name): + filename =3D 'mmio-kernel' if name.startswith('M') else 'kernel' + return Path(build) / filename + + +def run_runner(source, build, arguments): + loader =3D importlib.machinery.SourceFileLoader('virtio_villain', sour= ce) + spec =3D importlib.util.spec_from_loader(loader.name, loader) + runner =3D importlib.util.module_from_spec(spec) + loader.exec_module(runner) + # Separate runner processes otherwise allocate the same host vsock CID= s. + runner.Qemu._cid_counter =3D os.getpid() * 256 + sys.argv =3D [ + source, + '--init', str(Path(build) / 'target/init'), + '--initramfs', str(Path(build) / 'target/initramfs.cpio.gz'), + *arguments, + ] + runner.main() + + +def main(): + parser =3D argparse.ArgumentParser() + parser.add_argument('--build', type=3DPath, required=3DTrue) + parser.add_argument('--source', type=3DPath, required=3DTrue) + parser.add_argument('--qemu', required=3DTrue) + parser.add_argument('name') + args =3D parser.parse_args() + logs =3D args.build / 'logs' + logs.mkdir(exist_ok=3DTrue) + report_path =3D logs / f'{args.name}.json' + log_path =3D logs / f'{args.name}.log' + report_path.unlink(missing_ok=3DTrue) + log_path.unlink(missing_ok=3DTrue) + result =3D subprocess.run( + [sys.executable, '-B', str(Path(__file__).resolve()), '--runner', + str(args.source / 'run'), str(args.build), + '-m', args.qemu, '-k', + str(kernel_path(args.build, args.name)), + '--transport', 'mmio' if args.name.startswith('M') else 'pci', + '--skip-unsupported', '-j', '1', + '--log-dir', str(logs), + '--format', 'json', '--output', str(report_path), + args.name], capture_output=3DTrue, text=3DTrue, errors=3D'replace= ', + check=3DFalse) + text =3D clean(result.stdout) + clean(result.stderr) + serial =3D clean(log_path.read_text(errors=3D'replace')) \ + if log_path.exists() else None + code =3D 1 + try: + if not report_path.exists(): + raise ValueError('virtio-villain produced no JSON report') + with report_path.open() as stream: + report =3D json.load(stream) + for case in report['tests']: + text +=3D ('\n{status} {name} (spec {spec_section}) ' + '{description}\n').format(**case) + text +=3D serial if serial is not None else \ + clean(case.get('output') or '') + code =3D outcome(report, args.name, result.returncode) + except (OSError, ValueError, KeyError, TypeError) as error: + text +=3D f'\nERROR: invalid virtio-villain result: {error}\n' + log_path.write_text(text) + print(text, end=3D'') + print(f'\nFull virtio-villain log: {log_path}') + return code + + +class Helpers(unittest.TestCase): + def test_clean(self): + self.assertEqual(clean('\x1bc\x1b[?7lA\r\nB\rC\x1b[0m'), + 'A\nB\nC') + self.assertEqual(clean('\x1b]0;title\x07text'), 'text') + + def test_outcomes(self): + for status, expected in ( + ('PASS', 0), ('REJECT', 0), ('SKIP', 77), ('XFAIL', 77), + ('FAIL', 1), ('WEDGED', 1), ('XPASS', 1)): + with self.subTest(status=3Dstatus): + report =3D {'tests': [{'name': 'RNG0001', 'status': status= }]} + self.assertEqual(outcome(report, 'RNG0001', 0), expected) + + def test_runner_error_is_failure(self): + report =3D {'tests': [{'name': 'RNG0001', 'status': 'PASS'}]} + self.assertEqual(outcome(report, 'RNG0001', 1), 1) + self.assertEqual(outcome({'tests': []}, 'M0001', 0), 77) + with self.assertRaises(ValueError): + outcome({'tests': []}, 'RNG0001', 1) + + def test_wrong_case_is_error(self): + with self.assertRaises(ValueError): + outcome({'tests': [{'name': 'OTHER', 'status': 'PASS'}]}, + 'RNG0001', 0) + + def test_unknown_status_is_error(self): + with self.assertRaises(ValueError): + outcome({'tests': [{'name': 'RNG0001', 'status': 'UNKNOWN'}]}, + 'RNG0001', 0) + + def test_runner_configuration(self): + runner =3D types.SimpleNamespace( + main=3Dmock.Mock(), + Qemu=3Dtypes.SimpleNamespace()) + with mock.patch.object(importlib.machinery.SourceFileLoader, + 'exec_module'), \ + mock.patch.object(importlib.util, 'module_from_spec', + return_value=3Drunner), \ + mock.patch.object(sys, 'argv', []), \ + mock.patch.object(os, 'getpid', return_value=3D123): + run_runner('/source/run', '/build', ['RNG0001']) + self.assertEqual(runner.Qemu._cid_counter, 123 * 256) + runner.main.assert_called_once_with() + self.assertEqual(sys.argv, [ + '/source/run', + '--init', '/build/target/init', + '--initramfs', '/build/target/initramfs.cpio.gz', + 'RNG0001', + ]) + + def test_kernel_selection(self): + for name in ('RNG0001', 'B0201', 'PCI0200'): + with self.subTest(name=3Dname): + self.assertEqual(kernel_path(Path('/build'), name), + Path('/build/kernel')) + self.assertEqual(kernel_path(Path('/build'), 'M0010'), + Path('/build/mmio-kernel')) + + def test_build_uses_only_cloud_hypervisor_kernels(self): + script =3D Path(__file__).with_name('virtio-villain-build.py') + builder =3D runpy.run_path(str(script)) + for arch in ('x86_64', 'aarch64'): + with self.subTest(arch=3Darch), \ + tempfile.TemporaryDirectory() as directory: + root =3D Path(directory) + kernel =3D root / 'download' + kernel.write_bytes(b'kernel') + asset_type =3D mock.Mock() + asset_type.return_value.fetch.return_value =3D kernel + argv =3D [ + 'build', '--source', '/source', '--build', directory, + '--arch', arch, '--stamp', str(root / 'stamp'), + '--make', 'make', '--', 'cc', + ] + with mock.patch.object(sys, 'argv', argv), \ + mock.patch.object(subprocess, 'run') as build, \ + mock.patch.object(runpy, 'run_path', + return_value=3D{'Asset': asset_type= }): + builder['main']() + expected =3D [ + mock.call(builder['KERNEL_URL'] + filename, digest) + for filename, digest in [builder['KERNELS'][arch]] + + ([builder['MMIO_KERNEL']] if arch =3D=3D 'x86_64' el= se []) + ] + self.assertEqual(asset_type.call_args_list, expected) + self.assertEqual(asset_type.return_value.fetch.call_count, + len(expected)) + build.assert_called_once_with( + ['make', '-C', '/source', 'initramfs', + f'TARGET=3D{root / "target"}', 'CC=3Dcc'], check=3DTr= ue) + self.assertEqual((root / 'kernel').read_bytes(), b'kernel') + self.assertEqual((root / 'mmio-kernel').read_bytes(), + b'kernel') + self.assertFalse((root / 'hotplug-kernel').exists()) + self.assertTrue((root / 'stamp').exists()) + + def test_full_readable_log(self): + with tempfile.TemporaryDirectory() as directory: + root =3D Path(directory) + case =3D {'name': 'RNG0001', 'status': 'PASS', + 'spec_section': '5.4.6', + 'description': 'RNG basic request', + 'output': ''} + + def run(*unused_args, **unused_kwargs): + (root / 'logs/RNG0001.json').write_text( + json.dumps({'tests': [case]})) + (root / 'logs/RNG0001.log').write_bytes( + b'\x1bcguest\r\n[PASS] RNG0001\r\n') + return subprocess.CompletedProcess([], 0, '[PASS]\n', '') + + argv =3D ['test', '--build', directory, '--source', '/source', + '--qemu', '/build/qemu-system-x86_64', 'RNG0001'] + with mock.patch.object(sys, 'argv', argv), \ + mock.patch.object(subprocess, 'run', side_effect=3Drun), \ + mock.patch('builtins.print') as output: + self.assertEqual(main(), 0) + text =3D (root / 'logs/RNG0001.log').read_bytes() + self.assertIn(b'guest\n[PASS] RNG0001\n', text) + self.assertNotIn(b'\r', text) + self.assertNotIn(b'\x1b', text) + self.assertIn(str(root / 'logs/RNG0001.log'), + output.call_args.args[0]) + + def test_explicit_transport(self): + for name, transport in (('RNG0001', 'pci'), ('M0010', 'mmio')): + with self.subTest(name=3Dname), \ + tempfile.TemporaryDirectory() as directory: + root =3D Path(directory) + case =3D {'name': name, 'status': 'PASS', + 'spec_section': '4', 'description': 'Test case'} + + def run(command, **kwargs): + index =3D command.index('--transport') + self.assertEqual(command[index + 1], transport) + (root / f'logs/{name}.json').write_text( + json.dumps({'tests': [case]})) + return subprocess.CompletedProcess(command, 0, '', '') + + argv =3D ['test', '--build', directory, '--source', '/sour= ce', + '--qemu', '/build/qemu-system-x86_64', name] + with mock.patch.object(sys, 'argv', argv), \ + mock.patch.object(subprocess, 'run', side_effect=3Dru= n), \ + mock.patch('builtins.print'): + self.assertEqual(main(), 0) + + def test_source_discovery(self): + script =3D Path(__file__).with_name('virtio-villain-list.py') + discover =3D runpy.run_path(str(script))['test_names'] + with tempfile.TemporaryDirectory() as directory: + root =3D Path(directory) + (root / 'tests/rng').mkdir(parents=3DTrue) + (root / 'tests/rng/rng0001_basic.c').touch() + (root / 'tests/rng/rng_helpers.c').touch() + self.assertEqual(discover(root), ['RNG0001-basic']) + (root / 'tests/rng/rng0002_invalid_length.c').touch() + self.assertEqual(discover(root), + ['RNG0001-basic', 'RNG0002-invalid-length']) + (root / 'tests/rng/rng0001_duplicate.c').touch() + with self.assertRaises(ValueError): + discover(root) + + def test_initialization_keeps_stdout_machine_readable(self): + script =3D Path(__file__).with_name('virtio-villain-list.py') + list_main =3D runpy.run_path(str(script))['main'] + with tempfile.TemporaryDirectory() as directory: + root =3D Path(directory) + (root / '.git').mkdir() + + def initialize(*unused_args, **kwargs): + print('Submodule initialized', file=3Dkwargs['stdout']) + source =3D root / 'tests/virtio-villain' + (source / 'tests/rng').mkdir(parents=3DTrue) + (source / 'Makefile').touch() + (source / 'tests/rng/rng0001_basic.c').touch() + + output, diagnostic =3D io.StringIO(), io.StringIO() + with mock.patch.dict( + list_main.__globals__, + {'__file__': str(root / 'tests' / script.name)}), \ + mock.patch.object(sys, 'argv', ['list']), \ + mock.patch.object( + subprocess, 'run', side_effect=3Dinitialize), \ + contextlib.redirect_stdout(output), \ + contextlib.redirect_stderr(diagnostic): + list_main() + self.assertEqual(output.getvalue(), 'RNG0001-basic\n') + self.assertIn('Submodule initialized', diagnostic.getvalue()) + + +if __name__ =3D=3D '__main__': + if sys.argv[1:] =3D=3D ['--self-test']: + unittest.main(argv=3D[sys.argv[0]]) + elif sys.argv[1:2] =3D=3D ['--runner']: + run_runner(sys.argv[2], sys.argv[3], sys.argv[4:]) + else: + sys.exit(main()) --=20 2.56.0