From fd94563aebcd577e09136bf09bcc2470f1cfed5e Mon Sep 17 00:00:00 2001
From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com>
Date: Sat, 28 Nov 2026 01:40:24 -0500
Subject: [PATCH 1/9] ci(xbox): publish coverage from xemu guest tests
---
.github/workflows/ci-xbox-original.yml | 52 +++++++-
CMakeLists.txt | 1 +
README.md | 19 +++
build.sh | 8 +-
cmake/nxdk.cmake | 6 +
cmake/run-child-build.cmake | 1 +
cmake/xbox-build.cmake | 4 +
scripts/run-xbox-coverage.py | 171 +++++++++++++++++++++++++
scripts/run-xemu.sh | 26 +++-
scripts/setup-xemu.sh | 11 +-
tests/xbox/guest/CMakeLists.txt | 43 +++++++
tests/xbox/guest/gcov_serial.c | 134 +++++++++++++++++++
tests/xbox/guest/gcov_serial.h | 16 +++
tests/xbox/guest/gtest_port.h | 36 ++++++
tests/xbox/guest/main.cpp | 55 ++++++++
tests/xbox/guest/time_test.cpp | 65 ++++++++++
16 files changed, 638 insertions(+), 10 deletions(-)
create mode 100644 scripts/run-xbox-coverage.py
create mode 100644 tests/xbox/guest/CMakeLists.txt
create mode 100644 tests/xbox/guest/gcov_serial.c
create mode 100644 tests/xbox/guest/gcov_serial.h
create mode 100644 tests/xbox/guest/gtest_port.h
create mode 100644 tests/xbox/guest/main.cpp
create mode 100644 tests/xbox/guest/time_test.cpp
diff --git a/.github/workflows/ci-xbox-original.yml b/.github/workflows/ci-xbox-original.yml
index 57fef15a..62b27df9 100644
--- a/.github/workflows/ci-xbox-original.yml
+++ b/.github/workflows/ci-xbox-original.yml
@@ -101,7 +101,11 @@ jobs:
- name: Build
run: |
chmod +x build.sh
- ./build.sh --build-dir "${CMAKE_BUILD}" --coverage
+ coverage=(--coverage)
+ if [[ "${RUNNER_OS}" == Linux ]]; then
+ coverage+=(--xbox-coverage)
+ fi
+ ./build.sh --build-dir "${CMAKE_BUILD}" "${coverage[@]}"
# recursively list all files in build directory
ls -R "${CMAKE_BUILD}"
@@ -124,3 +128,49 @@ jobs:
platform: Xbox-host-${{ runner.os }}
test-shell: '${{ matrix.shell }}'
codecov-token: ${{ secrets.CODECOV_TOKEN }}
+
+ - name: Set up xemu
+ if: runner.os == 'Linux'
+ env:
+ SUNSHINE_XEMU_TAG: v0.8.139
+ run: |
+ sudo apt-get install --no-install-recommends -y libgl1-mesa-dri libglx-mesa0 xauth xvfb
+ bash scripts/setup-xemu.sh
+
+ - name: Run Xbox tests and recover guest coverage
+ if: runner.os == 'Linux'
+ id: guest-coverage
+ env:
+ APPIMAGE_EXTRACT_AND_RUN: '1'
+ LIBGL_ALWAYS_SOFTWARE: '1'
+ SDL_AUDIO_DRIVER: dummy
+ run: |
+ xvfb-run -a -s '-screen 0 1024x768x24' \
+ uv run --project third-party/lizardbyte-common --locked --no-sync \
+ python scripts/run-xbox-coverage.py "${CMAKE_BUILD}/xbox"
+
+ - name: Upload Xbox guest test and coverage artifacts
+ if: >-
+ ${{ !cancelled() &&
+ (steps.guest-coverage.outcome == 'success' || steps.guest-coverage.outcome == 'failure') }}
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: Tests-Xbox-guest-xemu
+ path: |
+ ${{ env.CMAKE_BUILD }}/xbox/xemu-coverage/*.log
+ ${{ env.CMAKE_BUILD }}/xbox/xemu-coverage/test_results.xml
+ ${{ env.CMAKE_BUILD }}/xbox/xemu-coverage/coverage.info
+ if-no-files-found: error
+
+ - name: Upload Xbox guest coverage to Codecov
+ if: >-
+ ${{ !cancelled() && startsWith(github.repository, 'SunshineStream/') &&
+ hashFiles(format('{0}/xbox/xemu-coverage/coverage.info', env.CMAKE_BUILD)) != '' }}
+ uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
+ with:
+ disable_search: true
+ fail_ci_if_error: true
+ files: ${{ env.CMAKE_BUILD }}/xbox/xemu-coverage/coverage.info
+ flags: Xbox-guest-xemu
+ report_type: coverage
+ token: ${{ secrets.CODECOV_TOKEN }}
diff --git a/CMakeLists.txt b/CMakeLists.txt
index ed15be94..68c882c3 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -11,6 +11,7 @@ set(SUNSHINE_BUILD_KIND "HOST" CACHE STRING "Internal Sunshine build mode")
set_property(CACHE SUNSHINE_BUILD_KIND PROPERTY STRINGS HOST XBOX)
option(SUNSHINE_BUILD_VIDEO_EXPERIMENTS "Build standalone GPU presentation and MPEG-2 sampling experiments" OFF)
option(SUNSHINE_BUILD_AUDIO_EXPERIMENTS "Build the standalone Opus playback probe" OFF)
+option(SUNSHINE_BUILD_XBOX_TESTS "Build a coverage-instrumented Original Xbox test ISO" OFF)
option(SUNSHINE_INPUT_DIAGNOSTICS "Display digital controller state while diagnosing stream input" OFF)
option(SUNSHINE_SCREENSHOT_DEMO "Use fictional hosts and apps for documentation screenshots" OFF)
diff --git a/README.md b/README.md
index a77e7144..d2cd62db 100644
--- a/README.md
+++ b/README.md
@@ -500,6 +500,25 @@ scripts\setup-xemu.cmd --skip-support-files
> [Xbox EEPROM Editor](https://github.com/Ernegien/XboxEepromEditor). 1080i streaming is demanding
> on the emulated CPU, especially when using software presentation.
+### Guest tests and coverage in xemu
+
+Build the instrumented test disc, set up xemu, and run the tests from the repository root.
+On Windows, run these commands in UCRT64 and use `cmake-build-release-ucrt64/xbox` as the Xbox
+build directory. Use the `llvm-cov` from the same LLVM installation as Clang.
+
+```bash
+bash build.sh --xbox-coverage
+bash scripts/setup-xemu.sh
+uv sync --locked
+uv run --locked python scripts/run-xbox-coverage.py cmake-build-release/xbox
+```
+
+The build creates `SunshineTests.iso` beside the release ISO. The runner boots the test disc in xemu
+and recovers test results and coverage counters from the guest's serial console. It pairs the counters
+with the coverage notes from the same build, then writes JUnit, LCOV, and logs under
+`xbox/xemu-coverage/`. Linux CI runs xemu under Xvfb and uploads the report to Codecov with the
+`Xbox-guest-xemu` flag.
+
## Host-native unit tests
The Xbox executable cannot run directly on Windows, macOS, or Linux, so the top-level project builds `test_sunshine` natively while the Xbox binary is built by an internal child configure that uses the `nxdk` toolchain. Keep Xbox runtime code thin and move logic you want to test into platform-neutral sources that can be linked into `test_sunshine`.
diff --git a/build.sh b/build.sh
index 47f4417d..76a7c3a1 100644
--- a/build.sh
+++ b/build.sh
@@ -4,7 +4,7 @@
set -euo pipefail
usage() {
- echo "Usage: $0 [--build-dir
| ] [--clean|clean] [--distclean|distclean] [--coverage]"
+ echo "Usage: $0 [--build-dir | ] [--clean|clean] [--distclean|distclean] [--coverage] [--xbox-coverage]"
return 0
}
@@ -16,6 +16,7 @@ case "${HOST_SYSTEM}" in
esac
CLEAN_BUILD=0
ENABLE_TEST_COVERAGE=0
+ENABLE_XBOX_COVERAGE=OFF
POSITIONAL_BUILD_DIR_SET=0
while [[ "$#" -gt 0 ]]; do
@@ -41,6 +42,10 @@ while [[ "$#" -gt 0 ]]; do
ENABLE_TEST_COVERAGE=1
shift
;;
+ --xbox-coverage)
+ ENABLE_XBOX_COVERAGE=ON
+ shift
+ ;;
-h|--help)
usage
exit 0
@@ -75,6 +80,7 @@ cmake_configure_args=(
-DBUILD_NATIVE_CLIENT=OFF
-DBUILD_TESTS=ON
-DBUILD_XBOX=ON
+ -DSUNSHINE_BUILD_XBOX_TESTS="${ENABLE_XBOX_COVERAGE}"
-DCMAKE_DEPENDS_USE_COMPILER=FALSE
-DCMAKE_BUILD_TYPE=Release
)
diff --git a/cmake/nxdk.cmake b/cmake/nxdk.cmake
index 9632b101..5dd92125 100644
--- a/cmake/nxdk.cmake
+++ b/cmake/nxdk.cmake
@@ -358,6 +358,7 @@ function(sunshine_add_xbox_build)
-DSUNSHINE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE}
-DSUNSHINE_BUILD_VIDEO_EXPERIMENTS:BOOL=${SUNSHINE_BUILD_VIDEO_EXPERIMENTS}
-DSUNSHINE_BUILD_AUDIO_EXPERIMENTS:BOOL=${SUNSHINE_BUILD_AUDIO_EXPERIMENTS}
+ -DSUNSHINE_BUILD_XBOX_TESTS:BOOL=${SUNSHINE_BUILD_XBOX_TESTS}
-DSUNSHINE_INPUT_DIAGNOSTICS:BOOL=${SUNSHINE_INPUT_DIAGNOSTICS}
-DSUNSHINE_SCREENSHOT_DEMO:BOOL=${SUNSHINE_SCREENSHOT_DEMO}
-P "${driver_script}"
@@ -377,12 +378,17 @@ function(sunshine_add_xbox_build)
if(SUNSHINE_SCREENSHOT_DEMO)
set(iso_name "SunshineDemo.iso")
endif()
+ set(test_iso)
+ if(SUNSHINE_BUILD_XBOX_TESTS)
+ set(test_iso "${SUNSHINE_XBOX_BINARY_DIR}/SunshineTests.iso")
+ endif()
add_custom_target(sunshine_xbox ALL
COMMAND ${configure_command}
COMMAND ${build_command}
BYPRODUCTS
"${SUNSHINE_XBOX_BINARY_DIR}/${iso_name}"
"${SUNSHINE_XBOX_BINARY_DIR}/xbe/default.xbe"
+ ${test_iso}
COMMENT "Configure and build the Xbox target in ${SUNSHINE_XBOX_BINARY_DIR}"
USES_TERMINAL
VERBATIM
diff --git a/cmake/run-child-build.cmake b/cmake/run-child-build.cmake
index d1857a51..ac43cc13 100644
--- a/cmake/run-child-build.cmake
+++ b/cmake/run-child-build.cmake
@@ -30,6 +30,7 @@ if(SUNSHINE_COMMAND_MODE STREQUAL "configure")
-DSUNSHINE_BUILD_KIND:STRING=XBOX
"-DSUNSHINE_BUILD_VIDEO_EXPERIMENTS:BOOL=${SUNSHINE_BUILD_VIDEO_EXPERIMENTS}"
"-DSUNSHINE_BUILD_AUDIO_EXPERIMENTS:BOOL=${SUNSHINE_BUILD_AUDIO_EXPERIMENTS}"
+ "-DSUNSHINE_BUILD_XBOX_TESTS:BOOL=${SUNSHINE_BUILD_XBOX_TESTS}"
"-DSUNSHINE_INPUT_DIAGNOSTICS:BOOL=${SUNSHINE_INPUT_DIAGNOSTICS}"
"-DSUNSHINE_SCREENSHOT_DEMO:BOOL=${SUNSHINE_SCREENSHOT_DEMO}"
"-DSUNSHINE_NXDK_DIR:PATH=${SUNSHINE_NXDK_SOURCE_DIR}"
diff --git a/cmake/xbox-build.cmake b/cmake/xbox-build.cmake
index 1fbcc86d..4bf127aa 100644
--- a/cmake/xbox-build.cmake
+++ b/cmake/xbox-build.cmake
@@ -128,6 +128,10 @@ endif()
set(_cxbe ${_packaging_env} "${NXDK_DIR}/tools/cxbe/cxbe${_packaging_tool_suffix}")
set(_extract_xiso ${_packaging_env} "${NXDK_DIR}/tools/extract-xiso/build/extract-xiso${_packaging_tool_suffix}")
+if(SUNSHINE_BUILD_XBOX_TESTS)
+ add_subdirectory(tests/xbox/guest)
+endif()
+
# Expose the same ISO target in the direct Xbox profile and its host parent.
add_custom_target(sunshine_xbox ALL
COMMAND "${CMAKE_COMMAND}" -E copy_directory
diff --git a/scripts/run-xbox-coverage.py b/scripts/run-xbox-coverage.py
new file mode 100644
index 00000000..bb12f0fb
--- /dev/null
+++ b/scripts/run-xbox-coverage.py
@@ -0,0 +1,171 @@
+#!/usr/bin/env python3
+"""Run the Xbox test ISO and recover its coverage and test results from xemu."""
+
+import argparse
+import os
+import re
+import shutil
+import subprocess
+import sys
+import time
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+
+RESULT = re.compile(rb"^SUNSHINE_TEST_DONE ([01]) (\d+)\r?\n", re.MULTILINE)
+GUEST_TEST_DIR = "tests/xbox/guest"
+
+
+def run_xemu(build, output):
+ """Wait for a complete guest report, keeping emulator logs on every exit."""
+ launcher = Path(__file__).with_name("run-xemu.sh").resolve()
+ shell = shutil.which("bash")
+ if not shell:
+ raise ValueError("Bash is needed to run the xemu launcher")
+ serial = output / "serial.log"
+ with (output / "xemu.log").open("wb") as log:
+ command = [
+ shell, launcher.as_posix(), "--iso", (build / "SunshineTests.iso").as_posix(),
+ "--test-output", output.as_posix(), "--network", "none",
+ ]
+ with subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=log, stderr=log) as xemu:
+ try:
+ deadline = time.monotonic() + 120
+ while time.monotonic() < deadline:
+ if serial.is_file():
+ transcript = serial.read_bytes()
+ if RESULT.search(transcript):
+ return transcript
+ if xemu.poll() is not None:
+ raise ValueError(f"xemu stopped before guest tests completed (exit {xemu.returncode})")
+ time.sleep(0.25)
+ raise ValueError("Timed out waiting for guest tests and coverage")
+ finally:
+ if xemu.poll() is None:
+ if os.name == "nt":
+ # MSYS2 exec waits for the native xemu process as a child.
+ subprocess.run(
+ ["taskkill", "/pid", str(xemu.pid), "/t", "/f"],
+ stdout=log, stderr=log, check=False,
+ )
+ else:
+ xemu.terminate()
+ try:
+ xemu.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ xemu.kill()
+
+
+def write_test_results(transcript, output):
+ """Write JUnit from the guest's completed tests and return its exit status."""
+ status, expected = map(int, RESULT.search(transcript).groups())
+ cases = re.findall(rb"^SUNSHINE_TEST_CASE (PASS|FAIL|SKIP) (\S+) (\S+)\r?$", transcript, re.MULTILINE)
+ if not cases or len(cases) != expected or len({(suite, name) for _, suite, name in cases}) != expected:
+ raise ValueError(f"Received {len(cases)} test records, expected {expected} unique records")
+
+ results = ET.Element("testsuites")
+ suite = ET.SubElement(results, "testsuite", name="Original Xbox in xemu", tests=str(len(cases)))
+ for result, classname, name in cases:
+ test = ET.SubElement(suite, "testcase", classname=classname.decode("ascii"), name=name.decode("ascii"))
+ if result == b"FAIL":
+ ET.SubElement(test, "failure", message="See serial.log for assertion output")
+ elif result == b"SKIP":
+ ET.SubElement(test, "skipped")
+ print(f"{result.decode()} {classname.decode()}.{name.decode()}")
+ suite.set("failures", str(sum(result == b"FAIL" for result, _, _ in cases)))
+ suite.set("skipped", str(sum(result == b"SKIP" for result, _, _ in cases)))
+ ET.ElementTree(results).write(output / "test_results.xml", encoding="utf-8", xml_declaration=True)
+ if not any(result == b"PASS" for result, _, _ in cases):
+ raise ValueError("No Xbox guest test passed")
+ return status or any(result == b"FAIL" for result, _, _ in cases)
+
+
+def extract_coverage(transcript, object_dir):
+ """Pair complete gcda files from the guest with their build's gcno files."""
+ note_files = list(object_dir.rglob("*.gcno"))
+ notes = {path.with_suffix(".gcda").name: path for path in note_files}
+ if not notes or len(notes) != len(note_files):
+ raise ValueError("Expected uniquely named coverage notes from the instrumented build")
+ data_files = {}
+ current = None
+ for line in transcript.splitlines():
+ tag, _, payload = line.partition(b" ")
+ if tag == b"SUNSHINE_GCOV_BEGIN":
+ current_name = payload.decode("ascii")
+ if current is not None or current_name not in notes or current_name in data_files:
+ raise ValueError(f"Unexpected gcda stream for {current_name}")
+ current = bytearray()
+ elif tag == b"SUNSHINE_GCOV_DATA" and current is not None:
+ current.extend(bytes.fromhex(payload.decode("ascii")))
+ elif tag == b"SUNSHINE_GCOV_END" and current is not None:
+ note = notes[current_name]
+ if len(current) < 20 or current[:12] != b"adcg" + note.read_bytes()[4:12] or any(current[-8:]):
+ raise ValueError(f"Invalid or mismatched gcda stream for {note.name}")
+ data_files[current_name] = current
+ current = None
+ elif tag.startswith(b"SUNSHINE_GCOV_"):
+ raise ValueError(f"Unexpected coverage record: {line!r}")
+ if current is not None or data_files.keys() != notes.keys():
+ raise ValueError(f"Incomplete guest coverage, missing: {sorted(notes.keys() - data_files.keys())}")
+ for name, data in data_files.items():
+ notes[name].with_suffix(".gcda").write_bytes(data)
+
+
+def generate_report(object_dir, output, llvm_cov):
+ """Export LCOV and require executed lines in both Xbox timing adapters."""
+ report = output / "coverage.info"
+ temporary = report.with_suffix(".tmp")
+ source_root = Path(__file__).resolve().parents[1]
+ subprocess.run(
+ [
+ sys.executable, "-m", "gcovr", str(object_dir), "--root", str(source_root),
+ "--gcov-executable", f"{llvm_cov} gcov", "--filter", "src/",
+ "--exclude-noncode-lines", "--exclude-throw-branches", "--exclude-unreachable-branches",
+ "--lcov", str(temporary),
+ ],
+ cwd=source_root,
+ check=True,
+ )
+ expected = {"src/_nxdk_compat/include/sunshine_time.h", "src/_nxdk_compat/runtime.c"}
+ source = ""
+ records = []
+ for line in temporary.read_text(encoding="utf-8").splitlines():
+ if line.startswith("SF:"):
+ path = Path(line[3:])
+ source = (source_root / path).relative_to(source_root).as_posix()
+ line = f"SF:{source}"
+ elif re.match(r"DA:\d+,[1-9]\d*(?:,|$)", line):
+ expected.discard(source)
+ records.append(line)
+ if expected:
+ raise ValueError(f"Missing executed lines in Xbox sources: {sorted(expected)}")
+ temporary.write_text("\n".join(records) + "\n", encoding="utf-8", newline="\n")
+ temporary.replace(report)
+
+
+def main():
+ """Collect one guest run from the Xbox child build."""
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("build", type=Path, help="Xbox child build directory containing SunshineTests.iso")
+ parser.add_argument("--llvm-cov", default="llvm-cov", help="llvm-cov matching the nxdk Clang compiler")
+ args = parser.parse_args()
+ build = args.build.resolve()
+ output = build / "xemu-coverage"
+ output.mkdir(exist_ok=True)
+ for name in ("serial.log", "test_results.xml", "coverage.info"):
+ (output / name).unlink(missing_ok=True)
+ object_dir = build / GUEST_TEST_DIR / "CMakeFiles/sunshine_xbox_coverage.dir"
+ for data in object_dir.rglob("*.gcda"):
+ data.unlink()
+ try:
+ transcript = run_xemu(build, output)
+ failure = write_test_results(transcript, output)
+ extract_coverage(transcript, object_dir)
+ generate_report(object_dir, output, args.llvm_cov)
+ except (OSError, ValueError, subprocess.CalledProcessError) as error:
+ parser.exit(1, f"{error}. See {output / 'xemu.log'} and {output / 'serial.log'}.\n")
+ return failure
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/run-xemu.sh b/scripts/run-xemu.sh
index fd5e97be..61be9f66 100644
--- a/scripts/run-xemu.sh
+++ b/scripts/run-xemu.sh
@@ -7,7 +7,9 @@ set -euo pipefail
usage() {
cat <<'EOF'
-Usage: run-xemu.sh [--check] [--build-dir dir] [--iso path] [--network mode] [--tap-ifname name] [path]
+Usage: run-xemu.sh [--check] [--build-dir dir] [--iso path] [--network mode] [--tap-ifname name] [--test-output dir] [path]
+
+Use --test-output to capture serial output and isolate the test guest's disk writes.
Environment overrides:
SUNSHINE_XEMU_BUILD_DIR
@@ -271,6 +273,7 @@ build_dir=""
iso_path="$(default_iso_path "$project_root")"
check_only=0
target_path=""
+test_output=""
network_mode="${SUNSHINE_XEMU_NETWORK:-user}"
tap_ifname="${SUNSHINE_XEMU_TAP_IFNAME:-}"
xemu_network_args=()
@@ -331,6 +334,14 @@ while [[ $# -gt 0 ]]; do
fi
tap_ifname="$1"
;;
+ --test-output)
+ shift
+ if [[ $# -eq 0 ]]; then
+ echo 'Missing value for --test-output' >&2
+ exit 2
+ fi
+ test_output="$(resolve_input_path "$1")"
+ ;;
--)
shift
if [[ $# -gt 0 ]]; then
@@ -364,14 +375,14 @@ if [[ -n "$target_path" ]]; then
fi
if [[ ! -f "$manifest_sh" ]]; then
- "$setup_script"
+ bash "$setup_script"
fi
# shellcheck disable=SC1090
source "$manifest_sh"
if [[ -z "${XEMU_EXE:-}" || ! -e "$XEMU_EXE" ]]; then
- "$setup_script"
+ bash "$setup_script"
# shellcheck disable=SC1090
source "$manifest_sh"
fi
@@ -388,6 +399,14 @@ flashrom_path="${XEMU_FLASHROM_PATH:-}"
eeprom_path="${XEMU_EEPROM_PATH:-}"
hdd_path="${XEMU_HDD_PATH:-}"
xemu_config_path="$project_root/.local/xemu/runtime/xemu.toml"
+test_args=()
+
+if [[ -n "$test_output" ]]; then
+ eeprom_path="$test_output/eeprom.bin"
+ xemu_config_path="$test_output/xemu.toml"
+ serial_args=(-device lpc47m157 -serial "file:$(to_native_path "$test_output/serial.log")")
+ test_args=(-snapshot)
+fi
if [[ -z "$eeprom_path" ]]; then
eeprom_path="$project_root/.local/xemu/eeprom.bin"
@@ -446,5 +465,6 @@ if [[ ${#xemu_network_args[@]} -gt 0 ]]; then
xemu_args+=("${xemu_network_args[@]}")
fi
xemu_args+=("${serial_args[@]}")
+xemu_args+=("${test_args[@]}")
exec "$xemu_exe" "${xemu_args[@]}"
diff --git a/scripts/setup-xemu.sh b/scripts/setup-xemu.sh
index abd7bf3d..bd161146 100644
--- a/scripts/setup-xemu.sh
+++ b/scripts/setup-xemu.sh
@@ -8,6 +8,7 @@ Usage: setup-xemu.sh [--force] [--skip-support-files]
Downloads a portable xemu build into .local/xemu and refreshes launcher manifests.
Existing .local/xemu files are preserved unless --force is passed.
+Set SUNSHINE_XEMU_TAG to select a release instead of the latest version.
EOF
return 0
}
@@ -118,13 +119,13 @@ select_xemu_asset() {
printf 'xemu-win-aarch64-release.zip\n'
;;
macos:*)
- printf 'xemu-%s-macos-universal.zip\n' "$tag"
+ printf 'xemu-%s-macos-universal.zip\n' "${tag#v}"
;;
linux:x86_64|linux:amd64)
- printf 'xemu-%s-x86_64.AppImage\n' "$tag"
+ printf 'xemu-%s-x86_64.AppImage\n' "${tag#v}"
;;
linux:arm64|linux:aarch64)
- printf 'xemu-%s-aarch64.AppImage\n' "$tag"
+ printf 'xemu-%s-aarch64.AppImage\n' "${tag#v}"
;;
*)
return 1
@@ -267,14 +268,14 @@ else
mapfile -t platform_info < <(detect_platform)
os_name="${platform_info[0]}"
arch_name="${platform_info[1]}"
- tag="$(latest_xemu_tag)"
+ tag="${SUNSHINE_XEMU_TAG:-$(latest_xemu_tag)}"
if [[ -z "$tag" ]]; then
echo 'Could not determine the latest xemu release tag.' >&2
exit 1
fi
asset_name="$(select_xemu_asset "$os_name" "$arch_name" "$tag")"
- asset_url="https://github.com/xemu-project/xemu/releases/latest/download/${asset_name}"
+ asset_url="https://github.com/xemu-project/xemu/releases/download/${tag}/${asset_name}"
asset_path="$downloads_dir/$asset_name"
download_file "$asset_url" "$asset_path" "$force_download"
diff --git a/tests/xbox/guest/CMakeLists.txt b/tests/xbox/guest/CMakeLists.txt
new file mode 100644
index 00000000..363dc34a
--- /dev/null
+++ b/tests/xbox/guest/CMakeLists.txt
@@ -0,0 +1,43 @@
+# Use the vendored GoogleTest sources with only the features nxdk supplies.
+set(_gtest_source "${CMAKE_SOURCE_DIR}/third-party/lizardbyte-common/third-party/googletest/googletest")
+add_library(sunshine_xbox_gtest STATIC "${_gtest_source}/src/gtest-all.cc")
+target_include_directories(sunshine_xbox_gtest SYSTEM PUBLIC
+ "${_gtest_source}/include"
+ "${CMAKE_SOURCE_DIR}/third-party/lizardbyte-common/tests/support/include")
+target_include_directories(sunshine_xbox_gtest SYSTEM PRIVATE "${_gtest_source}")
+target_include_directories(sunshine_xbox_gtest PUBLIC "${CMAKE_SOURCE_DIR}/src/_nxdk_compat/include")
+target_compile_definitions(sunshine_xbox_gtest PUBLIC
+ GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
+ GTEST_HAS_FILE_SYSTEM=0
+ GTEST_HAS_POSIX_RE=0
+ GTEST_HAS_PTHREAD=0
+ GTEST_HAS_SEH=0
+ LIZARDBYTE_COMMON_TESTING_KEEP_GTEST_TEST)
+target_compile_options(sunshine_xbox_gtest PUBLIC
+ "$<$:-include>"
+ "$<$:${CMAKE_CURRENT_SOURCE_DIR}/gtest_port.h>")
+
+add_library(sunshine_xbox_coverage OBJECT
+ time_test.cpp
+ "${CMAKE_SOURCE_DIR}/src/_nxdk_compat/runtime.c")
+target_include_directories(sunshine_xbox_coverage PRIVATE "${CMAKE_SOURCE_DIR}")
+target_link_libraries(sunshine_xbox_coverage PRIVATE sunshine_xbox_gtest)
+# nxdk has no compiler-rt profiling library. Link the serial writer separately
+# so the writer itself stays uninstrumented.
+target_compile_options(sunshine_xbox_coverage PRIVATE -O0 -fprofile-arcs -ftest-coverage)
+
+add_executable(sunshine_xbox_tests main.cpp gcov_serial.c)
+target_link_libraries(sunshine_xbox_tests PRIVATE
+ sunshine_xbox_coverage sunshine_xbox_gtest NXDK::NXDK NXDK::NXDK_CXX)
+
+set(_test_xbe_dir "${CMAKE_CURRENT_BINARY_DIR}/xbe")
+file(MAKE_DIRECTORY "${_test_xbe_dir}")
+add_custom_target(sunshine_xbox_test_iso ALL
+ COMMAND ${_cxbe} "-OUT:${_test_xbe_dir}/default.xbe" "-TITLE:Sunshine Tests"
+ "$"
+ COMMAND ${_extract_xiso} -c "${_test_xbe_dir}" "SunshineTests.iso"
+ BYPRODUCTS "${_test_xbe_dir}/default.xbe" "${CMAKE_BINARY_DIR}/SunshineTests.iso"
+ DEPENDS sunshine_xbox_tests
+ COMMENT "Package the instrumented Original Xbox tests"
+ WORKING_DIRECTORY "${CMAKE_BINARY_DIR}"
+ VERBATIM)
diff --git a/tests/xbox/guest/gcov_serial.c b/tests/xbox/guest/gcov_serial.c
new file mode 100644
index 00000000..71beceee
--- /dev/null
+++ b/tests/xbox/guest/gcov_serial.c
@@ -0,0 +1,134 @@
+/**
+ * @file tests/xbox/guest/gcov_serial.c
+ * @brief Write Clang's gcda records to xemu's serial console after the guest tests.
+ */
+// standard includes
+#include
+#include
+
+// lib includes
+#include
+
+// local includes
+#include "gcov_serial.h"
+
+/** @brief Clang-generated function that writes a translation unit's profile. */
+typedef void (*GcovWriter)(void);
+
+/** @brief Maximum number of translation units instrumented in one guest test XBE. */
+enum {
+ MAX_GCOV_WRITERS = 64
+};
+
+static GcovWriter writers[MAX_GCOV_WRITERS]; ///< Registered at startup by the instrumented objects.
+static size_t writer_count; ///< Number of successfully registered writers.
+static char serial_hex[129]; ///< Holds up to 64 bytes encoded as hex plus a terminator.
+static size_t serial_size; ///< Number of encoded characters currently in the buffer.
+
+/** @brief Send a complete line within the kernel's DbgPrint message size limit. */
+static void flush_serial(void) {
+ if (serial_size != 0) {
+ serial_hex[serial_size] = '\0';
+ DbgPrint("SUNSHINE_GCOV_DATA %s\r\n", serial_hex);
+ serial_size = 0;
+ }
+}
+
+/**
+ * @brief Append one little-endian word to the hex stream for the current gcda file.
+ * @param value Word to append.
+ */
+static void write_word(uint32_t value) {
+ static const char hex[] = "0123456789abcdef";
+ for (unsigned int byte = 0; byte < 4; ++byte) {
+ serial_hex[serial_size++] = hex[(value >> 4) & 0xf];
+ serial_hex[serial_size++] = hex[value & 0xf];
+ value >>= 8;
+ }
+ if (serial_size == sizeof(serial_hex) - 1) {
+ flush_serial();
+ }
+}
+
+/**
+ * @brief Register a write callback from Clang's gcov initializer.
+ * @param writeout Coverage writer for one instrumented translation unit.
+ * @param reset Counter reset callback, unused for a single test run.
+ */
+void llvm_gcov_init(GcovWriter writeout, GcovWriter reset) {
+ (void) reset;
+ if (writer_count == MAX_GCOV_WRITERS) {
+ DbgPrint("SUNSHINE_GCOV_ERROR Too many instrumented translation units\r\n");
+ return;
+ }
+ writers[writer_count++] = writeout;
+}
+
+void sunshine_write_guest_coverage(void) {
+ for (size_t index = 0; index < writer_count; ++index) {
+ writers[index]();
+ }
+}
+
+/**
+ * @brief Begin a gcda stream using the matching compiler's version and checksum.
+ * @param filename Path to the gcda as emitted by Clang.
+ * @param version Encoded gcov format.
+ * @param checksum Checksum shared with the matching gcno file.
+ */
+void llvm_gcda_start_file(const char *filename, uint32_t version, uint32_t checksum) {
+ const char *basename = filename;
+ for (const char *current = filename; *current != '\0'; ++current) {
+ if (*current == '/' || *current == '\\') {
+ basename = current + 1;
+ }
+ }
+ DbgPrint("SUNSHINE_GCOV_BEGIN %s\r\n", basename);
+ write_word(0x67636461); // GCDA magic.
+ write_word(version);
+ write_word(checksum);
+}
+
+/**
+ * @brief Write a gcov function record with both source and CFG checksums.
+ * @param ident Function ID in the notes file.
+ * @param function_checksum Function checksum.
+ * @param cfg_checksum Control-flow graph checksum.
+ */
+void llvm_gcda_emit_function(uint32_t ident, uint32_t function_checksum, uint32_t cfg_checksum) {
+ write_word(0x01000000); // Function tag.
+ write_word(3);
+ write_word(ident);
+ write_word(function_checksum);
+ write_word(cfg_checksum);
+}
+
+/**
+ * @brief Write a gcov arc record containing the guest's execution counts.
+ * @param count Number of counters for the current function.
+ * @param counters Execution counters assigned to the function.
+ */
+void llvm_gcda_emit_arcs(uint32_t count, uint64_t *counters) {
+ write_word(0x01a10000); // Arc counter tag.
+ write_word(count * 2);
+ for (uint32_t index = 0; index < count; ++index) {
+ write_word((uint32_t) counters[index]);
+ write_word((uint32_t) (counters[index] >> 32));
+ }
+}
+
+/** @brief Record one completed run in Clang's gcov object summary. */
+void llvm_gcda_summary_info(void) {
+ write_word(0xa1000000); // Object summary tag.
+ write_word(2);
+ write_word(1); // Runs.
+ write_word(0); // Maximum sum is unused by llvm-cov.
+}
+
+/** @brief Terminate the current gcda and send its final encoded bytes. */
+void llvm_gcda_end_file(void) {
+ write_word(0);
+ write_word(0);
+ flush_serial();
+ DbgPrint("SUNSHINE_GCOV_END\r\n");
+}
diff --git a/tests/xbox/guest/gcov_serial.h b/tests/xbox/guest/gcov_serial.h
new file mode 100644
index 00000000..4da3a191
--- /dev/null
+++ b/tests/xbox/guest/gcov_serial.h
@@ -0,0 +1,16 @@
+/**
+ * @file tests/xbox/guest/gcov_serial.h
+ * @brief Guest coverage export through the Xbox debug serial port.
+ */
+#pragma once
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ /** @brief Send registered translation units' gcov data to the xemu runner. */
+ void sunshine_write_guest_coverage(void);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/tests/xbox/guest/gtest_port.h b/tests/xbox/guest/gtest_port.h
new file mode 100644
index 00000000..d6f3144c
--- /dev/null
+++ b/tests/xbox/guest/gtest_port.h
@@ -0,0 +1,36 @@
+/**
+ * @file tests/xbox/guest/gtest_port.h
+ * @brief Adapt GoogleTest's C library calls to the nxdk test environment.
+ */
+#pragma once
+
+// standard includes
+#include
+#include
+#include
+
+/**
+ * @brief Report that the guest test runner has no interactive terminal.
+ * @param fd Stream descriptor.
+ * @return Zero for every descriptor.
+ */
+inline int isatty(int fd) {
+ (void) fd;
+ return 0;
+}
+
+/**
+ * @brief Compare strings case-insensitively through nxdk's Windows C library.
+ * @param lhs First string.
+ * @param rhs Second string.
+ * @return The ordering returned by nxdk.
+ */
+inline int strcasecmp(const char *lhs, const char *rhs) {
+ return _stricmp(lhs, rhs);
+}
+
+/** @brief Use PDCLib's bounded formatter in the GoogleTest Windows compiler path. */
+#define _snprintf_s(buffer, size, count, ...) snprintf(buffer, size, __VA_ARGS__)
+
+/** @brief Route GoogleTest's optional std::cout diagnostics to nxdk's available stream. */
+#define cout cerr
diff --git a/tests/xbox/guest/main.cpp b/tests/xbox/guest/main.cpp
new file mode 100644
index 00000000..c66f5b9e
--- /dev/null
+++ b/tests/xbox/guest/main.cpp
@@ -0,0 +1,55 @@
+/**
+ * @file tests/xbox/guest/main.cpp
+ * @brief Report GoogleTest results and coverage to the host from the Xbox test XBE.
+ */
+// lib includes
+#include
+#include
+#include
+
+// local includes
+#include "gcov_serial.h"
+
+namespace {
+ /** @brief Emit result records on the kernel's serial console for the test runner. */
+ class SerialResults: public testing::EmptyTestEventListener {
+ /**
+ * @brief Mirror a failing assertion to the serial log for diagnosis.
+ * @param result The assertion's result and diagnostic.
+ */
+ void OnTestPartResult(const testing::TestPartResult &result) override {
+ if (result.failed()) {
+ DbgPrint("Assertion at %s:%d\r\n", result.file_name(), result.line_number());
+ DbgPrint("%.200s\r\n", result.summary());
+ }
+ }
+
+ /**
+ * @brief Emit a result record after each test.
+ * @param info The completed test.
+ */
+ void OnTestEnd(const testing::TestInfo &info) override {
+ const auto *result = info.result();
+ const char *status = result->Skipped() ? "SKIP" : (result->Passed() ? "PASS" : "FAIL");
+ DbgPrint("SUNSHINE_TEST_CASE %s %s %s\r\n", status, info.test_suite_name(), info.name());
+ }
+ };
+} // namespace
+
+/**
+ * @brief Run the instrumented guest tests and report completion after exporting counters.
+ * @return This process waits for the emulator runner to shut down the guest.
+ */
+int main() {
+ testing::InitGoogleTest();
+ auto *tests = testing::UnitTest::GetInstance();
+ auto &listeners = tests->listeners();
+ delete listeners.Release(listeners.default_result_printer());
+ listeners.Append(new SerialResults);
+
+ const int result = RUN_ALL_TESTS();
+ sunshine_write_guest_coverage();
+ DbgPrint("SUNSHINE_TEST_DONE %d %d\r\n", result, tests->test_to_run_count());
+ Sleep(INFINITE);
+ return result;
+}
diff --git a/tests/xbox/guest/time_test.cpp b/tests/xbox/guest/time_test.cpp
new file mode 100644
index 00000000..3b2d9ea4
--- /dev/null
+++ b/tests/xbox/guest/time_test.cpp
@@ -0,0 +1,65 @@
+/**
+ * @file tests/xbox/guest/time_test.cpp
+ * @brief Exercise Sunshine's timing adapters against the Xbox kernel.
+ */
+// test header include
+#include "src/_nxdk_compat/include/sunshine_time.h"
+
+// standard includes
+#include
+
+// lib includes
+#include
+
+// local includes
+#include "src/_nxdk_compat/include/sys/time.h"
+
+/** @brief Convert known timestamps through the Xbox kernel and preserve caller-owned storage. */
+TEST(XboxGuestTime, ConvertsEpochAndLeapDay) {
+ std::tm epoch {};
+ ASSERT_TRUE(sunshine_gmtime(0, epoch));
+ EXPECT_EQ(epoch.tm_year, 70);
+ EXPECT_EQ(epoch.tm_mon, 0);
+ EXPECT_EQ(epoch.tm_mday, 1);
+ EXPECT_EQ(epoch.tm_wday, 4);
+ EXPECT_EQ(epoch.tm_yday, 0);
+
+ std::tm leapDay {};
+ ASSERT_TRUE(sunshine_gmtime(951827696, leapDay));
+ EXPECT_EQ(leapDay.tm_year, 100);
+ EXPECT_EQ(leapDay.tm_mon, 1);
+ EXPECT_EQ(leapDay.tm_mday, 29);
+ EXPECT_EQ(leapDay.tm_hour, 12);
+ EXPECT_EQ(leapDay.tm_min, 34);
+ EXPECT_EQ(leapDay.tm_sec, 56);
+ EXPECT_EQ(leapDay.tm_yday, 59);
+ EXPECT_EQ(epoch.tm_mday, 1);
+}
+
+/** @brief Reject pre-epoch timestamps without changing caller-owned storage. */
+TEST(XboxGuestTime, RejectsNegativeTimestamps) {
+ std::tm result {};
+ result.tm_year = 123;
+ EXPECT_FALSE(sunshine_gmtime(-1, result));
+ EXPECT_EQ(result.tm_year, 123);
+}
+
+/** @brief Read a normalized Unix timestamp from the running Xbox kernel. */
+TEST(XboxGuestTime, ReadsKernelSystemTime) {
+ timeval now {};
+ ASSERT_EQ(gettimeofday(&now, nullptr), 0);
+ EXPECT_GT(now.tv_sec, 0);
+ EXPECT_GE(now.tv_usec, 0);
+ EXPECT_LT(now.tv_usec, 1000000);
+}
+
+/** @brief Reject unsupported gettimeofday arguments without writing to caller storage. */
+TEST(XboxGuestTime, RejectsInvalidTimevalArguments) {
+ timeval now {123, 456};
+ EXPECT_EQ(gettimeofday(nullptr, nullptr), -1);
+ EXPECT_EQ(errno, EINVAL);
+ EXPECT_EQ(gettimeofday(&now, &now), -1);
+ EXPECT_EQ(errno, EINVAL);
+ EXPECT_EQ(now.tv_sec, 123);
+ EXPECT_EQ(now.tv_usec, 456);
+}
From 55776ce4c5906c8fcc40b9476278915fa0e48582 Mon Sep 17 00:00:00 2001
From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com>
Date: Sat, 28 Nov 2026 01:58:00 -0500
Subject: [PATCH 2/9] fix(ci): keep native and xemu coverage collection
independent
---
.github/actions/test-and-report/action.yml | 4 +-
.github/workflows/ci-xbox-original.yml | 6 ++-
scripts/run-xbox-coverage.py | 46 +++++++++++++---------
tests/xbox/guest/gcov_serial.c | 2 +-
tests/xbox/guest/main.cpp | 13 +++++-
5 files changed, 47 insertions(+), 24 deletions(-)
diff --git a/.github/actions/test-and-report/action.yml b/.github/actions/test-and-report/action.yml
index 02ad5b82..184436d0 100644
--- a/.github/actions/test-and-report/action.yml
+++ b/.github/actions/test-and-report/action.yml
@@ -91,12 +91,14 @@ runs:
gcov='xcrun llvm-cov gcov'
fi
gcov_args=(--gcov-executable "${gcov}")
+ coverage_search_root="${PWD}/${CMAKE_BUILD}/tests"
if [[ -n "${GCOV_SOURCE_ROOT}" ]]; then
coverage_root="$(realpath "${GCOV_SOURCE_ROOT}")/"
+ coverage_search_root="${PWD}/${CMAKE_BUILD}"
gcov_args=(--gcov-use-existing-files)
fi
uv run --directory "${GCOV_SOURCE_ROOT:-.}" --project "${PWD}/third-party/lizardbyte-common" \
- --locked --no-sync gcovr "${PWD}/${CMAKE_BUILD}" -r . "${gcov_args[@]}" --filter src \
+ --locked --no-sync gcovr "${coverage_search_root}" -r . "${gcov_args[@]}" --filter src \
--exclude-noncode-lines --exclude-throw-branches --exclude-unreachable-branches --lcov "${raw_report}"
fi
if [[ -n "${coverage_root}" ]]; then
diff --git a/.github/workflows/ci-xbox-original.yml b/.github/workflows/ci-xbox-original.yml
index 62b27df9..831f72cb 100644
--- a/.github/workflows/ci-xbox-original.yml
+++ b/.github/workflows/ci-xbox-original.yml
@@ -99,6 +99,7 @@ jobs:
mingw-w64-ucrt-x86_64-nasm
- name: Build
+ id: build
run: |
chmod +x build.sh
coverage=(--coverage)
@@ -130,7 +131,8 @@ jobs:
codecov-token: ${{ secrets.CODECOV_TOKEN }}
- name: Set up xemu
- if: runner.os == 'Linux'
+ if: ${{ !cancelled() && runner.os == 'Linux' && steps.build.outcome == 'success' }}
+ id: xemu-setup
env:
SUNSHINE_XEMU_TAG: v0.8.139
run: |
@@ -138,7 +140,7 @@ jobs:
bash scripts/setup-xemu.sh
- name: Run Xbox tests and recover guest coverage
- if: runner.os == 'Linux'
+ if: ${{ !cancelled() && steps.xemu-setup.outcome == 'success' }}
id: guest-coverage
env:
APPIMAGE_EXTRACT_AND_RUN: '1'
diff --git a/scripts/run-xbox-coverage.py b/scripts/run-xbox-coverage.py
index bb12f0fb..1d888fce 100644
--- a/scripts/run-xbox-coverage.py
+++ b/scripts/run-xbox-coverage.py
@@ -80,48 +80,59 @@ def write_test_results(transcript, output):
return status or any(result == b"FAIL" for result, _, _ in cases)
-def extract_coverage(transcript, object_dir):
- """Pair complete gcda files from the guest with their build's gcno files."""
- note_files = list(object_dir.rglob("*.gcno"))
- notes = {path.with_suffix(".gcda").name: path for path in note_files}
- if not notes or len(notes) != len(note_files):
- raise ValueError("Expected uniquely named coverage notes from the instrumented build")
+def read_coverage_streams(transcript):
+ """Decode each complete gcda stream framed by the guest's serial records."""
data_files = {}
current = None
for line in transcript.splitlines():
tag, _, payload = line.partition(b" ")
if tag == b"SUNSHINE_GCOV_BEGIN":
current_name = payload.decode("ascii")
- if current is not None or current_name not in notes or current_name in data_files:
+ if current is not None or current_name in data_files:
raise ValueError(f"Unexpected gcda stream for {current_name}")
current = bytearray()
elif tag == b"SUNSHINE_GCOV_DATA" and current is not None:
current.extend(bytes.fromhex(payload.decode("ascii")))
elif tag == b"SUNSHINE_GCOV_END" and current is not None:
- note = notes[current_name]
- if len(current) < 20 or current[:12] != b"adcg" + note.read_bytes()[4:12] or any(current[-8:]):
- raise ValueError(f"Invalid or mismatched gcda stream for {note.name}")
data_files[current_name] = current
current = None
elif tag.startswith(b"SUNSHINE_GCOV_"):
raise ValueError(f"Unexpected coverage record: {line!r}")
- if current is not None or data_files.keys() != notes.keys():
- raise ValueError(f"Incomplete guest coverage, missing: {sorted(notes.keys() - data_files.keys())}")
+ if current is not None:
+ raise ValueError(f"Unfinished gcda stream for {current_name}")
+ return data_files
+
+
+def extract_coverage(transcript, object_dir):
+ """Pair complete gcda files from the guest with their build's gcno files."""
+ note_files = list(object_dir.rglob("*.gcno"))
+ notes = {path.with_suffix(".gcda").name: path for path in note_files}
+ if not notes or len(notes) != len(note_files):
+ raise ValueError("Expected uniquely named coverage notes from the instrumented build")
+ data_files = read_coverage_streams(transcript)
+ if data_files.keys() != notes.keys():
+ missing = sorted(notes.keys() - data_files.keys())
+ unexpected = sorted(data_files.keys() - notes.keys())
+ raise ValueError(f"Guest coverage does not match this build. Missing {missing}, unexpected {unexpected}")
+ for name, data in data_files.items():
+ note_header = notes[name].read_bytes()[:12]
+ if len(data) < 20 or data[:12] != b"adcg" + note_header[4:] or any(data[-8:]):
+ raise ValueError(f"Invalid or mismatched gcda stream for {name}")
for name, data in data_files.items():
notes[name].with_suffix(".gcda").write_bytes(data)
-def generate_report(object_dir, output, llvm_cov):
+def generate_report(object_dir, output):
"""Export LCOV and require executed lines in both Xbox timing adapters."""
report = output / "coverage.info"
temporary = report.with_suffix(".tmp")
source_root = Path(__file__).resolve().parents[1]
subprocess.run(
[
- sys.executable, "-m", "gcovr", str(object_dir), "--root", str(source_root),
- "--gcov-executable", f"{llvm_cov} gcov", "--filter", "src/",
+ sys.executable, "-m", "gcovr", "--root", str(source_root),
+ "--gcov-executable", "llvm-cov gcov", "--filter", "src/",
"--exclude-noncode-lines", "--exclude-throw-branches", "--exclude-unreachable-branches",
- "--lcov", str(temporary),
+ "--lcov", str(temporary), "--", str(object_dir),
],
cwd=source_root,
check=True,
@@ -147,7 +158,6 @@ def main():
"""Collect one guest run from the Xbox child build."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("build", type=Path, help="Xbox child build directory containing SunshineTests.iso")
- parser.add_argument("--llvm-cov", default="llvm-cov", help="llvm-cov matching the nxdk Clang compiler")
args = parser.parse_args()
build = args.build.resolve()
output = build / "xemu-coverage"
@@ -161,7 +171,7 @@ def main():
transcript = run_xemu(build, output)
failure = write_test_results(transcript, output)
extract_coverage(transcript, object_dir)
- generate_report(object_dir, output, args.llvm_cov)
+ generate_report(object_dir, output)
except (OSError, ValueError, subprocess.CalledProcessError) as error:
parser.exit(1, f"{error}. See {output / 'xemu.log'} and {output / 'serial.log'}.\n")
return failure
diff --git a/tests/xbox/guest/gcov_serial.c b/tests/xbox/guest/gcov_serial.c
index 71beceee..a65ea837 100644
--- a/tests/xbox/guest/gcov_serial.c
+++ b/tests/xbox/guest/gcov_serial.c
@@ -108,7 +108,7 @@ void llvm_gcda_emit_function(uint32_t ident, uint32_t function_checksum, uint32_
* @param count Number of counters for the current function.
* @param counters Execution counters assigned to the function.
*/
-void llvm_gcda_emit_arcs(uint32_t count, uint64_t *counters) {
+void llvm_gcda_emit_arcs(uint32_t count, const uint64_t *counters) {
write_word(0x01a10000); // Arc counter tag.
write_word(count * 2);
for (uint32_t index = 0; index < count; ++index) {
diff --git a/tests/xbox/guest/main.cpp b/tests/xbox/guest/main.cpp
index c66f5b9e..533937a6 100644
--- a/tests/xbox/guest/main.cpp
+++ b/tests/xbox/guest/main.cpp
@@ -2,6 +2,9 @@
* @file tests/xbox/guest/main.cpp
* @brief Report GoogleTest results and coverage to the host from the Xbox test XBE.
*/
+// standard includes
+#include
+
// lib includes
#include
#include
@@ -30,7 +33,10 @@ namespace {
*/
void OnTestEnd(const testing::TestInfo &info) override {
const auto *result = info.result();
- const char *status = result->Skipped() ? "SKIP" : (result->Passed() ? "PASS" : "FAIL");
+ const char *status = result->Passed() ? "PASS" : "FAIL";
+ if (result->Skipped()) {
+ status = "SKIP";
+ }
DbgPrint("SUNSHINE_TEST_CASE %s %s %s\r\n", status, info.test_suite_name(), info.name());
}
};
@@ -44,7 +50,10 @@ int main() {
testing::InitGoogleTest();
auto *tests = testing::UnitTest::GetInstance();
auto &listeners = tests->listeners();
- delete listeners.Release(listeners.default_result_printer());
+ std::unique_ptr defaultPrinter {
+ listeners.Release(listeners.default_result_printer())
+ };
+ defaultPrinter.reset();
listeners.Append(new SerialResults);
const int result = RUN_ALL_TESTS();
From 6e8dbda16fe3abdfbe0d093c75d7ea8e012236f3 Mon Sep 17 00:00:00 2001
From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com>
Date: Sat, 28 Nov 2026 02:02:22 -0500
Subject: [PATCH 3/9] fix(ci): install the Linux xemu runtime dependencies
---
.github/workflows/ci-xbox-original.yml | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/.github/workflows/ci-xbox-original.yml b/.github/workflows/ci-xbox-original.yml
index 831f72cb..951efd50 100644
--- a/.github/workflows/ci-xbox-original.yml
+++ b/.github/workflows/ci-xbox-original.yml
@@ -136,7 +136,7 @@ jobs:
env:
SUNSHINE_XEMU_TAG: v0.8.139
run: |
- sudo apt-get install --no-install-recommends -y libgl1-mesa-dri libglx-mesa0 xauth xvfb
+ sudo apt-get install --no-install-recommends -y libgl1-mesa-dri libglx-mesa0 libusb-1.0-0 xauth xvfb
bash scripts/setup-xemu.sh
- name: Run Xbox tests and recover guest coverage
@@ -146,6 +146,7 @@ jobs:
APPIMAGE_EXTRACT_AND_RUN: '1'
LIBGL_ALWAYS_SOFTWARE: '1'
SDL_AUDIO_DRIVER: dummy
+ SDL_VIDEO_DRIVER: x11
run: |
xvfb-run -a -s '-screen 0 1024x768x24' \
uv run --project third-party/lizardbyte-common --locked --no-sync \
From c0aa8c884f62f148305d8987b0f2d657ae0aa9b3 Mon Sep 17 00:00:00 2001
From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com>
Date: Sat, 28 Nov 2026 09:31:52 -0500
Subject: [PATCH 4/9] test(xbox): run the shared suite in xemu on every
toolchain
---
.github/actions/test-and-report/action.yml | 78 ++++++--
.github/workflows/ci-xbox-original.yml | 75 ++------
CMakePresets.json | 10 +-
README.md | 16 +-
build.sh | 15 +-
cmake/sources.cmake | 4 +-
cmake/xbox-build.cmake | 15 +-
scripts/run-xbox-coverage.py | 83 +++++----
scripts/run-xemu.sh | 4 +-
scripts/setup-xemu.sh | 9 +-
src/network/host_pairing.cpp | 8 +-
src/platform/filesystem_utils.cpp | 28 ++-
src/ui/shell_layout.cpp | 12 +-
tests/CMakeLists.txt | 13 +-
tests/sources.cmake | 3 +
tests/support/filesystem_test_utils.h | 168 +++++++++++++++++-
tests/unit/app/file_save_activity_test.cpp | 36 ++--
tests/unit/app/screenshot_library_test.cpp | 57 +++---
tests/unit/app/settings_storage_test.cpp | 16 +-
tests/unit/logging/log_file_test.cpp | 4 +-
tests/unit/network/host_discovery_test.cpp | 3 +
tests/unit/network/host_pairing_test.cpp | 14 +-
tests/unit/network/runtime_network_test.cpp | 5 +
tests/unit/platform/filesystem_utils_test.cpp | 16 +-
tests/unit/splash/splash_layout_test.cpp | 19 +-
.../startup/client_identity_storage_test.cpp | 2 +-
tests/unit/startup/cover_art_cache_test.cpp | 2 +-
tests/unit/startup/host_storage_test.cpp | 4 +-
tests/unit/startup/saved_files_test.cpp | 8 +-
tests/unit/startup/storage_paths_test.cpp | 4 +
tests/xbox/guest/CMakeLists.txt | 27 ++-
tests/xbox/guest/gcov_serial.c | 79 ++++++--
tests/xbox/guest/gcov_serial.h | 12 +-
tests/xbox/guest/gtest_port.h | 6 +
tests/xbox/guest/gtest_serial.cpp | 55 ++++++
tests/xbox/guest/main.cpp | 37 ++--
tests/xbox/guest/time_test.cpp | 18 +-
37 files changed, 682 insertions(+), 283 deletions(-)
create mode 100644 tests/sources.cmake
create mode 100644 tests/xbox/guest/gtest_serial.cpp
diff --git a/.github/actions/test-and-report/action.yml b/.github/actions/test-and-report/action.yml
index 184436d0..b0d91026 100644
--- a/.github/actions/test-and-report/action.yml
+++ b/.github/actions/test-and-report/action.yml
@@ -1,6 +1,6 @@
---
name: Test and report coverage
-description: Publish JUnit and LCOV reports from native tests
+description: Publish JUnit and LCOV reports from native or Xbox guest tests
inputs:
build-dir:
description: Build directory relative to the workspace
@@ -11,6 +11,10 @@ inputs:
gcov-source-root:
description: Retained source directory when CTest and gcov already ran in the build sandbox
required: false
+ xemu-tests:
+ description: Run the Original Xbox test ISO in xemu
+ required: false
+ default: 'false'
test-shell:
description: Shell with the build toolchain on its path
required: false
@@ -23,26 +27,27 @@ runs:
using: composite
steps:
- name: Set up Python
- if: runner.os != 'Windows'
+ if: runner.os != 'Windows' || inputs.xemu-tests == 'true'
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: '3.14'
- name: Set up uv
- if: runner.os != 'Windows'
+ if: runner.os != 'Windows' || inputs.xemu-tests == 'true'
uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
enable-cache: true
cache-dependency-glob: third-party/lizardbyte-common/uv.lock
- name: Install coverage tools
- if: runner.os != 'Windows'
+ if: runner.os != 'Windows' || inputs.xemu-tests == 'true'
shell: ${{ inputs.test-shell }}
run: |
uv sync --project third-party/lizardbyte-common --locked --only-group test-c \
--no-python-downloads --no-install-project
- name: Run unit tests
+ if: inputs.xemu-tests != 'true'
id: tests
shell: ${{ inputs.test-shell }}
env:
@@ -91,14 +96,12 @@ runs:
gcov='xcrun llvm-cov gcov'
fi
gcov_args=(--gcov-executable "${gcov}")
- coverage_search_root="${PWD}/${CMAKE_BUILD}/tests"
if [[ -n "${GCOV_SOURCE_ROOT}" ]]; then
coverage_root="$(realpath "${GCOV_SOURCE_ROOT}")/"
- coverage_search_root="${PWD}/${CMAKE_BUILD}"
gcov_args=(--gcov-use-existing-files)
fi
uv run --directory "${GCOV_SOURCE_ROOT:-.}" --project "${PWD}/third-party/lizardbyte-common" \
- --locked --no-sync gcovr "${coverage_search_root}" -r . "${gcov_args[@]}" --filter src \
+ --locked --no-sync gcovr "${PWD}/${CMAKE_BUILD}" -r . "${gcov_args[@]}" --filter src \
--exclude-noncode-lines --exclude-throw-branches --exclude-unreachable-branches --lcov "${raw_report}"
fi
if [[ -n "${coverage_root}" ]]; then
@@ -123,26 +126,71 @@ runs:
fi
test -s "${report}"
+ - name: Run Xbox tests and recover guest coverage
+ if: inputs.xemu-tests == 'true'
+ id: xemu
+ shell: bash
+ env:
+ CMAKE_BUILD: ${{ inputs.build-dir }}
+ APPIMAGE_EXTRACT_AND_RUN: '1'
+ SDL_AUDIO_DRIVER: dummy
+ run: |
+ tests=(uv run --project third-party/lizardbyte-common --locked --no-sync
+ python scripts/run-xbox-coverage.py "${CMAKE_BUILD}")
+ if [[ "${RUNNER_OS}" == Linux ]]; then
+ LIBGL_ALWAYS_SOFTWARE=1 SDL_VIDEO_DRIVER=x11 \
+ xvfb-run -a -s '-screen 0 1024x768x24' "${tests[@]}"
+ else
+ "${tests[@]}"
+ fi
+
+ - name: Select report paths
+ id: reports
+ if: >-
+ ${{ !cancelled() &&
+ (steps.tests.outcome == 'success' || steps.tests.outcome == 'failure' ||
+ steps.xemu.outcome == 'success' || steps.xemu.outcome == 'failure') }}
+ shell: ${{ inputs.test-shell }}
+ env:
+ CMAKE_BUILD: ${{ inputs.build-dir }}
+ XEMU_TESTS: ${{ inputs.xemu-tests }}
+ run: |
+ if [[ "${XEMU_TESTS}" == true ]]; then
+ {
+ echo "coverage=${CMAKE_BUILD}/xemu-coverage/coverage.info"
+ echo "junit=${CMAKE_BUILD}/xemu-coverage/test_results.xml"
+ echo "logs=${CMAKE_BUILD}/xemu-coverage/*.log"
+ } >> "${GITHUB_OUTPUT}"
+ else
+ {
+ echo "coverage=${CMAKE_BUILD}/coverage.info"
+ echo "junit=${CMAKE_BUILD}/tests/test_results.xml"
+ } >> "${GITHUB_OUTPUT}"
+ fi
+
- name: Upload test and coverage artifacts
- if: ${{ !cancelled() && (steps.tests.outcome == 'success' || steps.tests.outcome == 'failure') }}
+ if: ${{ !cancelled() && steps.reports.outcome == 'success' }}
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: Tests-${{ inputs.platform }}
path: |
- ${{ inputs.build-dir }}/coverage.info
- ${{ inputs.build-dir }}/tests/test_results.xml
+ ${{ steps.reports.outputs.coverage }}
+ ${{ steps.reports.outputs.junit }}
+ ${{ steps.reports.outputs.logs }}
include-hidden-files: ${{ inputs.gcov-source-root != '' }}
if-no-files-found: error
- name: Upload coverage to Codecov
if: >-
- ${{ !cancelled() && steps.coverage.outcome == 'success' &&
+ ${{ !cancelled() && steps.reports.outcome == 'success' &&
+ (steps.coverage.outcome == 'success' ||
+ (inputs.xemu-tests == 'true' && hashFiles(steps.reports.outputs.coverage) != '')) &&
startsWith(github.repository, 'SunshineStream/') }}
uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
with:
disable_search: true
fail_ci_if_error: true
- files: ${{ inputs.build-dir }}/coverage.info
+ files: ${{ steps.reports.outputs.coverage }}
flags: ${{ inputs.platform }}
report_type: coverage
token: ${{ inputs.codecov-token }}
@@ -150,14 +198,14 @@ runs:
- name: Upload test results to Codecov
if: >-
${{ !cancelled() &&
- (steps.tests.outcome == 'success' || steps.tests.outcome == 'failure') &&
- hashFiles(format('{0}/tests/test_results.xml', inputs.build-dir)) != '' &&
+ steps.reports.outcome == 'success' &&
+ hashFiles(steps.reports.outputs.junit) != '' &&
startsWith(github.repository, 'SunshineStream/') }}
uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
with:
disable_search: true
fail_ci_if_error: true
- files: ${{ inputs.build-dir }}/tests/test_results.xml
+ files: ${{ steps.reports.outputs.junit }}
flags: ${{ inputs.platform }}
report_type: test_results
token: ${{ inputs.codecov-token }}
diff --git a/.github/workflows/ci-xbox-original.yml b/.github/workflows/ci-xbox-original.yml
index 951efd50..dfbeea4b 100644
--- a/.github/workflows/ci-xbox-original.yml
+++ b/.github/workflows/ci-xbox-original.yml
@@ -54,6 +54,10 @@ jobs:
)
sunshine_dependencies=(
"patch"
+ # Xvfb brings xauth. Mesa GLX brings the software OpenGL driver.
+ "libglx-mesa0"
+ "libusb-1.0-0"
+ "xvfb"
)
dependencies=("${nxdk_dependencies[@]}" "${sunshine_dependencies[@]}")
sudo apt-get update
@@ -73,6 +77,7 @@ jobs:
)
dependencies=("${nxdk_dependencies[@]}" "${sunshine_dependencies[@]}")
brew install "${dependencies[@]}"
+ echo "$(brew --prefix llvm)/bin" >> "${GITHUB_PATH}"
- name: Setup Dependencies Windows
if: runner.os == 'Windows'
@@ -96,17 +101,13 @@ jobs:
mingw-w64-ucrt-x86_64-llvm
mingw-w64-ucrt-x86_64-llvm-tools
mingw-w64-ucrt-x86_64-make
+ mingw-w64-ucrt-x86_64-mesa
mingw-w64-ucrt-x86_64-nasm
- name: Build
- id: build
run: |
chmod +x build.sh
- coverage=(--coverage)
- if [[ "${RUNNER_OS}" == Linux ]]; then
- coverage+=(--xbox-coverage)
- fi
- ./build.sh --build-dir "${CMAKE_BUILD}" "${coverage[@]}"
+ ./build.sh --build-dir "${CMAKE_BUILD}" --xbox-coverage
# recursively list all files in build directory
ls -R "${CMAKE_BUILD}"
@@ -122,58 +123,20 @@ jobs:
name: Sunshine-client-XboxOG-${{ runner.os }}
path: artifacts/
- - name: Test and report coverage
- uses: ./.github/actions/test-and-report
- with:
- build-dir: ${{ env.CMAKE_BUILD }}
- platform: Xbox-host-${{ runner.os }}
- test-shell: '${{ matrix.shell }}'
- codecov-token: ${{ secrets.CODECOV_TOKEN }}
-
- name: Set up xemu
- if: ${{ !cancelled() && runner.os == 'Linux' && steps.build.outcome == 'success' }}
- id: xemu-setup
- env:
- SUNSHINE_XEMU_TAG: v0.8.139
- run: |
- sudo apt-get install --no-install-recommends -y libgl1-mesa-dri libglx-mesa0 libusb-1.0-0 xauth xvfb
- bash scripts/setup-xemu.sh
+ shell: bash
+ run: bash scripts/setup-xemu.sh
- - name: Run Xbox tests and recover guest coverage
- if: ${{ !cancelled() && steps.xemu-setup.outcome == 'success' }}
- id: guest-coverage
- env:
- APPIMAGE_EXTRACT_AND_RUN: '1'
- LIBGL_ALWAYS_SOFTWARE: '1'
- SDL_AUDIO_DRIVER: dummy
- SDL_VIDEO_DRIVER: x11
+ - name: Set up Windows software OpenGL
+ if: runner.os == 'Windows'
run: |
- xvfb-run -a -s '-screen 0 1024x768x24' \
- uv run --project third-party/lizardbyte-common --locked --no-sync \
- python scripts/run-xbox-coverage.py "${CMAKE_BUILD}/xbox"
+ cp "${MINGW_PREFIX}/bin/"{opengl32,libgallium_wgl}.dll .local/xemu/app/
+ cygpath -w "${MINGW_PREFIX}/bin" >> "${GITHUB_PATH}"
- - name: Upload Xbox guest test and coverage artifacts
- if: >-
- ${{ !cancelled() &&
- (steps.guest-coverage.outcome == 'success' || steps.guest-coverage.outcome == 'failure') }}
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
- with:
- name: Tests-Xbox-guest-xemu
- path: |
- ${{ env.CMAKE_BUILD }}/xbox/xemu-coverage/*.log
- ${{ env.CMAKE_BUILD }}/xbox/xemu-coverage/test_results.xml
- ${{ env.CMAKE_BUILD }}/xbox/xemu-coverage/coverage.info
- if-no-files-found: error
-
- - name: Upload Xbox guest coverage to Codecov
- if: >-
- ${{ !cancelled() && startsWith(github.repository, 'SunshineStream/') &&
- hashFiles(format('{0}/xbox/xemu-coverage/coverage.info', env.CMAKE_BUILD)) != '' }}
- uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
+ - name: Test and report Xbox guest coverage
+ uses: ./.github/actions/test-and-report
with:
- disable_search: true
- fail_ci_if_error: true
- files: ${{ env.CMAKE_BUILD }}/xbox/xemu-coverage/coverage.info
- flags: Xbox-guest-xemu
- report_type: coverage
- token: ${{ secrets.CODECOV_TOKEN }}
+ build-dir: ${{ env.CMAKE_BUILD }}/xbox
+ platform: Xbox-guest-xemu-${{ runner.os }}
+ xemu-tests: 'true'
+ codecov-token: ${{ secrets.CODECOV_TOKEN }}
diff --git a/CMakePresets.json b/CMakePresets.json
index 70da6a4c..3382654f 100644
--- a/CMakePresets.json
+++ b/CMakePresets.json
@@ -36,8 +36,8 @@
},
{
"name": "nxdk-release (ucrt64)",
- "displayName": "Xbox and Host Tests Release (UCRT64)",
- "description": "Build host tests natively with MinGW Makefiles and drive the Xbox target through an internal nxdk child configure",
+ "displayName": "Xbox Release with Documentation (UCRT64)",
+ "description": "Build the documentation and the Xbox ISO through the host build",
"generator": "MinGW Makefiles",
"toolchainFile": "${sourceDir}/cmake/host-ucrt64-clang.cmake",
"binaryDir": "${sourceDir}/cmake-build-release-ucrt64",
@@ -48,7 +48,7 @@
"cacheVariables": {
"BUILD_DOCS": "ON",
"BUILD_NATIVE_CLIENT": "OFF",
- "BUILD_TESTS": "ON",
+ "BUILD_TESTS": "OFF",
"BUILD_XBOX": "ON",
"CMAKE_DEPENDS_USE_COMPILER": "FALSE",
"CMAKE_BUILD_TYPE": "Release"
@@ -56,8 +56,8 @@
},
{
"name": "nxdk-debug (ucrt64)",
- "displayName": "Xbox and Host Tests Debug (UCRT64)",
- "description": "Debug host build with the internal nxdk Xbox child configure enabled",
+ "displayName": "Xbox Debug with Documentation (UCRT64)",
+ "description": "Build the documentation and a debug Xbox ISO through the host build",
"inherits": "nxdk-release (ucrt64)",
"binaryDir": "${sourceDir}/cmake-build-nxdk-debug-ucrt64",
"cacheVariables": {
diff --git a/README.md b/README.md
index d2cd62db..421fe4f9 100644
--- a/README.md
+++ b/README.md
@@ -470,8 +470,8 @@ from the run configuration menu. **Run** builds `sunshine_xbox` and opens the re
`cmake-build-xbox-release-ucrt64/Sunshine.iso` in xemu. To package the ISO on its own, build the
`sunshine_xbox` target. The `sunshine_xbox_executable` target builds the intermediate binary.
-Use **Xbox and Host Tests Release (UCRT64)** when you also need the native test targets or
-documentation. That profile builds the Xbox client in a child directory and puts the ISO at
+Use **Xbox Release with Documentation (UCRT64)** when you also need the documentation.
+That profile builds the Xbox client in a child directory and puts the ISO at
`cmake-build-release-ucrt64/xbox/Sunshine.iso`.
For the first xemu launch, you can either run the shared `Setup portable xemu` configuration or run the Windows wrapper manually:
@@ -513,11 +513,13 @@ uv sync --locked
uv run --locked python scripts/run-xbox-coverage.py cmake-build-release/xbox
```
-The build creates `SunshineTests.iso` beside the release ISO. The runner boots the test disc in xemu
-and recovers test results and coverage counters from the guest's serial console. It pairs the counters
-with the coverage notes from the same build, then writes JUnit, LCOV, and logs under
-`xbox/xemu-coverage/`. Linux CI runs xemu under Xvfb and uploads the report to Codecov with the
-`Xbox-guest-xemu` flag.
+The build creates `SunshineTests.iso` beside the release ISO. It contains the regular unit tests
+from `tests/unit/` and the Xbox cases in `tests/xbox/guest/`. Desktop-only cases use platform guards.
+xemu prints each GoogleTest `[ RUN ]` line as the test starts so the last line identifies where a
+crash or hang occurred. The runner collects counters on
+the second serial port, pairs them with the coverage notes from the same build, and writes JUnit,
+LCOV, and the captured data under `xbox/xemu-coverage/`. Xbox CI runs xemu on each toolchain and
+uploads the results to Codecov under `Xbox-guest-xemu-`.
## Host-native unit tests
diff --git a/build.sh b/build.sh
index 76a7c3a1..9259ccbb 100644
--- a/build.sh
+++ b/build.sh
@@ -4,7 +4,7 @@
set -euo pipefail
usage() {
- echo "Usage: $0 [--build-dir | ] [--clean|clean] [--distclean|distclean] [--coverage] [--xbox-coverage]"
+ echo "Usage: $0 [--build-dir | ] [--clean|clean] [--distclean|distclean] [--xbox-coverage]"
return 0
}
@@ -15,7 +15,6 @@ case "${HOST_SYSTEM}" in
*) BUILD_DIR="cmake-build-release" ;;
esac
CLEAN_BUILD=0
-ENABLE_TEST_COVERAGE=0
ENABLE_XBOX_COVERAGE=OFF
POSITIONAL_BUILD_DIR_SET=0
@@ -38,11 +37,7 @@ while [[ "$#" -gt 0 ]]; do
CLEAN_BUILD=1
shift
;;
- --coverage)
- ENABLE_TEST_COVERAGE=1
- shift
- ;;
- --xbox-coverage)
+ --xbox-coverage|--coverage)
ENABLE_XBOX_COVERAGE=ON
shift
;;
@@ -78,17 +73,13 @@ cmake_configure_args=(
-B "${BUILD_DIR_PATH}"
-DBUILD_DOCS=OFF
-DBUILD_NATIVE_CLIENT=OFF
- -DBUILD_TESTS=ON
+ -DBUILD_TESTS=OFF
-DBUILD_XBOX=ON
-DSUNSHINE_BUILD_XBOX_TESTS="${ENABLE_XBOX_COVERAGE}"
-DCMAKE_DEPENDS_USE_COMPILER=FALSE
-DCMAKE_BUILD_TYPE=Release
)
-if [[ "${ENABLE_TEST_COVERAGE}" -eq 1 ]]; then
- cmake_configure_args+=(-DSUNSHINE_TEST_COVERAGE=ON)
-fi
-
case "${HOST_SYSTEM}" in
MINGW*|MSYS*|CYGWIN*)
if [[ "${MSYSTEM:-}" != "UCRT64" ]]; then
diff --git a/cmake/sources.cmake b/cmake/sources.cmake
index 64f21397..23ea2ac7 100644
--- a/cmake/sources.cmake
+++ b/cmake/sources.cmake
@@ -31,8 +31,8 @@ set(SUNSHINE_TEST_EXCLUDED_SOURCES
"${SUNSHINE_SOURCE_ROOT}/src/ui/svg_assets.cpp"
)
-set(SUNSHINE_HOST_TESTABLE_SOURCES ${SUNSHINE_SOURCES})
-list(REMOVE_ITEM SUNSHINE_HOST_TESTABLE_SOURCES ${SUNSHINE_TEST_EXCLUDED_SOURCES})
+set(SUNSHINE_TESTABLE_SOURCES ${SUNSHINE_SOURCES})
+list(REMOVE_ITEM SUNSHINE_TESTABLE_SOURCES ${SUNSHINE_TEST_EXCLUDED_SOURCES})
if(SUNSHINE_SCREENSHOT_DEMO)
set_property(SOURCE
diff --git a/cmake/xbox-build.cmake b/cmake/xbox-build.cmake
index 4bf127aa..06820b5b 100644
--- a/cmake/xbox-build.cmake
+++ b/cmake/xbox-build.cmake
@@ -65,8 +65,7 @@ target_sources(sunshine_xbox_executable
$
$
)
-target_include_directories(sunshine_xbox_executable
- SYSTEM PRIVATE
+set(SUNSHINE_XBOX_INCLUDE_DIRS
"${CMAKE_CURRENT_SOURCE_DIR}"
"${SUNSHINE_FFMPEG_INCLUDE_DIR}"
"${tomlplusplus_SOURCE_DIR}/include"
@@ -76,8 +75,7 @@ target_include_directories(sunshine_xbox_executable
"${NXDK_DIR}/lib/usb/libusbohci/inc"
"${NXDK_DIR}/lib/usb/libusbohci_xbox"
)
-target_link_libraries(sunshine_xbox_executable
- PUBLIC
+set(SUNSHINE_XBOX_LIBRARIES
moonlight-common-c
${SUNSHINE_FFMPEG_LIBRARIES}
NXDK::NXDK
@@ -91,6 +89,8 @@ target_link_libraries(sunshine_xbox_executable
OpenSSL::Crypto
OpenSSL::SSL
)
+target_include_directories(sunshine_xbox_executable SYSTEM PRIVATE ${SUNSHINE_XBOX_INCLUDE_DIRS})
+target_link_libraries(sunshine_xbox_executable PUBLIC ${SUNSHINE_XBOX_LIBRARIES})
target_compile_options(sunshine_xbox_executable
PRIVATE
${SUNSHINE_COMPILE_OPTIONS}
@@ -99,15 +99,14 @@ target_compile_options(sunshine_xbox_executable
# NASM's freestanding i386 objects do not carry Windows SafeSEH metadata; the
# final Xbox image is packaged as XBE and does not use the Windows PE loader.
target_link_options(sunshine_xbox_executable PRIVATE /safeseh:no)
-target_compile_definitions(sunshine_xbox_executable
- PRIVATE
+set(SUNSHINE_XBOX_COMPILE_DEFINITIONS
XBOX
NXDK
USBH_USE_EXTERNAL_CONFIG="usbh_config_xbox.h"
TOML_EXCEPTIONS=0
- TOML_ENABLE_WINDOWS_COMPAT=0)
-target_compile_definitions(sunshine_xbox_executable PRIVATE
+ TOML_ENABLE_WINDOWS_COMPAT=0
SUNSHINE_INPUT_DIAGNOSTICS=$)
+target_compile_definitions(sunshine_xbox_executable PRIVATE ${SUNSHINE_XBOX_COMPILE_DEFINITIONS})
add_dependencies(sunshine_xbox_executable moonlight-common-c)
if(BUILD_DOCS)
diff --git a/scripts/run-xbox-coverage.py b/scripts/run-xbox-coverage.py
index 1d888fce..d194b95b 100644
--- a/scripts/run-xbox-coverage.py
+++ b/scripts/run-xbox-coverage.py
@@ -16,44 +16,52 @@
GUEST_TEST_DIR = "tests/xbox/guest"
+def wait_for_guest_report(xemu, reports):
+ """Allow steady test and coverage progress while detecting a stalled guest."""
+ timeout = 120
+ deadline = time.monotonic() + timeout
+ run_limit = time.monotonic() + 600
+ size = 0
+ while time.monotonic() < min(deadline, run_limit):
+ if reports.is_file():
+ new_size = reports.stat().st_size
+ if new_size > size:
+ size = new_size
+ deadline = time.monotonic() + timeout
+ transcript = reports.read_bytes()
+ if RESULT.search(transcript):
+ return transcript
+ if xemu.poll() is not None:
+ raise ValueError(f"xemu stopped before guest tests completed (exit {xemu.returncode})")
+ time.sleep(0.25)
+ raise ValueError("Timed out waiting for the Xbox guest tests and coverage")
+
+
def run_xemu(build, output):
- """Wait for a complete guest report, keeping emulator logs on every exit."""
+ """Wait for a complete guest report while xemu writes to the terminal."""
launcher = Path(__file__).with_name("run-xemu.sh").resolve()
shell = shutil.which("bash")
if not shell:
raise ValueError("Bash is needed to run the xemu launcher")
- serial = output / "serial.log"
- with (output / "xemu.log").open("wb") as log:
- command = [
- shell, launcher.as_posix(), "--iso", (build / "SunshineTests.iso").as_posix(),
- "--test-output", output.as_posix(), "--network", "none",
- ]
- with subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=log, stderr=log) as xemu:
- try:
- deadline = time.monotonic() + 120
- while time.monotonic() < deadline:
- if serial.is_file():
- transcript = serial.read_bytes()
- if RESULT.search(transcript):
- return transcript
- if xemu.poll() is not None:
- raise ValueError(f"xemu stopped before guest tests completed (exit {xemu.returncode})")
- time.sleep(0.25)
- raise ValueError("Timed out waiting for guest tests and coverage")
- finally:
- if xemu.poll() is None:
- if os.name == "nt":
- # MSYS2 exec waits for the native xemu process as a child.
- subprocess.run(
- ["taskkill", "/pid", str(xemu.pid), "/t", "/f"],
- stdout=log, stderr=log, check=False,
- )
- else:
- xemu.terminate()
- try:
- xemu.wait(timeout=5)
- except subprocess.TimeoutExpired:
- xemu.kill()
+ reports = output / "coverage.log"
+ command = [
+ shell, launcher.as_posix(), "--iso", (build / "SunshineTests.iso").as_posix(),
+ "--test-output", output.as_posix(), "--network", "none",
+ ]
+ with subprocess.Popen(command, stdin=subprocess.DEVNULL) as xemu:
+ try:
+ return wait_for_guest_report(xemu, reports)
+ finally:
+ if xemu.poll() is None:
+ if os.name == "nt":
+ # MSYS2 exec waits for the native xemu process as a child.
+ subprocess.run(["taskkill", "/pid", str(xemu.pid), "/t", "/f"], check=False)
+ else:
+ xemu.terminate()
+ try:
+ xemu.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ xemu.kill()
def write_test_results(transcript, output):
@@ -68,10 +76,9 @@ def write_test_results(transcript, output):
for result, classname, name in cases:
test = ET.SubElement(suite, "testcase", classname=classname.decode("ascii"), name=name.decode("ascii"))
if result == b"FAIL":
- ET.SubElement(test, "failure", message="See serial.log for assertion output")
+ ET.SubElement(test, "failure", message="See the xemu terminal output for the assertion")
elif result == b"SKIP":
ET.SubElement(test, "skipped")
- print(f"{result.decode()} {classname.decode()}.{name.decode()}")
suite.set("failures", str(sum(result == b"FAIL" for result, _, _ in cases)))
suite.set("skipped", str(sum(result == b"SKIP" for result, _, _ in cases)))
ET.ElementTree(results).write(output / "test_results.xml", encoding="utf-8", xml_declaration=True)
@@ -81,7 +88,7 @@ def write_test_results(transcript, output):
def read_coverage_streams(transcript):
- """Decode each complete gcda stream framed by the guest's serial records."""
+ """Decode each complete gcda stream framed by the guest's debug records."""
data_files = {}
current = None
for line in transcript.splitlines():
@@ -162,7 +169,7 @@ def main():
build = args.build.resolve()
output = build / "xemu-coverage"
output.mkdir(exist_ok=True)
- for name in ("serial.log", "test_results.xml", "coverage.info"):
+ for name in ("coverage.log", "test_results.xml", "coverage.info"):
(output / name).unlink(missing_ok=True)
object_dir = build / GUEST_TEST_DIR / "CMakeFiles/sunshine_xbox_coverage.dir"
for data in object_dir.rglob("*.gcda"):
@@ -173,7 +180,7 @@ def main():
extract_coverage(transcript, object_dir)
generate_report(object_dir, output)
except (OSError, ValueError, subprocess.CalledProcessError) as error:
- parser.exit(1, f"{error}. See {output / 'xemu.log'} and {output / 'serial.log'}.\n")
+ parser.exit(1, f"{error}. See the xemu terminal output and {output / 'coverage.log'}.\n")
return failure
diff --git a/scripts/run-xemu.sh b/scripts/run-xemu.sh
index 61be9f66..84a48e32 100644
--- a/scripts/run-xemu.sh
+++ b/scripts/run-xemu.sh
@@ -9,7 +9,7 @@ usage() {
cat <<'EOF'
Usage: run-xemu.sh [--check] [--build-dir dir] [--iso path] [--network mode] [--tap-ifname name] [--test-output dir] [path]
-Use --test-output to capture serial output and isolate the test guest's disk writes.
+Use --test-output to capture guest coverage records and isolate the test guest's disk writes.
Environment overrides:
SUNSHINE_XEMU_BUILD_DIR
@@ -404,7 +404,7 @@ test_args=()
if [[ -n "$test_output" ]]; then
eeprom_path="$test_output/eeprom.bin"
xemu_config_path="$test_output/xemu.toml"
- serial_args=(-device lpc47m157 -serial "file:$(to_native_path "$test_output/serial.log")")
+ serial_args=(-device lpc47m157 -serial stdio -serial "file:$(to_native_path "$test_output/coverage.log")")
test_args=(-snapshot)
fi
diff --git a/scripts/setup-xemu.sh b/scripts/setup-xemu.sh
index bd161146..cffdd9a6 100644
--- a/scripts/setup-xemu.sh
+++ b/scripts/setup-xemu.sh
@@ -8,7 +8,6 @@ Usage: setup-xemu.sh [--force] [--skip-support-files]
Downloads a portable xemu build into .local/xemu and refreshes launcher manifests.
Existing .local/xemu files are preserved unless --force is passed.
-Set SUNSHINE_XEMU_TAG to select a release instead of the latest version.
EOF
return 0
}
@@ -157,7 +156,7 @@ detect_platform() {
;;
esac
- printf '%s\n%s\n' "$os_name" "$arch_name"
+ printf '%s %s\n' "$os_name" "$arch_name"
}
find_first_file() {
@@ -265,10 +264,8 @@ xemu_exe="$(find_existing_xemu_executable "$app_dir" || true)"
if [[ -n "$xemu_exe" && "$force_download" -eq 0 ]]; then
reused_existing_xemu=1
else
- mapfile -t platform_info < <(detect_platform)
- os_name="${platform_info[0]}"
- arch_name="${platform_info[1]}"
- tag="${SUNSHINE_XEMU_TAG:-$(latest_xemu_tag)}"
+ read -r os_name arch_name < <(detect_platform)
+ tag="$(latest_xemu_tag)"
if [[ -z "$tag" ]]; then
echo 'Could not determine the latest xemu release tag.' >&2
exit 1
diff --git a/src/network/host_pairing.cpp b/src/network/host_pairing.cpp
index ee88c222..31ac348e 100644
--- a/src/network/host_pairing.cpp
+++ b/src/network/host_pairing.cpp
@@ -10,7 +10,6 @@
#include
#include
#include
-#include
#include
#include
#include
@@ -462,7 +461,12 @@ namespace {
*/
std::string stream_key_id(std::string_view ivHex) {
std::uint32_t prefix = 0;
- std::from_chars(ivHex.data(), ivHex.data() + 8, prefix, 16);
+ // The caller validates the IV. nxdk's base-16 from_chars calls an unimplemented log2f().
+ for (const char character : ivHex.substr(0, 8)) {
+ unsigned char digit = 0;
+ hex_value(character, &digit);
+ prefix = (prefix << 4) | digit;
+ }
const std::int64_t keyId = prefix < (1U << 31) ? prefix : static_cast(prefix) - (1LL << 32);
return std::to_string(keyId);
}
diff --git a/src/platform/filesystem_utils.cpp b/src/platform/filesystem_utils.cpp
index 913a26e2..77aa2cbe 100644
--- a/src/platform/filesystem_utils.cpp
+++ b/src/platform/filesystem_utils.cpp
@@ -72,20 +72,42 @@ namespace {
return path;
}
+ /**
+ * @brief Create a missing path component or report why it cannot be created.
+ * @param path Path component to create.
+ * @param errorMessage Receives an optional filesystem error.
+ * @return True when the directory is available.
+ */
bool create_directory_if_missing(const std::string &path, std::string *errorMessage) {
-#if defined(_WIN32) || defined(NXDK)
- if (_mkdir(path.c_str()) == 0 || errno == EEXIST) {
+#ifdef NXDK
+ // nxdk's _mkdir asserts for some kernel errors, including a file used as
+ // a directory. Call Win32 directly so the client can report the failure.
+ if (CreateDirectoryA(path.c_str(), nullptr)) {
+ return true;
+ }
+ const DWORD error = GetLastError();
+ const DWORD attributes = GetFileAttributesA(path.c_str());
+ if (attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
return true;
}
+ if (errorMessage != nullptr) {
+ *errorMessage = "Failed to create directory '" + path + "' (Xbox error " + std::to_string(error) + ").";
+ }
#else
+ #ifdef _WIN32
+ if (_mkdir(path.c_str()) == 0 || errno == EEXIST) {
+ return true;
+ }
+ #else
if (mkdir(path.c_str(), 0750) == 0 || errno == EEXIST) {
return true;
}
-#endif
+ #endif
if (errorMessage != nullptr) {
*errorMessage = "Failed to create directory '" + path + "': " + std::error_code(errno, std::generic_category()).message();
}
+#endif
return false;
}
diff --git a/src/ui/shell_layout.cpp b/src/ui/shell_layout.cpp
index 9ba31c3a..d13b5210 100644
--- a/src/ui/shell_layout.cpp
+++ b/src/ui/shell_layout.cpp
@@ -78,12 +78,22 @@ namespace ui {
};
}
+ /**
+ * @brief Fit a positive window into the desktop layout's minimum logical dimensions.
+ */
ShellRect calculate_desktop_shell_viewport(int width, int height, float displayScale) {
if (width <= 0 || height <= 0) {
return {};
}
const float scale = std::min({displayScale > 0.0f ? displayScale : 1.0f, static_cast(width) / 440.0f, static_cast(height) / 480.0f});
- return {0, 0, static_cast(std::lround(static_cast(width) / scale)), static_cast(std::lround(static_cast(height) / scale))};
+ const float logicalWidth = static_cast(width) / scale;
+ const float logicalHeight = static_cast(height) / scale;
+#ifdef NXDK
+ // The guest tests exercise this shared layout code. nxdk's lroundf is a stub.
+ return {0, 0, static_cast(static_cast(logicalWidth) + 0.5), static_cast(static_cast(logicalHeight) + 0.5)};
+#else
+ return {0, 0, static_cast(std::lround(logicalWidth)), static_cast(std::lround(logicalHeight))};
+#endif
}
DesktopGridColumns calculate_desktop_grid_columns(int width) {
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 4863be4d..8941ab4d 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -6,7 +6,7 @@ cmake_minimum_required(VERSION 3.13)
project(test_sunshine LANGUAGES CXX)
-if(NOT DEFINED SUNSHINE_HOST_TESTABLE_SOURCES)
+if(NOT DEFINED SUNSHINE_TESTABLE_SOURCES)
message(FATAL_ERROR "tests/CMakeLists.txt must be configured from the top-level CMake project")
endif()
@@ -49,17 +49,12 @@ if(WIN32 OR MINGW OR CMAKE_HOST_WIN32)
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) # cmake-lint: disable=C0103
endif()
-file(GLOB_RECURSE TEST_SOURCES CONFIGURE_DEPENDS
- ${CMAKE_SOURCE_DIR}/tests/*.h
- ${CMAKE_SOURCE_DIR}/tests/*.cpp)
-list(FILTER TEST_SOURCES EXCLUDE REGEX "/tests/gpu/")
-list(FILTER TEST_SOURCES EXCLUDE REGEX "/tests/controller/")
-list(FILTER TEST_SOURCES EXCLUDE REGEX "/tests/xbox/")
+include("${CMAKE_CURRENT_SOURCE_DIR}/sources.cmake")
add_executable(${PROJECT_NAME}
- ${TEST_SOURCES}
+ ${SUNSHINE_UNIT_TEST_SOURCES}
"${CMAKE_SOURCE_DIR}/src/_nxdk_compat/ffmpeg_memory.c"
- ${SUNSHINE_HOST_TESTABLE_SOURCES})
+ ${SUNSHINE_TESTABLE_SOURCES})
set_target_properties(${PROJECT_NAME} PROPERTIES CXX_STANDARD 17)
diff --git a/tests/sources.cmake b/tests/sources.cmake
new file mode 100644
index 00000000..9551752e
--- /dev/null
+++ b/tests/sources.cmake
@@ -0,0 +1,3 @@
+# Desktop and Xbox builds share the regular test suite.
+file(GLOB_RECURSE SUNSHINE_UNIT_TEST_SOURCES CONFIGURE_DEPENDS
+ "${CMAKE_SOURCE_DIR}/tests/unit/*.cpp")
diff --git a/tests/support/filesystem_test_utils.h b/tests/support/filesystem_test_utils.h
index c6f5963e..c75968d1 100644
--- a/tests/support/filesystem_test_utils.h
+++ b/tests/support/filesystem_test_utils.h
@@ -5,33 +5,197 @@
#pragma once
// standard includes
+#include
#include
-#include
+#include
#include
+#include
+#ifndef NXDK
+ #include
+#endif
+
+// lib includes
+#ifdef NXDK
+ #include
+#endif
namespace test_support {
+#ifdef NXDK
+ inline constexpr char guest_scratch_directory[] = "E:\\sunshine-tests"; ///< Writable root in the xemu disk snapshot.
+#endif
+
+ /**
+ * @brief Resolve a fixture path on a writable filesystem.
+ * @param name Basename relative to the test's scratch directory.
+ * @return Fixture path for the active platform.
+ */
+ inline std::string scratch_path(const std::string &name) {
+#ifdef NXDK
+ return std::string(guest_scratch_directory) + '\\' + name;
+#else
+ return name;
+#endif
+ }
+
+ /**
+ * @brief Join two fixture path components using the active filesystem's separator.
+ * @param left Existing directory.
+ * @param right Child path.
+ * @return Joined path.
+ */
inline std::string join_path(const std::string &left, const std::string &right) {
+#ifdef NXDK
+ return left + '\\' + right;
+#else
return (std::filesystem::path(left) / right).make_preferred().string();
+#endif
+ }
+
+ /**
+ * @brief Check that the fixture path exists.
+ * @param path Fixture path.
+ * @return True when the file or directory exists.
+ */
+ inline bool exists(const std::string &path) {
+#ifdef NXDK
+ return GetFileAttributesA(path.c_str()) != INVALID_FILE_ATTRIBUTES;
+#else
+ return std::filesystem::exists(path);
+#endif
+ }
+
+ /**
+ * @brief Check whether a fixture path is a directory.
+ * @param path Fixture path.
+ * @return True for an existing directory.
+ */
+ inline bool is_directory(const std::string &path) {
+#ifdef NXDK
+ const auto attributes = GetFileAttributesA(path.c_str());
+ return attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
+#else
+ return std::filesystem::is_directory(path);
+#endif
}
+ /**
+ * @brief Read the size of a fixture file.
+ * @param path Fixture file path.
+ * @return Size in bytes, or UINT64_MAX when the Xbox filesystem cannot read the file metadata.
+ */
+ inline std::uint64_t file_size(const std::string &path) {
+#ifdef NXDK
+ WIN32_FILE_ATTRIBUTE_DATA attributes {};
+ if (!GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &attributes)) {
+ return UINT64_MAX;
+ }
+ return (static_cast(attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
+#else
+ return std::filesystem::file_size(path);
+#endif
+ }
+
+ /**
+ * @brief Extract the final name of a fixture path.
+ * @param path Path to inspect.
+ * @return File or directory name without its parent.
+ */
+ inline std::string file_name(const std::string &path) {
+#ifdef NXDK
+ const auto separator = path.find_last_of("\\/");
+ return separator == std::string::npos ? path : path.substr(separator + 1);
+#else
+ return std::filesystem::path(path).filename().string();
+#endif
+ }
+
+ /** @brief Remove a fixture file, if present. @param path File path. */
inline void remove_if_present(const std::string &path) {
std::remove(path.c_str());
}
+ /** @brief Remove an empty fixture directory, if present. @param path Directory path. */
inline void remove_directory_if_present(const std::string &path) {
+#ifdef NXDK
+ RemoveDirectoryA(path.c_str());
+#else
std::error_code error;
std::filesystem::remove(path, error);
+#endif
+ }
+
+#ifdef NXDK
+ /**
+ * @brief Visit each immediate child of an Xbox fixture directory.
+ * @tparam Visitor Callable receiving the directory record.
+ * @param path Directory to list.
+ * @param visit Called with each file and subdirectory.
+ */
+ template
+ void for_each_entry(const std::string &path, Visitor visit) {
+ WIN32_FIND_DATAA entry {};
+ const auto handle = FindFirstFileA(join_path(path, "*").c_str(), &entry);
+ if (handle == INVALID_HANDLE_VALUE) {
+ return;
+ }
+ do {
+ const std::string_view name(entry.cFileName);
+ if (name != "." && name != "..") {
+ visit(entry);
+ }
+ } while (FindNextFileA(handle, &entry));
+ FindClose(handle);
+ }
+#endif
+
+ /**
+ * @brief Count fixture directory entries.
+ * @param path Directory to list.
+ * @return Number of immediate children.
+ */
+ inline std::size_t entry_count(const std::string &path) {
+#ifdef NXDK
+ std::size_t count = 0;
+ for_each_entry(path, [&count](const WIN32_FIND_DATAA &) {
+ ++count;
+ });
+ return count;
+#else
+ return static_cast(std::distance(std::filesystem::directory_iterator(path), {}));
+#endif
}
+ /** @brief Remove a directory owned by the test fixture. @param path Directory to remove. */
inline void remove_tree_if_present(const std::string &path) {
+#ifdef NXDK
+ for_each_entry(path, [&path](const WIN32_FIND_DATAA &entry) {
+ const auto child = join_path(path, entry.cFileName);
+ if ((entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
+ remove_tree_if_present(child);
+ } else {
+ remove_if_present(child);
+ }
+ });
+ remove_directory_if_present(path);
+#else
std::error_code error;
std::filesystem::remove_all(path, error);
+#endif
}
- inline bool create_directory(const std::filesystem::path &path) {
+ /**
+ * @brief Create a fixture directory if it does not already exist.
+ * @param path Fixture directory.
+ * @return True when the directory is ready for use.
+ */
+ inline bool create_directory(const std::string &path) {
+#ifdef NXDK
+ return CreateDirectoryA(path.c_str(), nullptr) || is_directory(path);
+#else
std::error_code error;
return std::filesystem::create_directory(path, error) || std::filesystem::is_directory(path, error);
+#endif
}
} // namespace test_support
diff --git a/tests/unit/app/file_save_activity_test.cpp b/tests/unit/app/file_save_activity_test.cpp
index 55d589b1..80bbc7b6 100644
--- a/tests/unit/app/file_save_activity_test.cpp
+++ b/tests/unit/app/file_save_activity_test.cpp
@@ -6,7 +6,8 @@
#include "src/app/file_save_activity.h"
// standard includes
-#include
+#include
+#include
#include
// lib includes
@@ -34,23 +35,38 @@ TEST(FileSaveActivityTest, ClearsOnEarlyReturn) {
*/
TEST(FileSaveActivityTest, RemainsActiveUntilTheLastWriterFinishes) {
const auto before = app::file_save_snapshot();
- std::promise entered;
- std::promise finish;
- auto enteredFuture = entered.get_future();
- auto finishFuture = finish.get_future();
- std::thread worker([&entered, &finishFuture] {
+ std::mutex mutex;
+ std::condition_variable changed;
+ bool entered = false;
+ bool finish = false;
+ // nxdk implements condition variables, but its exception runtime cannot
+ // construct the exception state used by std::promise.
+ std::thread worker([&] {
const app::FileSaveActivity saving;
- entered.set_value();
- finishFuture.wait();
+ std::unique_lock lock(mutex);
+ entered = true;
+ changed.notify_one();
+ changed.wait(lock, [&finish] {
+ return finish;
+ });
});
- enteredFuture.wait();
+ {
+ std::unique_lock lock(mutex);
+ changed.wait(lock, [&entered] {
+ return entered;
+ });
+ }
{
const app::FileSaveActivity saving;
EXPECT_TRUE(app::file_save_snapshot().active);
EXPECT_EQ(app::file_save_snapshot().generation, before.generation + 1);
}
EXPECT_TRUE(app::file_save_snapshot().active);
- finish.set_value();
+ {
+ const std::lock_guard lock(mutex);
+ finish = true;
+ }
+ changed.notify_one();
worker.join();
EXPECT_FALSE(app::file_save_snapshot().active);
EXPECT_EQ(app::file_save_snapshot().generation, before.generation + 1);
diff --git a/tests/unit/app/screenshot_library_test.cpp b/tests/unit/app/screenshot_library_test.cpp
index 18f17489..4e0a86a3 100644
--- a/tests/unit/app/screenshot_library_test.cpp
+++ b/tests/unit/app/screenshot_library_test.cpp
@@ -6,7 +6,6 @@
#include "src/app/screenshot_library.h"
// standard includes
-#include
#include
#include
@@ -27,8 +26,8 @@ namespace {
*/
class ScreenshotLibraryTest: public BaseTest { // NOSONAR(cpp:S3656) gtest fixture lifetime
protected:
- std::string root = "screenshot-library-test"; ///< Fixture-owned storage root.
- std::string journal = root + "/index.tsv"; ///< Isolated screenshot index.
+ std::string root = test_support::scratch_path("screenshot-library-test"); ///< Fixture-owned storage root.
+ std::string journal = test_support::join_path(root, "index.tsv"); ///< Isolated screenshot index.
app::ScreenshotSource source {"server-one", "192.0.2.1", 47989, "Office PC", 7, "Game"}; ///< Default capture identity.
/**
@@ -123,22 +122,22 @@ namespace {
EXPECT_TRUE(app::load_screenshots(source, journal).entries.empty());
EXPECT_TRUE(app::load_screenshots(source, journal).error.empty());
std::string error;
- EXPECT_TRUE(app::append_screenshot({source, root + "/old/capture.bmp", 10}, journal, error)) << error;
+ EXPECT_TRUE(app::append_screenshot({source, test_support::join_path(test_support::join_path(root, "old"), "capture.bmp"), 10}, journal, error)) << error;
auto other = source;
other.appId = 8;
- EXPECT_TRUE(app::append_screenshot({other, root + "/other.bmp", 99}, journal, error));
+ EXPECT_TRUE(app::append_screenshot({other, test_support::join_path(root, "other.bmp"), 99}, journal, error));
{
std::ofstream damaged(journal, std::ios::app | std::ios::binary);
damaged << std::string(9000, 'x') << "\ninvalid\n"
<< "1\t20\t7\t47989\tserver-one\tip\thost\tapp\tpartial.bmp";
}
- EXPECT_TRUE(app::append_screenshot({source, root + "/new/first.bmp", 20}, journal, error));
- EXPECT_TRUE(app::append_screenshot({source, root + "/new/second.bmp", 20}, journal, error));
+ EXPECT_TRUE(app::append_screenshot({source, test_support::join_path(test_support::join_path(root, "new"), "first.bmp"), 20}, journal, error));
+ EXPECT_TRUE(app::append_screenshot({source, test_support::join_path(test_support::join_path(root, "new"), "second.bmp"), 20}, journal, error));
auto result = app::load_screenshots(source, journal);
ASSERT_EQ(result.entries.size(), 3U);
- EXPECT_EQ(result.entries[0].path, root + "/new/second.bmp");
- EXPECT_EQ(result.entries[1].path, root + "/new/first.bmp");
- EXPECT_EQ(result.entries[2].path, root + "/old/capture.bmp");
+ EXPECT_EQ(result.entries[0].path, test_support::join_path(test_support::join_path(root, "new"), "second.bmp"));
+ EXPECT_EQ(result.entries[1].path, test_support::join_path(test_support::join_path(root, "new"), "first.bmp"));
+ EXPECT_EQ(result.entries[2].path, test_support::join_path(test_support::join_path(root, "old"), "capture.bmp"));
EXPECT_FALSE(result.error.empty());
{
std::ofstream partial(journal, std::ios::app | std::ios::binary);
@@ -147,7 +146,7 @@ namespace {
EXPECT_EQ(app::load_screenshots(source, journal).entries.size(), 3U);
EXPECT_FALSE(app::append_screenshot({}, journal, error));
EXPECT_FALSE(error.empty());
- EXPECT_FALSE(app::append_screenshot({source, "file.bmp", 30}, journal + "/not-a-directory", error));
+ EXPECT_FALSE(app::append_screenshot({source, "file.bmp", 30}, test_support::join_path(journal, "not-a-directory"), error));
EXPECT_FALSE(error.empty());
EXPECT_FALSE(app::append_screenshot({source, "file.bmp", 30}, root, error));
EXPECT_FALSE(error.empty());
@@ -158,17 +157,17 @@ namespace {
*/
TEST_F(ScreenshotLibraryTest, ChoosesUnusedFatxNames) {
std::string error;
- const std::string first = app::next_screenshot_path(root + "/shots", 1700000000, error);
+ const std::string first = app::next_screenshot_path(test_support::join_path(root, "shots"), 1700000000, error);
ASSERT_FALSE(first.empty()) << error;
{
std::ofstream image(first);
image << "original capture";
}
- const std::string second = app::next_screenshot_path(root + "/shots", 1700000000, error);
+ const std::string second = app::next_screenshot_path(test_support::join_path(root, "shots"), 1700000000, error);
EXPECT_NE(first, second);
- EXPECT_LT(std::filesystem::path(second).filename().string().size(), 43U);
- EXPECT_EQ(std::filesystem::file_size(first), 16U);
- EXPECT_TRUE(app::next_screenshot_path(first + "/blocked", 1, error).empty());
+ EXPECT_LT(test_support::file_name(second).size(), 43U);
+ EXPECT_EQ(test_support::file_size(first), 16U);
+ EXPECT_TRUE(app::next_screenshot_path(test_support::join_path(first, "blocked"), 1, error).empty());
EXPECT_FALSE(error.empty());
EXPECT_TRUE(app::next_screenshot_path(root, -1, error).empty());
EXPECT_FALSE(error.empty());
@@ -250,8 +249,8 @@ namespace {
*/
TEST_F(ScreenshotLibraryTest, DeletesOnlyTheChosenCaptureAndCanReuseItsFilename) {
std::string error;
- const auto first = app::next_screenshot_path(root + "/shots", 10, error);
- const auto otherPath = root + "/other.bmp";
+ const auto first = app::next_screenshot_path(test_support::join_path(root, "shots"), 10, error);
+ const auto otherPath = test_support::join_path(root, "other.bmp");
{
std::ofstream image(first);
image << "first image";
@@ -266,8 +265,8 @@ namespace {
ASSERT_TRUE(app::append_screenshot(record, journal, error));
ASSERT_TRUE(app::append_screenshot({other, otherPath, 11}, journal, error));
ASSERT_TRUE(app::delete_screenshot(record, journal, error)) << error;
- EXPECT_FALSE(std::filesystem::exists(first));
- EXPECT_TRUE(std::filesystem::exists(otherPath));
+ EXPECT_FALSE(test_support::exists(first));
+ EXPECT_TRUE(test_support::exists(otherPath));
EXPECT_TRUE(app::load_screenshots(source, journal).entries.empty());
EXPECT_EQ(app::load_screenshots(other, journal).entries.size(), 1U);
EXPECT_TRUE(app::load_screenshots(source, journal).error.empty());
@@ -293,26 +292,26 @@ namespace {
*/
TEST_F(ScreenshotLibraryTest, ReportsDeletionFailuresWithoutLosingOtherCaptures) {
std::string error;
- const std::filesystem::path first = app::next_screenshot_path(root, 10, error);
+ const std::string first = app::next_screenshot_path(root, 10, error);
{
std::ofstream image(first);
image << "capture";
}
- const app::ScreenshotRecord record {source, first.string(), 10};
+ const app::ScreenshotRecord record {source, first, 10};
ASSERT_TRUE(app::append_screenshot(record, journal, error));
EXPECT_FALSE(app::delete_screenshot({}, journal, error));
EXPECT_FALSE(error.empty());
- EXPECT_FALSE(app::delete_screenshot(record, root + "/missing/index.tsv", error));
- EXPECT_TRUE(std::filesystem::exists(first));
- std::filesystem::create_directory(root + "/protected.bmp");
+ EXPECT_FALSE(app::delete_screenshot(record, test_support::join_path(test_support::join_path(root, "missing"), "index.tsv"), error));
+ EXPECT_TRUE(test_support::exists(first));
+ ASSERT_TRUE(test_support::create_directory(test_support::join_path(root, "protected.bmp")));
{
- std::ofstream child(root + "/protected.bmp/child.txt");
+ std::ofstream child(test_support::join_path(test_support::join_path(root, "protected.bmp"), "child.txt"));
child << "keep";
}
- EXPECT_FALSE(app::delete_screenshot({source, root + "/protected.bmp", 10}, journal, error));
+ EXPECT_FALSE(app::delete_screenshot({source, test_support::join_path(root, "protected.bmp"), 10}, journal, error));
EXPECT_FALSE(error.empty());
- EXPECT_TRUE(std::filesystem::exists(root + "/protected.bmp/child.txt"));
+ EXPECT_TRUE(test_support::exists(test_support::join_path(test_support::join_path(root, "protected.bmp"), "child.txt")));
EXPECT_EQ(app::load_screenshots(source, journal).entries.size(), 1U);
- EXPECT_TRUE(std::filesystem::exists(first));
+ EXPECT_TRUE(test_support::exists(first));
}
} // namespace
diff --git a/tests/unit/app/settings_storage_test.cpp b/tests/unit/app/settings_storage_test.cpp
index 803dc55e..66c384de 100644
--- a/tests/unit/app/settings_storage_test.cpp
+++ b/tests/unit/app/settings_storage_test.cpp
@@ -27,7 +27,7 @@ namespace {
class SettingsStorageTest: public BaseTest { // NOSONAR(cpp:S3656) protected members are required by gtest
protected:
- std::string testDirectory = "settings-storage-test";
+ std::string testDirectory = test_support::scratch_path("settings-storage-test");
std::string settingsPath = test_support::join_path(testDirectory, "moonlight.toml");
void SetUp() override {
@@ -175,7 +175,19 @@ namespace {
/** @brief Accept only the three documented integer values for GPU buffering. */
TEST_F(SettingsStorageTest, RejectsInvalidGpuBufferCounts) {
- for (const auto value : {"-1", "1", "4", "4294967299", "3.0", "'3'", "true"}) {
+ for (const auto value : {
+ "-1",
+ "1",
+ "4",
+ "4294967299",
+ "inf",
+ "'3'",
+ "true",
+#ifndef NXDK
+ // Decimal TOML floats use strtod(), which nxdk leaves unimplemented.
+ "3.0",
+#endif
+ }) {
SCOPED_TRACE(value);
write_text_file(settingsPath, std::string("[streaming]\ngpu_buffer_count = ") + value + "\n");
const auto invalid = app::load_app_settings(settingsPath);
diff --git a/tests/unit/logging/log_file_test.cpp b/tests/unit/logging/log_file_test.cpp
index 60ae8213..d61ce599 100644
--- a/tests/unit/logging/log_file_test.cpp
+++ b/tests/unit/logging/log_file_test.cpp
@@ -29,7 +29,7 @@ namespace {
}
std::string test_log_file_path(const char *name) {
- return test_support::join_path(test_support::join_path("test-output", "logging"), name);
+ return test_support::join_path(test_support::scratch_path(test_support::join_path("test-output", "logging")), name);
}
TEST(LogFileTest, AppendsEntriesAndLoadsRecentLines) {
@@ -148,7 +148,7 @@ namespace {
TEST(LogFileTest, LoadsTheFinalLineEvenWhenTheFileDoesNotEndWithANewline) {
const std::string filePath = test_log_file_path("unterminated.log");
std::remove(filePath.c_str());
- ASSERT_TRUE(test_support::create_directory(test_support::join_path("test-output", "logging")));
+ ASSERT_TRUE(test_support::create_directory(test_support::scratch_path(test_support::join_path("test-output", "logging"))));
write_raw_text_file(filePath, "first line\r\nsecond line\r\nthird line");
const logging::LoadLogFileResult loadedLog = logging::load_log_file(filePath, 0U);
diff --git a/tests/unit/network/host_discovery_test.cpp b/tests/unit/network/host_discovery_test.cpp
index 1db28354..45b605ee 100644
--- a/tests/unit/network/host_discovery_test.cpp
+++ b/tests/unit/network/host_discovery_test.cpp
@@ -41,12 +41,15 @@ namespace {
ScopedHostDiscoveryTestHandler &operator=(const ScopedHostDiscoveryTestHandler &) = delete;
};
+#ifndef NXDK
+ /** @brief Verify the desktop discovery stub when no scripted handler is installed. */
TEST(HostDiscoveryTest, ReturnsAnEmptySuccessfulResultWithoutATestHandler) {
const network::DiscoverHostsResult result = network::discover_hosts(250U);
EXPECT_TRUE(result.hosts.empty());
EXPECT_TRUE(result.errorMessage.empty());
}
+#endif
TEST(HostDiscoveryTest, UsesTheScriptedTestHandlerWhenInstalled) {
ScopedHostDiscoveryTestHandler guard([](uint32_t timeoutMilliseconds) {
diff --git a/tests/unit/network/host_pairing_test.cpp b/tests/unit/network/host_pairing_test.cpp
index 5b6cf990..9852283f 100644
--- a/tests/unit/network/host_pairing_test.cpp
+++ b/tests/unit/network/host_pairing_test.cpp
@@ -8,13 +8,12 @@
// standard includes
#include
#include
-#include
#include
+#include
#include
#include
#include
#include
-#include
#include
// lib includes
@@ -202,11 +201,10 @@ namespace {
EXPECT_EQ(text.size() % 2U, 0U);
bytes.reserve(text.size() / 2U);
for (std::size_t index = 0; index + 1U < text.size(); index += 2U) {
- const std::string encodedByte(text.substr(index, 2U));
- unsigned int value = 0U;
- const std::from_chars_result decodeResult = std::from_chars(encodedByte.data(), encodedByte.data() + encodedByte.size(), value, 16);
- EXPECT_EQ(decodeResult.ec, std::errc());
- EXPECT_EQ(decodeResult.ptr, encodedByte.data() + encodedByte.size());
+ const std::array encodedByte {text[index], text[index + 1], '\0'};
+ char *end = nullptr;
+ const auto value = std::strtoul(encodedByte.data(), &end, 16);
+ EXPECT_EQ(end, encodedByte.data() + 2U);
bytes.push_back(static_cast(value));
}
return bytes;
@@ -773,6 +771,7 @@ namespace {
EXPECT_TRUE(network::resolve_reachable_address({}, serverInfo).empty());
}
+#ifndef NXDK
/**
* @brief Exercise socket creation without the scripted transport or a listening server.
*/
@@ -783,6 +782,7 @@ namespace {
EXPECT_FALSE(network::query_server_info("not-an-ip-address", 47989, nullptr, &serverInfo, &errorMessage));
EXPECT_NE(errorMessage.find("Pairing currently requires a dotted IPv4 host address"), std::string::npos) << errorMessage;
}
+#endif
TEST(HostPairingTest, QueriesServerInfoAcrossFallbackPortsWhenTheDefaultPortFails) {
ScriptedHostPairingHttpHandler handler({
diff --git a/tests/unit/network/runtime_network_test.cpp b/tests/unit/network/runtime_network_test.cpp
index 351df306..7abf137d 100644
--- a/tests/unit/network/runtime_network_test.cpp
+++ b/tests/unit/network/runtime_network_test.cpp
@@ -97,6 +97,10 @@ namespace {
EXPECT_EQ(lines[0], "Gateway: " + std::string(test_support::kTestIpv4Addresses[test_support::kIpRuntimeGateway]));
}
+#ifndef NXDK
+ /**
+ * @brief Desktop builds report the OS-provided network status without initializing nxdk networking.
+ */
TEST(RuntimeNetworkTest, InitializesAndCachesTheHostRuntimeNetworkStatus) {
const network::RuntimeNetworkStatus initialized = network::initialize_runtime_networking();
const network::RuntimeNetworkStatus &cached = network::runtime_network_status();
@@ -112,5 +116,6 @@ namespace {
EXPECT_EQ(cached.summary, initialized.summary);
EXPECT_EQ(cached.initializationCode, initialized.initializationCode);
}
+#endif
} // namespace
diff --git a/tests/unit/platform/filesystem_utils_test.cpp b/tests/unit/platform/filesystem_utils_test.cpp
index 0e53b7dd..0dbe0f9d 100644
--- a/tests/unit/platform/filesystem_utils_test.cpp
+++ b/tests/unit/platform/filesystem_utils_test.cpp
@@ -8,8 +8,6 @@
// standard includes
#include
#include
-#include
-#include
#include
// lib includes
@@ -29,7 +27,7 @@ namespace {
class FilesystemUtilsTest: public BaseTest { // NOSONAR(cpp:S3656) protected members are required by gtest
protected:
- std::string rootDirectory = "filesystem-utils-test";
+ std::string rootDirectory = test_support::scratch_path("filesystem-utils-test");
std::string nestedDirectory = test_support::join_path(test_support::join_path(rootDirectory, "level-one"), "level-two");
std::string filePath = test_support::join_path(nestedDirectory, "payload.bin");
@@ -55,7 +53,7 @@ namespace {
EXPECT_TRUE(platform::ensure_directory_exists({}, &errorMessage)) << errorMessage;
EXPECT_TRUE(platform::ensure_directory_exists(nestedDirectory, &errorMessage)) << errorMessage;
- EXPECT_TRUE(std::filesystem::is_directory(nestedDirectory));
+ EXPECT_TRUE(test_support::is_directory(nestedDirectory));
EXPECT_TRUE(platform::ensure_directory_exists(nestedDirectory, &errorMessage)) << errorMessage;
}
@@ -146,7 +144,7 @@ namespace {
std::string error = "old";
EXPECT_TRUE(platform::create_child_directory(rootDirectory, "New folder", error));
EXPECT_TRUE(error.empty());
- EXPECT_TRUE(std::filesystem::is_directory(test_support::join_path(rootDirectory, "New folder")));
+ EXPECT_TRUE(test_support::is_directory(test_support::join_path(rootDirectory, "New folder")));
EXPECT_FALSE(platform::create_child_directory(rootDirectory, "New folder", error));
EXPECT_FALSE(error.empty());
write_test_file(test_support::join_path(rootDirectory, "file.txt"), "keep");
@@ -154,7 +152,7 @@ namespace {
EXPECT_FALSE(platform::create_child_directory(rootDirectory, "../escape", error));
EXPECT_FALSE(platform::create_child_directory({}, "Folder", error));
EXPECT_FALSE(platform::create_child_directory(test_support::join_path(rootDirectory, "missing"), "Folder", error));
- EXPECT_EQ(std::filesystem::file_size(test_support::join_path(rootDirectory, "file.txt")), 4);
+ EXPECT_EQ(test_support::file_size(test_support::join_path(rootDirectory, "file.txt")), 4);
}
/**
@@ -167,8 +165,8 @@ namespace {
std::string error = "old";
EXPECT_TRUE(platform::directory_is_writable(rootDirectory, error)) << error;
EXPECT_TRUE(error.empty());
- EXPECT_EQ(std::filesystem::file_size(sentinel), 4);
- EXPECT_EQ(std::distance(std::filesystem::directory_iterator(rootDirectory), std::filesystem::directory_iterator {}), 1);
+ EXPECT_EQ(test_support::file_size(sentinel), 4);
+ EXPECT_EQ(test_support::entry_count(rootDirectory), 1);
EXPECT_FALSE(platform::directory_is_writable({}, error));
EXPECT_FALSE(platform::directory_is_writable(sentinel, error));
EXPECT_FALSE(platform::directory_is_writable(test_support::join_path(rootDirectory, "missing"), error));
@@ -186,7 +184,7 @@ namespace {
std::string error;
EXPECT_FALSE(platform::directory_is_writable(rootDirectory, error));
EXPECT_FALSE(error.empty());
- EXPECT_EQ(std::distance(std::filesystem::directory_iterator(rootDirectory), std::filesystem::directory_iterator {}), 32);
+ EXPECT_EQ(test_support::entry_count(rootDirectory), 32);
}
} // namespace
diff --git a/tests/unit/splash/splash_layout_test.cpp b/tests/unit/splash/splash_layout_test.cpp
index a0ca2b09..6e229379 100644
--- a/tests/unit/splash/splash_layout_test.cpp
+++ b/tests/unit/splash/splash_layout_test.cpp
@@ -18,6 +18,19 @@
#include "src/app/stream_bitrate.h"
namespace {
+ /**
+ * @brief Read the active floating-point rounding mode.
+ * @return The rounding mode supported by the active target's math runtime.
+ */
+ int current_rounding_mode() {
+#ifdef NXDK
+ unsigned short controlWord = 0;
+ asm volatile("fnstcw %0" : "=m"(controlWord));
+ return controlWord & 0x0c00;
+#else
+ return std::fegetround();
+#endif
+ }
/**
* @brief Preserve the calling thread's floating-point environment around width regressions.
@@ -31,7 +44,11 @@ namespace {
*/
void SetUp() override {
BaseTest::SetUp();
+#ifdef NXDK
+ ASSERT_EQ(std::feholdexcept(&originalEnvironment), 0);
+#else
ASSERT_EQ(std::fegetenv(&originalEnvironment), 0);
+#endif
}
/**
@@ -57,7 +74,7 @@ namespace {
EXPECT_EQ(splash::calculate_display_width(480, {640, 480, 32, 60}, 0UL), 640);
EXPECT_EQ(splash::calculate_display_width(720, {1280, 720, 32, 60}, 0UL), 960);
EXPECT_EQ(splash::calculate_display_width(480, {720, 480, 32, 60}, VIDEO_WIDESCREEN), 853);
- EXPECT_EQ(std::fegetround(), roundingMode);
+ EXPECT_EQ(current_rounding_mode(), roundingMode);
}
}
}
diff --git a/tests/unit/startup/client_identity_storage_test.cpp b/tests/unit/startup/client_identity_storage_test.cpp
index bba16f96..4037ea85 100644
--- a/tests/unit/startup/client_identity_storage_test.cpp
+++ b/tests/unit/startup/client_identity_storage_test.cpp
@@ -40,7 +40,7 @@ namespace {
BaseTest::TearDown();
}
- std::string testDirectory = "pairing-storage-test";
+ std::string testDirectory = test_support::scratch_path("pairing-storage-test");
std::string nestedIdentityDirectory = test_support::join_path(test_support::join_path(testDirectory, "nested"), "identity");
};
diff --git a/tests/unit/startup/cover_art_cache_test.cpp b/tests/unit/startup/cover_art_cache_test.cpp
index 6ef13c93..84fde572 100644
--- a/tests/unit/startup/cover_art_cache_test.cpp
+++ b/tests/unit/startup/cover_art_cache_test.cpp
@@ -25,7 +25,7 @@ namespace {
BaseTest::TearDown();
}
- std::string testDirectory = "cover-art-cache-test";
+ std::string testDirectory = test_support::scratch_path("cover-art-cache-test");
std::string cacheKey = startup::build_cover_art_cache_key(
"host-uuid-123",
test_support::kTestIpv4Addresses[test_support::kIpHostGridA],
diff --git a/tests/unit/startup/host_storage_test.cpp b/tests/unit/startup/host_storage_test.cpp
index 8d734d30..fef3063c 100644
--- a/tests/unit/startup/host_storage_test.cpp
+++ b/tests/unit/startup/host_storage_test.cpp
@@ -29,8 +29,8 @@ namespace {
BaseTest::TearDown();
}
- std::string testDirectory = "host-storage-test";
- std::string testFilePath = "host-storage-test.tsv";
+ std::string testDirectory = test_support::scratch_path("host-storage-test");
+ std::string testFilePath = test_support::scratch_path("host-storage-test.tsv");
std::string nestedFilePath = test_support::join_path(test_support::join_path(testDirectory, "nested"), "hosts.tsv");
};
diff --git a/tests/unit/startup/saved_files_test.cpp b/tests/unit/startup/saved_files_test.cpp
index 570316c9..c3e86ba7 100644
--- a/tests/unit/startup/saved_files_test.cpp
+++ b/tests/unit/startup/saved_files_test.cpp
@@ -26,7 +26,7 @@ namespace {
class SavedFilesTest: public BaseTest { // NOSONAR(cpp:S3656) protected members are required by gtest
protected:
- std::string testDirectory = "saved-files-test";
+ std::string testDirectory = test_support::scratch_path("saved-files-test");
std::string pairingDirectory = test_support::join_path(testDirectory, "pairing");
std::string hostStoragePath = test_support::join_path(testDirectory, "moonlight-hosts.tsv");
std::string settingsFilePath = test_support::join_path(testDirectory, "moonlight.toml");
@@ -103,13 +103,17 @@ namespace {
EXPECT_EQ(file, nullptr);
}
+ /**
+ * @brief Refuse to delete an unrelated file on the writable test volume.
+ */
TEST_F(SavedFilesTest, RefusesToDeleteFilesOutsideTheManagedStorageSet) {
- const std::string outsidePath = "outside.txt";
+ const std::string outsidePath = test_support::scratch_path("outside.txt");
write_file_bytes(outsidePath, {'x'});
std::string errorMessage;
EXPECT_FALSE(startup::delete_saved_file(outsidePath, &errorMessage, config));
EXPECT_FALSE(errorMessage.empty());
+ EXPECT_TRUE(test_support::exists(outsidePath));
test_support::remove_if_present(outsidePath);
}
diff --git a/tests/unit/startup/storage_paths_test.cpp b/tests/unit/startup/storage_paths_test.cpp
index 9404cd5f..c4454e63 100644
--- a/tests/unit/startup/storage_paths_test.cpp
+++ b/tests/unit/startup/storage_paths_test.cpp
@@ -12,7 +12,11 @@
* @brief Default screenshots live together under save data; custom Xbox and host separators are preserved.
*/
TEST(StoragePathsTest, ResolvesScreenshotFoldersAndTrailingSeparators) {
+#ifdef NXDK
+ EXPECT_EQ(startup::screenshot_storage_path("", "capture.bmp"), startup::title_scoped_storage_root() + "screenshots\\capture.bmp");
+#else
EXPECT_EQ(startup::screenshot_storage_path("", "capture.bmp"), startup::default_storage_path("screenshots") + "/capture.bmp");
+#endif
EXPECT_EQ(startup::screenshot_storage_path("F:\\Screenshots", "capture.bmp"), "F:\\Screenshots\\capture.bmp");
EXPECT_EQ(startup::screenshot_storage_path("F:\\Screenshots\\", "capture.bmp"), "F:\\Screenshots\\capture.bmp");
EXPECT_EQ(startup::screenshot_storage_path("/tmp/screenshots", "capture.bmp"), "/tmp/screenshots/capture.bmp");
diff --git a/tests/xbox/guest/CMakeLists.txt b/tests/xbox/guest/CMakeLists.txt
index 363dc34a..c093de24 100644
--- a/tests/xbox/guest/CMakeLists.txt
+++ b/tests/xbox/guest/CMakeLists.txt
@@ -1,6 +1,6 @@
# Use the vendored GoogleTest sources with only the features nxdk supplies.
set(_gtest_source "${CMAKE_SOURCE_DIR}/third-party/lizardbyte-common/third-party/googletest/googletest")
-add_library(sunshine_xbox_gtest STATIC "${_gtest_source}/src/gtest-all.cc")
+add_library(sunshine_xbox_gtest STATIC gtest_serial.cpp)
target_include_directories(sunshine_xbox_gtest SYSTEM PUBLIC
"${_gtest_source}/include"
"${CMAKE_SOURCE_DIR}/third-party/lizardbyte-common/tests/support/include")
@@ -12,23 +12,36 @@ target_compile_definitions(sunshine_xbox_gtest PUBLIC
GTEST_HAS_POSIX_RE=0
GTEST_HAS_PTHREAD=0
GTEST_HAS_SEH=0
+ LIZARDBYTE_COMMON_TESTING_NO_GLOBAL_ALIASES
LIZARDBYTE_COMMON_TESTING_KEEP_GTEST_TEST)
target_compile_options(sunshine_xbox_gtest PUBLIC
- "$<$:-include>"
- "$<$:${CMAKE_CURRENT_SOURCE_DIR}/gtest_port.h>")
+ "$<$:SHELL:-include \"${CMAKE_CURRENT_SOURCE_DIR}/gtest_port.h\">")
+include("${CMAKE_SOURCE_DIR}/tests/sources.cmake")
add_library(sunshine_xbox_coverage OBJECT
time_test.cpp
+ ${SUNSHINE_TESTABLE_SOURCES}
+ "${CMAKE_SOURCE_DIR}/src/_nxdk_compat/fenv_compat.cpp"
+ "${CMAKE_SOURCE_DIR}/src/_nxdk_compat/ffmpeg_memory.c"
"${CMAKE_SOURCE_DIR}/src/_nxdk_compat/runtime.c")
-target_include_directories(sunshine_xbox_coverage PRIVATE "${CMAKE_SOURCE_DIR}")
-target_link_libraries(sunshine_xbox_coverage PRIVATE sunshine_xbox_gtest)
+target_include_directories(sunshine_xbox_coverage SYSTEM PRIVATE ${SUNSHINE_XBOX_INCLUDE_DIRS})
+target_compile_definitions(sunshine_xbox_coverage PRIVATE ${SUNSHINE_XBOX_COMPILE_DEFINITIONS})
+target_link_libraries(sunshine_xbox_coverage PRIVATE sunshine_xbox_gtest ${SUNSHINE_XBOX_LIBRARIES})
# nxdk has no compiler-rt profiling library. Link the serial writer separately
# so the writer itself stays uninstrumented.
target_compile_options(sunshine_xbox_coverage PRIVATE -O0 -fprofile-arcs -ftest-coverage)
-add_executable(sunshine_xbox_tests main.cpp gcov_serial.c)
+add_executable(sunshine_xbox_tests main.cpp gcov_serial.c ${SUNSHINE_UNIT_TEST_SOURCES}
+ $
+ $)
+target_include_directories(sunshine_xbox_tests SYSTEM PRIVATE ${SUNSHINE_XBOX_INCLUDE_DIRS})
+get_target_property(_coverage_sources sunshine_xbox_coverage SOURCES)
+list(LENGTH _coverage_sources _coverage_source_count)
+target_compile_definitions(sunshine_xbox_tests PRIVATE ${SUNSHINE_XBOX_COMPILE_DEFINITIONS}
+ SUNSHINE_GCOV_MAX_WRITERS=${_coverage_source_count})
target_link_libraries(sunshine_xbox_tests PRIVATE
- sunshine_xbox_coverage sunshine_xbox_gtest NXDK::NXDK NXDK::NXDK_CXX)
+ sunshine_xbox_coverage sunshine_xbox_gtest ${SUNSHINE_XBOX_LIBRARIES})
+target_link_options(sunshine_xbox_tests PRIVATE /safeseh:no)
set(_test_xbe_dir "${CMAKE_CURRENT_BINARY_DIR}/xbe")
file(MAKE_DIRECTORY "${_test_xbe_dir}")
diff --git a/tests/xbox/guest/gcov_serial.c b/tests/xbox/guest/gcov_serial.c
index a65ea837..fd52bb0d 100644
--- a/tests/xbox/guest/gcov_serial.c
+++ b/tests/xbox/guest/gcov_serial.c
@@ -1,13 +1,12 @@
/**
* @file tests/xbox/guest/gcov_serial.c
- * @brief Write Clang's gcda records to xemu's serial console after the guest tests.
+ * @brief Write Clang's gcda records to xemu over COM2 after the guest tests.
*/
// standard includes
+#include
#include
#include
-
-// lib includes
-#include
+#include
// local includes
#include "gcov_serial.h"
@@ -17,7 +16,7 @@ typedef void (*GcovWriter)(void);
/** @brief Maximum number of translation units instrumented in one guest test XBE. */
enum {
- MAX_GCOV_WRITERS = 64
+ MAX_GCOV_WRITERS = SUNSHINE_GCOV_MAX_WRITERS
};
static GcovWriter writers[MAX_GCOV_WRITERS]; ///< Registered at startup by the instrumented objects.
@@ -25,11 +24,71 @@ static size_t writer_count; ///< Number of successfully registered writers.
static char serial_hex[129]; ///< Holds up to 64 bytes encoded as hex plus a terminator.
static size_t serial_size; ///< Number of encoded characters currently in the buffer.
-/** @brief Send a complete line within the kernel's DbgPrint message size limit. */
+/** @brief Xbox port addresses used for the second serial channel. */
+enum {
+ SUPER_IO_INDEX = 0x2e,
+ SUPER_IO_DATA = 0x2f,
+ COVERAGE_UART = 0x2f8
+};
+
+/**
+ * @brief Write one byte to an Xbox I/O port.
+ * @param port I/O port address.
+ * @param value Byte to write.
+ */
+static void write_port(uint16_t port, uint8_t value) {
+ __asm__ volatile("outb %0, %1" : : "a"(value), "Nd"(port));
+}
+
+/**
+ * @brief Set a register in the LPC47M157.
+ * @param reg Index of the configuration register.
+ * @param value Byte to write.
+ */
+static void set_super_io_register(uint8_t reg, uint8_t value) {
+ write_port(SUPER_IO_INDEX, reg);
+ write_port(SUPER_IO_DATA, value);
+}
+
+void sunshine_prepare_guest_records(void) {
+ // Enable the second serial device, using polling so the guest does not need an IRQ handler.
+ write_port(SUPER_IO_INDEX, 0x55); // Enter configuration mode.
+ set_super_io_register(0x07, 0x05); // Select COM2.
+ set_super_io_register(0x60, COVERAGE_UART >> 8);
+ set_super_io_register(0x61, COVERAGE_UART & 0xff);
+ set_super_io_register(0x70, 0);
+ set_super_io_register(0x30, 1);
+ write_port(SUPER_IO_INDEX, 0xaa); // Apply the configuration.
+
+ write_port(COVERAGE_UART + 1, 0); // Disable UART interrupts.
+ write_port(COVERAGE_UART + 3, 0x80); // Select the baud divisor registers.
+ write_port(COVERAGE_UART, 1); // Use 115200 baud.
+ write_port(COVERAGE_UART + 1, 0);
+ write_port(COVERAGE_UART + 3, 3); // Eight data bits, no parity, one stop bit.
+}
+
+void sunshine_write_guest_record(const char *format, ...) {
+ char buffer[256];
+ va_list args;
+ va_start(args, format);
+ const int length = vsnprintf(buffer, sizeof(buffer), format, args);
+ va_end(args);
+ const char *record = length >= 0 && length < (int) sizeof(buffer) ? buffer : "SUNSHINE_GCOV_ERROR Result record exceeds buffer size\r\n";
+ // COM1 stays available to DbgPrint and GoogleTest throughout the run.
+ for (const char *byte = record; *byte != '\0'; ++byte) {
+ uint8_t line_status;
+ do {
+ __asm__ volatile("inb %1, %0" : "=a"(line_status) : "Nd"((uint16_t) (COVERAGE_UART + 5)));
+ } while ((line_status & 0x20) == 0); // Wait for the transmitter to accept the byte.
+ write_port(COVERAGE_UART, (uint8_t) *byte);
+ }
+}
+
+/** @brief Send a complete gcda record line through the coverage serial port. */
static void flush_serial(void) {
if (serial_size != 0) {
serial_hex[serial_size] = '\0';
- DbgPrint("SUNSHINE_GCOV_DATA %s\r\n", serial_hex);
+ sunshine_write_guest_record("SUNSHINE_GCOV_DATA %s\r\n", serial_hex);
serial_size = 0;
}
}
@@ -58,7 +117,7 @@ static void write_word(uint32_t value) {
void llvm_gcov_init(GcovWriter writeout, GcovWriter reset) {
(void) reset;
if (writer_count == MAX_GCOV_WRITERS) {
- DbgPrint("SUNSHINE_GCOV_ERROR Too many instrumented translation units\r\n");
+ sunshine_write_guest_record("SUNSHINE_GCOV_ERROR Too many instrumented translation units\r\n");
return;
}
writers[writer_count++] = writeout;
@@ -83,7 +142,7 @@ void llvm_gcda_start_file(const char *filename, uint32_t version, uint32_t check
basename = current + 1;
}
}
- DbgPrint("SUNSHINE_GCOV_BEGIN %s\r\n", basename);
+ sunshine_write_guest_record("SUNSHINE_GCOV_BEGIN %s\r\n", basename);
write_word(0x67636461); // GCDA magic.
write_word(version);
write_word(checksum);
@@ -130,5 +189,5 @@ void llvm_gcda_end_file(void) {
write_word(0);
write_word(0);
flush_serial();
- DbgPrint("SUNSHINE_GCOV_END\r\n");
+ sunshine_write_guest_record("SUNSHINE_GCOV_END\r\n");
}
diff --git a/tests/xbox/guest/gcov_serial.h b/tests/xbox/guest/gcov_serial.h
index 4da3a191..aeae68cc 100644
--- a/tests/xbox/guest/gcov_serial.h
+++ b/tests/xbox/guest/gcov_serial.h
@@ -1,6 +1,6 @@
/**
* @file tests/xbox/guest/gcov_serial.h
- * @brief Guest coverage export through the Xbox debug serial port.
+ * @brief Export guest coverage and test results through the second serial port.
*/
#pragma once
@@ -8,6 +8,16 @@
extern "C" {
#endif
+ /**
+ * @brief Send a formatted machine-readable record to xemu over COM2.
+ * @param format Printf format string.
+ * @param ... Format arguments.
+ */
+ void sunshine_write_guest_record(const char *format, ...);
+
+ /** @brief Configure the second LPC47M157 serial port for coverage records. */
+ void sunshine_prepare_guest_records(void);
+
/** @brief Send registered translation units' gcov data to the xemu runner. */
void sunshine_write_guest_coverage(void);
diff --git a/tests/xbox/guest/gtest_port.h b/tests/xbox/guest/gtest_port.h
index d6f3144c..3ed8400b 100644
--- a/tests/xbox/guest/gtest_port.h
+++ b/tests/xbox/guest/gtest_port.h
@@ -34,3 +34,9 @@ inline int strcasecmp(const char *lhs, const char *rhs) {
/** @brief Route GoogleTest's optional std::cout diagnostics to nxdk's available stream. */
#define cout cerr
+
+// Shared test fixtures can run without the host-only stdio capture hooks.
+#include
+
+/** @brief GoogleTest fixture base for shared tests running in the Xbox guest. */
+using BaseTest = ::testing::Test;
diff --git a/tests/xbox/guest/gtest_serial.cpp b/tests/xbox/guest/gtest_serial.cpp
new file mode 100644
index 00000000..d5346e66
--- /dev/null
+++ b/tests/xbox/guest/gtest_serial.cpp
@@ -0,0 +1,55 @@
+/**
+ * @file tests/xbox/guest/gtest_serial.cpp
+ * @brief Route GoogleTest's native result printer through the Xbox debug console.
+ */
+// standard includes
+#include
+#include
+#include
+
+// lib includes
+#include
+
+namespace testing {
+ /**
+ * @brief Send formatted test output through DbgPrint in bounded chunks.
+ * @param format Printf format string.
+ * @param arguments Format arguments.
+ * @return Number of characters formatted, or a negative formatting error.
+ */
+ static int vprintf(const char *format, std::va_list arguments) {
+ std::va_list copy;
+ va_copy(copy, arguments);
+ const int count = std::vsnprintf(nullptr, 0, format, copy);
+ va_end(copy);
+ if (count <= 0) {
+ return count;
+ }
+
+ std::string output(static_cast(count) + 1, '\0');
+ std::vsnprintf(output.data(), output.size(), format, arguments);
+ constexpr int chunkSize = 200;
+ for (int offset = 0; offset < count; offset += chunkSize) {
+ DbgPrint("%.*s", chunkSize, output.c_str() + offset);
+ }
+ return count;
+ }
+
+ /**
+ * @brief Route GoogleTest's standard output to the debug serial console.
+ * @param format Printf format string.
+ * @param ... Format arguments.
+ * @return Number of characters formatted, or a negative formatting error.
+ */
+ static int printf(const char *format, ...) {
+ std::va_list arguments;
+ va_start(arguments, format);
+ const int count = testing::vprintf(format, arguments);
+ va_end(arguments);
+ return count;
+ }
+} // namespace testing
+
+// Include GoogleTest after the adapters so its unqualified printf calls use the
+// debug console. nxdk's standard output stream has no backing console handle.
+#include "src/gtest-all.cc"
diff --git a/tests/xbox/guest/main.cpp b/tests/xbox/guest/main.cpp
index 533937a6..9adf3eb2 100644
--- a/tests/xbox/guest/main.cpp
+++ b/tests/xbox/guest/main.cpp
@@ -2,9 +2,6 @@
* @file tests/xbox/guest/main.cpp
* @brief Report GoogleTest results and coverage to the host from the Xbox test XBE.
*/
-// standard includes
-#include
-
// lib includes
#include
#include
@@ -12,21 +9,14 @@
// local includes
#include "gcov_serial.h"
+#include "src/platform/filesystem_utils.h"
+
+// test includes
+#include "tests/support/filesystem_test_utils.h"
namespace {
- /** @brief Emit result records on the kernel's serial console for the test runner. */
+ /** @brief Emit result records on COM2 for the test runner. */
class SerialResults: public testing::EmptyTestEventListener {
- /**
- * @brief Mirror a failing assertion to the serial log for diagnosis.
- * @param result The assertion's result and diagnostic.
- */
- void OnTestPartResult(const testing::TestPartResult &result) override {
- if (result.failed()) {
- DbgPrint("Assertion at %s:%d\r\n", result.file_name(), result.line_number());
- DbgPrint("%.200s\r\n", result.summary());
- }
- }
-
/**
* @brief Emit a result record after each test.
* @param info The completed test.
@@ -37,7 +27,7 @@ namespace {
if (result->Skipped()) {
status = "SKIP";
}
- DbgPrint("SUNSHINE_TEST_CASE %s %s %s\r\n", status, info.test_suite_name(), info.name());
+ sunshine_write_guest_record("SUNSHINE_TEST_CASE %s %s %s\r\n", status, info.test_suite_name(), info.name());
}
};
} // namespace
@@ -47,18 +37,19 @@ namespace {
* @return This process waits for the emulator runner to shut down the guest.
*/
int main() {
+ sunshine_prepare_guest_records();
+ if (!platform::ensure_directory_exists(test_support::guest_scratch_directory)) {
+ DbgPrint("Failed to create the Xbox guest test directory\r\n");
+ sunshine_write_guest_record("SUNSHINE_TEST_DONE 1 0\r\n");
+ return 1;
+ }
testing::InitGoogleTest();
auto *tests = testing::UnitTest::GetInstance();
- auto &listeners = tests->listeners();
- std::unique_ptr defaultPrinter {
- listeners.Release(listeners.default_result_printer())
- };
- defaultPrinter.reset();
- listeners.Append(new SerialResults);
+ tests->listeners().Append(new SerialResults);
const int result = RUN_ALL_TESTS();
sunshine_write_guest_coverage();
- DbgPrint("SUNSHINE_TEST_DONE %d %d\r\n", result, tests->test_to_run_count());
+ sunshine_write_guest_record("SUNSHINE_TEST_DONE %d %d\r\n", result, tests->test_to_run_count());
Sleep(INFINITE);
return result;
}
diff --git a/tests/xbox/guest/time_test.cpp b/tests/xbox/guest/time_test.cpp
index 3b2d9ea4..b2b943f6 100644
--- a/tests/xbox/guest/time_test.cpp
+++ b/tests/xbox/guest/time_test.cpp
@@ -2,17 +2,18 @@
* @file tests/xbox/guest/time_test.cpp
* @brief Exercise Sunshine's timing adapters against the Xbox kernel.
*/
-// test header include
-#include "src/_nxdk_compat/include/sunshine_time.h"
+#if defined(NXDK)
+ // test header include
+ #include "src/_nxdk_compat/include/sunshine_time.h"
-// standard includes
-#include
+ // standard includes
+ #include
-// lib includes
-#include
+ // lib includes
+ #include
-// local includes
-#include "src/_nxdk_compat/include/sys/time.h"
+ // local includes
+ #include "src/_nxdk_compat/include/sys/time.h"
/** @brief Convert known timestamps through the Xbox kernel and preserve caller-owned storage. */
TEST(XboxGuestTime, ConvertsEpochAndLeapDay) {
@@ -63,3 +64,4 @@ TEST(XboxGuestTime, RejectsInvalidTimevalArguments) {
EXPECT_EQ(now.tv_sec, 123);
EXPECT_EQ(now.tv_usec, 456);
}
+#endif
From bc7b35e54da83efad9cee7bdafab78fb5acce844 Mon Sep 17 00:00:00 2001
From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com>
Date: Sat, 28 Nov 2026 09:50:39 -0500
Subject: [PATCH 5/9] fix(xbox): connect guest stdout and require C++17 for
tests
---
tests/support/filesystem_test_utils.h | 6 +-
tests/unit/app/file_save_activity_test.cpp | 2 +-
tests/unit/platform/filesystem_utils_test.cpp | 16 ++++++
tests/xbox/guest/CMakeLists.txt | 11 +++-
tests/xbox/guest/console_serial.c | 40 ++++++++++++++
tests/xbox/guest/gcov_serial.c | 35 +++++-------
tests/xbox/guest/gcov_serial.h | 7 +--
tests/xbox/guest/gtest_serial.cpp | 55 -------------------
tests/xbox/guest/main.cpp | 11 +++-
9 files changed, 94 insertions(+), 89 deletions(-)
create mode 100644 tests/xbox/guest/console_serial.c
delete mode 100644 tests/xbox/guest/gtest_serial.cpp
diff --git a/tests/support/filesystem_test_utils.h b/tests/support/filesystem_test_utils.h
index c75968d1..90547ba9 100644
--- a/tests/support/filesystem_test_utils.h
+++ b/tests/support/filesystem_test_utils.h
@@ -189,13 +189,15 @@ namespace test_support {
* @param path Fixture directory.
* @return True when the directory is ready for use.
*/
- inline bool create_directory(const std::string &path) {
#ifdef NXDK
+ inline bool create_directory(const std::string &path) {
return CreateDirectoryA(path.c_str(), nullptr) || is_directory(path);
+ }
#else
+ inline bool create_directory(const std::filesystem::path &path) {
std::error_code error;
return std::filesystem::create_directory(path, error) || std::filesystem::is_directory(path, error);
-#endif
}
+#endif
} // namespace test_support
diff --git a/tests/unit/app/file_save_activity_test.cpp b/tests/unit/app/file_save_activity_test.cpp
index 80bbc7b6..a176aa99 100644
--- a/tests/unit/app/file_save_activity_test.cpp
+++ b/tests/unit/app/file_save_activity_test.cpp
@@ -41,7 +41,7 @@ TEST(FileSaveActivityTest, RemainsActiveUntilTheLastWriterFinishes) {
bool finish = false;
// nxdk implements condition variables, but its exception runtime cannot
// construct the exception state used by std::promise.
- std::thread worker([&] {
+ std::thread worker([&changed, &entered, &finish, &mutex] {
const app::FileSaveActivity saving;
std::unique_lock lock(mutex);
entered = true;
diff --git a/tests/unit/platform/filesystem_utils_test.cpp b/tests/unit/platform/filesystem_utils_test.cpp
index 0dbe0f9d..d609b8e5 100644
--- a/tests/unit/platform/filesystem_utils_test.cpp
+++ b/tests/unit/platform/filesystem_utils_test.cpp
@@ -57,6 +57,22 @@ namespace {
EXPECT_TRUE(platform::ensure_directory_exists(nestedDirectory, &errorMessage)) << errorMessage;
}
+#ifdef NXDK
+ /**
+ * @brief A missing directory on the Xbox disc reports an error even when the caller omits diagnostics.
+ */
+ TEST(FolderPickerFilesystemTest, RefusesToCreateDirectoriesOnTheReadOnlyXboxDisc) {
+ ASSERT_TRUE(test_support::exists("D:\\default.xbe"));
+ const std::string directory = "D:\\sunshine-tests-output";
+ std::string error;
+
+ EXPECT_FALSE(platform::ensure_directory_exists(directory, &error));
+ EXPECT_FALSE(error.empty());
+ EXPECT_FALSE(platform::ensure_directory_exists(directory));
+ EXPECT_FALSE(test_support::exists(directory));
+ }
+#endif
+
TEST_F(FilesystemUtilsTest, ReportsRegularFileSizesAndRejectsDirectoriesOrMissingPaths) {
ASSERT_TRUE(platform::ensure_directory_exists(nestedDirectory, nullptr));
write_test_file(filePath, "payload");
diff --git a/tests/xbox/guest/CMakeLists.txt b/tests/xbox/guest/CMakeLists.txt
index c093de24..eb38d1ef 100644
--- a/tests/xbox/guest/CMakeLists.txt
+++ b/tests/xbox/guest/CMakeLists.txt
@@ -1,6 +1,6 @@
# Use the vendored GoogleTest sources with only the features nxdk supplies.
set(_gtest_source "${CMAKE_SOURCE_DIR}/third-party/lizardbyte-common/third-party/googletest/googletest")
-add_library(sunshine_xbox_gtest STATIC gtest_serial.cpp)
+add_library(sunshine_xbox_gtest STATIC "${_gtest_source}/src/gtest-all.cc")
target_include_directories(sunshine_xbox_gtest SYSTEM PUBLIC
"${_gtest_source}/include"
"${CMAKE_SOURCE_DIR}/third-party/lizardbyte-common/tests/support/include")
@@ -15,6 +15,8 @@ target_compile_definitions(sunshine_xbox_gtest PUBLIC
LIZARDBYTE_COMMON_TESTING_NO_GLOBAL_ALIASES
LIZARDBYTE_COMMON_TESTING_KEEP_GTEST_TEST)
target_compile_options(sunshine_xbox_gtest PUBLIC
+ # The stock nxdk wrapper can lead CMake to probe the host's C++ default on Windows.
+ $<$:-std=gnu++17>
"$<$:SHELL:-include \"${CMAKE_CURRENT_SOURCE_DIR}/gtest_port.h\">")
include("${CMAKE_SOURCE_DIR}/tests/sources.cmake")
@@ -31,7 +33,12 @@ target_link_libraries(sunshine_xbox_coverage PRIVATE sunshine_xbox_gtest ${SUNSH
# so the writer itself stays uninstrumented.
target_compile_options(sunshine_xbox_coverage PRIVATE -O0 -fprofile-arcs -ftest-coverage)
-add_executable(sunshine_xbox_tests main.cpp gcov_serial.c ${SUNSHINE_UNIT_TEST_SOURCES}
+# Retain nxdk's regular file flushing while redirecting the guest's standard streams.
+set(_nxdk_flush "${NXDK_DIR}/lib/pdclib/platform/xbox/functions/_PDCLIB/_PDCLIB_flushbuffer.c")
+set_source_files_properties("${_nxdk_flush}" PROPERTIES
+ COMPILE_DEFINITIONS "_PDCLIB_flushbuffer=sunshine_pdclib_flush_file")
+add_executable(sunshine_xbox_tests main.cpp console_serial.c gcov_serial.c ${SUNSHINE_UNIT_TEST_SOURCES}
+ "${_nxdk_flush}"
$
$)
target_include_directories(sunshine_xbox_tests SYSTEM PRIVATE ${SUNSHINE_XBOX_INCLUDE_DIRS})
diff --git a/tests/xbox/guest/console_serial.c b/tests/xbox/guest/console_serial.c
new file mode 100644
index 00000000..d68dc048
--- /dev/null
+++ b/tests/xbox/guest/console_serial.c
@@ -0,0 +1,40 @@
+/**
+ * @file tests/xbox/guest/console_serial.c
+ * @brief Connect the Xbox test XBE's standard streams to xemu's debug serial console.
+ */
+// standard includes
+#include
+
+// lib includes
+#include
+#include
+
+/**
+ * @brief Flush a regular file stream through the original nxdk implementation.
+ * @param stream PDCLib stream to flush.
+ * @return Zero on success or EOF on failure.
+ */
+int sunshine_pdclib_flush_file(FILE *stream);
+
+/**
+ * @brief Flush stdout and stderr to the Xbox debug port and preserve normal file I/O.
+ * @param stream PDCLib stream to flush.
+ * @return Zero on success or EOF on failure.
+ */
+int _PDCLIB_flushbuffer(FILE *stream) {
+ // nxdk starts the standard output streams without backing file handles.
+ if (stream != stdout && stream != stderr) {
+ return sunshine_pdclib_flush_file(stream);
+ }
+
+ size_t offset = 0;
+ while (offset < stream->bufidx) {
+ const size_t remaining = stream->bufidx - offset;
+ const int length = remaining > 200 ? 200 : (int) remaining;
+ DbgPrint("%.*s", length, stream->buffer + offset);
+ offset += length;
+ }
+ stream->pos.offset += stream->bufidx;
+ stream->bufidx = 0;
+ return 0;
+}
diff --git a/tests/xbox/guest/gcov_serial.c b/tests/xbox/guest/gcov_serial.c
index fd52bb0d..0824e6f3 100644
--- a/tests/xbox/guest/gcov_serial.c
+++ b/tests/xbox/guest/gcov_serial.c
@@ -3,10 +3,8 @@
* @brief Write Clang's gcda records to xemu over COM2 after the guest tests.
*/
// standard includes
-#include
#include
#include
-#include
// local includes
#include "gcov_serial.h"
@@ -14,12 +12,7 @@
/** @brief Clang-generated function that writes a translation unit's profile. */
typedef void (*GcovWriter)(void);
-/** @brief Maximum number of translation units instrumented in one guest test XBE. */
-enum {
- MAX_GCOV_WRITERS = SUNSHINE_GCOV_MAX_WRITERS
-};
-
-static GcovWriter writers[MAX_GCOV_WRITERS]; ///< Registered at startup by the instrumented objects.
+static GcovWriter writers[SUNSHINE_GCOV_MAX_WRITERS + 1]; ///< Registered at startup, with a null sentinel at the end.
static size_t writer_count; ///< Number of successfully registered writers.
static char serial_hex[129]; ///< Holds up to 64 bytes encoded as hex plus a terminator.
static size_t serial_size; ///< Number of encoded characters currently in the buffer.
@@ -67,15 +60,9 @@ void sunshine_prepare_guest_records(void) {
write_port(COVERAGE_UART + 3, 3); // Eight data bits, no parity, one stop bit.
}
-void sunshine_write_guest_record(const char *format, ...) {
- char buffer[256];
- va_list args;
- va_start(args, format);
- const int length = vsnprintf(buffer, sizeof(buffer), format, args);
- va_end(args);
- const char *record = length >= 0 && length < (int) sizeof(buffer) ? buffer : "SUNSHINE_GCOV_ERROR Result record exceeds buffer size\r\n";
+void sunshine_write_guest_text(const char *text) {
// COM1 stays available to DbgPrint and GoogleTest throughout the run.
- for (const char *byte = record; *byte != '\0'; ++byte) {
+ for (const char *byte = text; *byte != '\0'; ++byte) {
uint8_t line_status;
do {
__asm__ volatile("inb %1, %0" : "=a"(line_status) : "Nd"((uint16_t) (COVERAGE_UART + 5)));
@@ -88,7 +75,9 @@ void sunshine_write_guest_record(const char *format, ...) {
static void flush_serial(void) {
if (serial_size != 0) {
serial_hex[serial_size] = '\0';
- sunshine_write_guest_record("SUNSHINE_GCOV_DATA %s\r\n", serial_hex);
+ sunshine_write_guest_text("SUNSHINE_GCOV_DATA ");
+ sunshine_write_guest_text(serial_hex);
+ sunshine_write_guest_text("\r\n");
serial_size = 0;
}
}
@@ -116,15 +105,15 @@ static void write_word(uint32_t value) {
*/
void llvm_gcov_init(GcovWriter writeout, GcovWriter reset) {
(void) reset;
- if (writer_count == MAX_GCOV_WRITERS) {
- sunshine_write_guest_record("SUNSHINE_GCOV_ERROR Too many instrumented translation units\r\n");
+ if (writer_count + 1 == sizeof(writers) / sizeof(writers[0])) {
+ sunshine_write_guest_text("SUNSHINE_GCOV_ERROR Too many instrumented translation units\r\n");
return;
}
writers[writer_count++] = writeout;
}
void sunshine_write_guest_coverage(void) {
- for (size_t index = 0; index < writer_count; ++index) {
+ for (size_t index = 0; writers[index] != NULL; ++index) {
writers[index]();
}
}
@@ -142,7 +131,9 @@ void llvm_gcda_start_file(const char *filename, uint32_t version, uint32_t check
basename = current + 1;
}
}
- sunshine_write_guest_record("SUNSHINE_GCOV_BEGIN %s\r\n", basename);
+ sunshine_write_guest_text("SUNSHINE_GCOV_BEGIN ");
+ sunshine_write_guest_text(basename);
+ sunshine_write_guest_text("\r\n");
write_word(0x67636461); // GCDA magic.
write_word(version);
write_word(checksum);
@@ -189,5 +180,5 @@ void llvm_gcda_end_file(void) {
write_word(0);
write_word(0);
flush_serial();
- sunshine_write_guest_record("SUNSHINE_GCOV_END\r\n");
+ sunshine_write_guest_text("SUNSHINE_GCOV_END\r\n");
}
diff --git a/tests/xbox/guest/gcov_serial.h b/tests/xbox/guest/gcov_serial.h
index aeae68cc..28c95beb 100644
--- a/tests/xbox/guest/gcov_serial.h
+++ b/tests/xbox/guest/gcov_serial.h
@@ -9,11 +9,10 @@ extern "C" {
#endif
/**
- * @brief Send a formatted machine-readable record to xemu over COM2.
- * @param format Printf format string.
- * @param ... Format arguments.
+ * @brief Send part or all of a machine-readable record to xemu over COM2.
+ * @param text Null-terminated text to transmit.
*/
- void sunshine_write_guest_record(const char *format, ...);
+ void sunshine_write_guest_text(const char *text);
/** @brief Configure the second LPC47M157 serial port for coverage records. */
void sunshine_prepare_guest_records(void);
diff --git a/tests/xbox/guest/gtest_serial.cpp b/tests/xbox/guest/gtest_serial.cpp
deleted file mode 100644
index d5346e66..00000000
--- a/tests/xbox/guest/gtest_serial.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-/**
- * @file tests/xbox/guest/gtest_serial.cpp
- * @brief Route GoogleTest's native result printer through the Xbox debug console.
- */
-// standard includes
-#include
-#include
-#include
-
-// lib includes
-#include
-
-namespace testing {
- /**
- * @brief Send formatted test output through DbgPrint in bounded chunks.
- * @param format Printf format string.
- * @param arguments Format arguments.
- * @return Number of characters formatted, or a negative formatting error.
- */
- static int vprintf(const char *format, std::va_list arguments) {
- std::va_list copy;
- va_copy(copy, arguments);
- const int count = std::vsnprintf(nullptr, 0, format, copy);
- va_end(copy);
- if (count <= 0) {
- return count;
- }
-
- std::string output(static_cast(count) + 1, '\0');
- std::vsnprintf(output.data(), output.size(), format, arguments);
- constexpr int chunkSize = 200;
- for (int offset = 0; offset < count; offset += chunkSize) {
- DbgPrint("%.*s", chunkSize, output.c_str() + offset);
- }
- return count;
- }
-
- /**
- * @brief Route GoogleTest's standard output to the debug serial console.
- * @param format Printf format string.
- * @param ... Format arguments.
- * @return Number of characters formatted, or a negative formatting error.
- */
- static int printf(const char *format, ...) {
- std::va_list arguments;
- va_start(arguments, format);
- const int count = testing::vprintf(format, arguments);
- va_end(arguments);
- return count;
- }
-} // namespace testing
-
-// Include GoogleTest after the adapters so its unqualified printf calls use the
-// debug console. nxdk's standard output stream has no backing console handle.
-#include "src/gtest-all.cc"
diff --git a/tests/xbox/guest/main.cpp b/tests/xbox/guest/main.cpp
index 9adf3eb2..f67ca8b8 100644
--- a/tests/xbox/guest/main.cpp
+++ b/tests/xbox/guest/main.cpp
@@ -2,6 +2,9 @@
* @file tests/xbox/guest/main.cpp
* @brief Report GoogleTest results and coverage to the host from the Xbox test XBE.
*/
+// standard includes
+#include
+
// lib includes
#include
#include
@@ -27,7 +30,8 @@ namespace {
if (result->Skipped()) {
status = "SKIP";
}
- sunshine_write_guest_record("SUNSHINE_TEST_CASE %s %s %s\r\n", status, info.test_suite_name(), info.name());
+ const auto record = std::string("SUNSHINE_TEST_CASE ") + status + ' ' + info.test_suite_name() + ' ' + info.name() + "\r\n";
+ sunshine_write_guest_text(record.c_str());
}
};
} // namespace
@@ -40,7 +44,7 @@ int main() {
sunshine_prepare_guest_records();
if (!platform::ensure_directory_exists(test_support::guest_scratch_directory)) {
DbgPrint("Failed to create the Xbox guest test directory\r\n");
- sunshine_write_guest_record("SUNSHINE_TEST_DONE 1 0\r\n");
+ sunshine_write_guest_text("SUNSHINE_TEST_DONE 1 0\r\n");
return 1;
}
testing::InitGoogleTest();
@@ -49,7 +53,8 @@ int main() {
const int result = RUN_ALL_TESTS();
sunshine_write_guest_coverage();
- sunshine_write_guest_record("SUNSHINE_TEST_DONE %d %d\r\n", result, tests->test_to_run_count());
+ const auto done = "SUNSHINE_TEST_DONE " + std::to_string(result) + ' ' + std::to_string(tests->test_to_run_count()) + "\r\n";
+ sunshine_write_guest_text(done.c_str());
Sleep(INFINITE);
return result;
}
From 48e334bb8bb1371f72b4e63f89b18d3212469835 Mon Sep 17 00:00:00 2001
From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com>
Date: Sat, 28 Nov 2026 10:11:26 -0500
Subject: [PATCH 6/9] fix(ci): bypass release API limits and use llvmpipe for
xemu
---
.github/actions/test-and-report/action.yml | 4 +++-
.github/workflows/ci-xbox-original.yml | 3 +++
scripts/run-xemu.sh | 5 +++++
scripts/setup-xemu.sh | 14 +++++++++-----
4 files changed, 20 insertions(+), 6 deletions(-)
diff --git a/.github/actions/test-and-report/action.yml b/.github/actions/test-and-report/action.yml
index b0d91026..c1ddbafe 100644
--- a/.github/actions/test-and-report/action.yml
+++ b/.github/actions/test-and-report/action.yml
@@ -169,7 +169,9 @@ runs:
fi
- name: Upload test and coverage artifacts
- if: ${{ !cancelled() && steps.reports.outcome == 'success' }}
+ if: >-
+ ${{ !cancelled() && steps.reports.outcome == 'success' &&
+ (inputs.xemu-tests != 'true' || hashFiles(steps.reports.outputs.coverage, steps.reports.outputs.logs) != '') }}
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: Tests-${{ inputs.platform }}
diff --git a/.github/workflows/ci-xbox-original.yml b/.github/workflows/ci-xbox-original.yml
index dfbeea4b..072ce35e 100644
--- a/.github/workflows/ci-xbox-original.yml
+++ b/.github/workflows/ci-xbox-original.yml
@@ -132,6 +132,9 @@ jobs:
run: |
cp "${MINGW_PREFIX}/bin/"{opengl32,libgallium_wgl}.dll .local/xemu/app/
cygpath -w "${MINGW_PREFIX}/bin" >> "${GITHUB_PATH}"
+ # The hosted runner's Microsoft Basic Render Driver can exit during xemu startup.
+ echo 'LIBGL_ALWAYS_SOFTWARE=1' >> "${GITHUB_ENV}"
+ echo 'GALLIUM_DRIVER=llvmpipe' >> "${GITHUB_ENV}"
- name: Test and report Xbox guest coverage
uses: ./.github/actions/test-and-report
diff --git a/scripts/run-xemu.sh b/scripts/run-xemu.sh
index 84a48e32..e3cc0522 100644
--- a/scripts/run-xemu.sh
+++ b/scripts/run-xemu.sh
@@ -467,4 +467,9 @@ fi
xemu_args+=("${serial_args[@]}")
xemu_args+=("${test_args[@]}")
+if [[ -n "$test_output" ]] && is_windows; then
+ # The serial file argument already embeds a native path for QEMU.
+ export MSYS2_ARG_CONV_EXCL='*'
+fi
+
exec "$xemu_exe" "${xemu_args[@]}"
diff --git a/scripts/setup-xemu.sh b/scripts/setup-xemu.sh
index cffdd9a6..f3c60e40 100644
--- a/scripts/setup-xemu.sh
+++ b/scripts/setup-xemu.sh
@@ -97,10 +97,14 @@ copy_tree_preserving_existing() {
}
latest_xemu_tag() {
- curl -fsSL --proto '=https' --proto-redir '=https' -A 'Sunshine-client setup-xemu' \
- 'https://api.github.com/repos/xemu-project/xemu/releases/latest' |
- sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' |
- head -n 1
+ local releases='https://github.com/xemu-project/xemu/releases'
+ local release_page
+ # The public release page redirects to the latest tag without consuming the REST API quota.
+ release_page="$(curl -fsSLI --retry 3 --proto '=https' --proto-redir '=https' \
+ -A 'Sunshine-client setup-xemu' -o /dev/null -w '%{url_effective}' "$releases/latest")" || return 1
+ if [[ "$release_page" == "$releases/tag/"* ]]; then
+ printf '%s\n' "${release_page##*/}"
+ fi
return 0
}
@@ -265,7 +269,7 @@ if [[ -n "$xemu_exe" && "$force_download" -eq 0 ]]; then
reused_existing_xemu=1
else
read -r os_name arch_name < <(detect_platform)
- tag="$(latest_xemu_tag)"
+ tag="$(latest_xemu_tag || true)"
if [[ -z "$tag" ]]; then
echo 'Could not determine the latest xemu release tag.' >&2
exit 1
From b0c08d61823eb4d07c13c85cb8487f90a774b126 Mon Sep 17 00:00:00 2001
From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com>
Date: Sat, 28 Nov 2026 11:21:21 -0500
Subject: [PATCH 7/9] ci: publish test artifacts through a dedicated coverage
workflow
---
.github/actions/test-and-report/action.yml | 213 ---------------------
.github/workflows/ci-apple.yml | 3 -
.github/workflows/ci-coverage.yml | 62 ++++++
.github/workflows/ci-flatpak.yml | 69 +++++--
.github/workflows/ci-linux.yml | 5 -
.github/workflows/ci-macos.yml | 51 ++++-
.github/workflows/ci-windows.yml | 62 +++++-
.github/workflows/ci-xbox-original.yml | 79 +++++---
.github/workflows/ci-xbox.yml | 5 -
.github/workflows/ci.yml | 16 +-
README.md | 10 +-
src/_nxdk_compat/include/sunshine_time.h | 6 +-
tests/CMakeLists.txt | 3 +-
tests/{xbox/guest => }/main.cpp | 45 +++--
tests/xbox/guest/CMakeLists.txt | 18 +-
tests/xbox/guest/time_test.cpp | 13 ++
16 files changed, 353 insertions(+), 307 deletions(-)
delete mode 100644 .github/actions/test-and-report/action.yml
create mode 100644 .github/workflows/ci-coverage.yml
rename tests/{xbox/guest => }/main.cpp (55%)
diff --git a/.github/actions/test-and-report/action.yml b/.github/actions/test-and-report/action.yml
deleted file mode 100644
index c1ddbafe..00000000
--- a/.github/actions/test-and-report/action.yml
+++ /dev/null
@@ -1,213 +0,0 @@
----
-name: Test and report coverage
-description: Publish JUnit and LCOV reports from native or Xbox guest tests
-inputs:
- build-dir:
- description: Build directory relative to the workspace
- required: true
- platform:
- description: Platform name for the report artifact and Codecov flag
- required: true
- gcov-source-root:
- description: Retained source directory when CTest and gcov already ran in the build sandbox
- required: false
- xemu-tests:
- description: Run the Original Xbox test ISO in xemu
- required: false
- default: 'false'
- test-shell:
- description: Shell with the build toolchain on its path
- required: false
- default: bash
- codecov-token:
- description: Codecov token for the project
- required: false
-
-runs:
- using: composite
- steps:
- - name: Set up Python
- if: runner.os != 'Windows' || inputs.xemu-tests == 'true'
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
- with:
- python-version: '3.14'
-
- - name: Set up uv
- if: runner.os != 'Windows' || inputs.xemu-tests == 'true'
- uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
- with:
- enable-cache: true
- cache-dependency-glob: third-party/lizardbyte-common/uv.lock
-
- - name: Install coverage tools
- if: runner.os != 'Windows' || inputs.xemu-tests == 'true'
- shell: ${{ inputs.test-shell }}
- run: |
- uv sync --project third-party/lizardbyte-common --locked --only-group test-c \
- --no-python-downloads --no-install-project
-
- - name: Run unit tests
- if: inputs.xemu-tests != 'true'
- id: tests
- shell: ${{ inputs.test-shell }}
- env:
- CMAKE_BUILD: ${{ inputs.build-dir }}
- GCOV_SOURCE_ROOT: ${{ inputs.gcov-source-root }}
- run: |
- if [[ -n "${GCOV_SOURCE_ROOT}" ]]; then
- test -s "${CMAKE_BUILD}/tests/test_results.xml"
- exit
- fi
- if [[ "${RUNNER_OS}" == Windows ]]; then
- export LLVM_PROFILE_FILE
- LLVM_PROFILE_FILE="$(cygpath -m "${PWD}/${CMAKE_BUILD}/tests/%m-%p.profraw")"
- fi
- ctest --test-dir "${CMAKE_BUILD}" --output-on-failure \
- --output-junit "${PWD}/${CMAKE_BUILD}/tests/test_results.xml"
-
- - name: Generate coverage report
- id: coverage
- if: ${{ !cancelled() && (steps.tests.outcome == 'success' || steps.tests.outcome == 'failure') }}
- shell: ${{ inputs.test-shell }}
- env:
- CMAKE_BUILD: ${{ inputs.build-dir }}
- GCOV_SOURCE_ROOT: ${{ inputs.gcov-source-root }}
- run: |
- set -euo pipefail
- report="${PWD}/${CMAKE_BUILD}/coverage.info"
- raw_report="${report}.raw"
- coverage_root=
- if [[ "${RUNNER_OS}" == Windows ]]; then
- # CTest starts one process per test, which can exceed the Windows command line limit.
- printf '%s\n' "${CMAKE_BUILD}"/tests/*.profraw > "${CMAKE_BUILD}/coverage-inputs.txt"
- llvm-profdata merge -sparse -f "${CMAKE_BUILD}/coverage-inputs.txt" -o "${CMAKE_BUILD}/coverage.profdata"
- binaries=("${CMAKE_BUILD}"/tests/test_*.exe)
- objects=()
- for binary in "${binaries[@]:1}"; do
- objects+=("-object=${binary}")
- done
- mapfile -t sources < <(git ls-files src)
- coverage_root="$(cygpath -am "${PWD}")/"
- llvm-cov export -format=lcov -instr-profile="${CMAKE_BUILD}/coverage.profdata" \
- "${binaries[0]}" "${objects[@]}" "${sources[@]}" > "${raw_report}"
- else
- gcov=gcov
- if [[ "${RUNNER_OS}" == macOS ]]; then
- gcov='xcrun llvm-cov gcov'
- fi
- gcov_args=(--gcov-executable "${gcov}")
- if [[ -n "${GCOV_SOURCE_ROOT}" ]]; then
- coverage_root="$(realpath "${GCOV_SOURCE_ROOT}")/"
- gcov_args=(--gcov-use-existing-files)
- fi
- uv run --directory "${GCOV_SOURCE_ROOT:-.}" --project "${PWD}/third-party/lizardbyte-common" \
- --locked --no-sync gcovr "${PWD}/${CMAKE_BUILD}" -r . "${gcov_args[@]}" --filter src \
- --exclude-noncode-lines --exclude-throw-branches --exclude-unreachable-branches --lcov "${raw_report}"
- fi
- if [[ -n "${coverage_root}" ]]; then
- # LCOV source paths must resolve from the repository checkout.
- awk -v root="${coverage_root}" '
- /^SF:/ {
- source = substr($0, 4)
- gsub(/\\/, "/", source)
- sub(/\r$/, "", source)
- if (index(tolower(source), tolower(root)) != 1) {
- print "Coverage source is outside the source tree: " source > "/dev/stderr"
- exit 1
- }
- $0 = "SF:" substr(source, length(root) + 1)
- }
- { print }
- ' "${raw_report}" > "${report}.tmp"
- grep -q '^SF:src/' "${report}.tmp"
- mv "${report}.tmp" "${report}"
- else
- mv "${raw_report}" "${report}"
- fi
- test -s "${report}"
-
- - name: Run Xbox tests and recover guest coverage
- if: inputs.xemu-tests == 'true'
- id: xemu
- shell: bash
- env:
- CMAKE_BUILD: ${{ inputs.build-dir }}
- APPIMAGE_EXTRACT_AND_RUN: '1'
- SDL_AUDIO_DRIVER: dummy
- run: |
- tests=(uv run --project third-party/lizardbyte-common --locked --no-sync
- python scripts/run-xbox-coverage.py "${CMAKE_BUILD}")
- if [[ "${RUNNER_OS}" == Linux ]]; then
- LIBGL_ALWAYS_SOFTWARE=1 SDL_VIDEO_DRIVER=x11 \
- xvfb-run -a -s '-screen 0 1024x768x24' "${tests[@]}"
- else
- "${tests[@]}"
- fi
-
- - name: Select report paths
- id: reports
- if: >-
- ${{ !cancelled() &&
- (steps.tests.outcome == 'success' || steps.tests.outcome == 'failure' ||
- steps.xemu.outcome == 'success' || steps.xemu.outcome == 'failure') }}
- shell: ${{ inputs.test-shell }}
- env:
- CMAKE_BUILD: ${{ inputs.build-dir }}
- XEMU_TESTS: ${{ inputs.xemu-tests }}
- run: |
- if [[ "${XEMU_TESTS}" == true ]]; then
- {
- echo "coverage=${CMAKE_BUILD}/xemu-coverage/coverage.info"
- echo "junit=${CMAKE_BUILD}/xemu-coverage/test_results.xml"
- echo "logs=${CMAKE_BUILD}/xemu-coverage/*.log"
- } >> "${GITHUB_OUTPUT}"
- else
- {
- echo "coverage=${CMAKE_BUILD}/coverage.info"
- echo "junit=${CMAKE_BUILD}/tests/test_results.xml"
- } >> "${GITHUB_OUTPUT}"
- fi
-
- - name: Upload test and coverage artifacts
- if: >-
- ${{ !cancelled() && steps.reports.outcome == 'success' &&
- (inputs.xemu-tests != 'true' || hashFiles(steps.reports.outputs.coverage, steps.reports.outputs.logs) != '') }}
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
- with:
- name: Tests-${{ inputs.platform }}
- path: |
- ${{ steps.reports.outputs.coverage }}
- ${{ steps.reports.outputs.junit }}
- ${{ steps.reports.outputs.logs }}
- include-hidden-files: ${{ inputs.gcov-source-root != '' }}
- if-no-files-found: error
-
- - name: Upload coverage to Codecov
- if: >-
- ${{ !cancelled() && steps.reports.outcome == 'success' &&
- (steps.coverage.outcome == 'success' ||
- (inputs.xemu-tests == 'true' && hashFiles(steps.reports.outputs.coverage) != '')) &&
- startsWith(github.repository, 'SunshineStream/') }}
- uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
- with:
- disable_search: true
- fail_ci_if_error: true
- files: ${{ steps.reports.outputs.coverage }}
- flags: ${{ inputs.platform }}
- report_type: coverage
- token: ${{ inputs.codecov-token }}
-
- - name: Upload test results to Codecov
- if: >-
- ${{ !cancelled() &&
- steps.reports.outcome == 'success' &&
- hashFiles(steps.reports.outputs.junit) != '' &&
- startsWith(github.repository, 'SunshineStream/') }}
- uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
- with:
- disable_search: true
- fail_ci_if_error: true
- files: ${{ steps.reports.outputs.junit }}
- flags: ${{ inputs.platform }}
- report_type: test_results
- token: ${{ inputs.codecov-token }}
diff --git a/.github/workflows/ci-apple.yml b/.github/workflows/ci-apple.yml
index 202e0b34..f837ea4b 100644
--- a/.github/workflows/ci-apple.yml
+++ b/.github/workflows/ci-apple.yml
@@ -9,8 +9,6 @@ on:
required: true
type: boolean
secrets:
- CODECOV_TOKEN:
- required: false
APPLE_ID:
required: false
APPLE_TEAM_ID:
@@ -39,7 +37,6 @@ jobs:
with:
publish_release: ${{ inputs.publish_release }}
secrets:
- CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
APPLE_NOTARYTOOL_PASSWORD: ${{ secrets.APPLE_NOTARYTOOL_PASSWORD }}
diff --git a/.github/workflows/ci-coverage.yml b/.github/workflows/ci-coverage.yml
new file mode 100644
index 00000000..8a9b11e0
--- /dev/null
+++ b/.github/workflows/ci-coverage.yml
@@ -0,0 +1,62 @@
+---
+name: CI-Coverage
+permissions: {}
+
+on:
+ workflow_call:
+ secrets:
+ CODECOV_TOKEN:
+ required: false
+
+jobs:
+ upload:
+ name: ${{ matrix.platform }}
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ strategy:
+ fail-fast: false
+ matrix:
+ platform:
+ - Linux-aarch64
+ - Linux-x86_64
+ - macOS-arm64
+ - macOS-x86_64
+ - Windows-AMD64
+ - Windows-ARM64
+ - Xbox-guest-xemu-Linux
+ - Xbox-guest-xemu-macOS
+ - Xbox-guest-xemu-Windows
+ steps:
+ - name: Checkout
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+
+ - name: Download test and coverage artifact
+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
+ with:
+ name: Tests-${{ matrix.platform }}
+ path: _coverage
+
+ - name: Upload test coverage
+ if: hashFiles('_coverage/coverage.info') != ''
+ uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
+ with:
+ disable_search: true
+ fail_ci_if_error: true
+ files: _coverage/coverage.info
+ report_type: coverage
+ flags: ${{ matrix.platform }}
+ token: ${{ secrets.CODECOV_TOKEN }}
+
+ - name: Upload test results
+ if: ${{ !cancelled() && hashFiles('_coverage/test_results.xml') != '' }}
+ uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
+ with:
+ disable_search: true
+ fail_ci_if_error: true
+ files: _coverage/test_results.xml
+ report_type: test_results
+ flags: ${{ matrix.platform }}
+ token: ${{ secrets.CODECOV_TOKEN }}
diff --git a/.github/workflows/ci-flatpak.yml b/.github/workflows/ci-flatpak.yml
index aba51b8b..f2623cd8 100644
--- a/.github/workflows/ci-flatpak.yml
+++ b/.github/workflows/ci-flatpak.yml
@@ -4,9 +4,6 @@ permissions: {}
on:
workflow_call:
- secrets:
- CODECOV_TOKEN:
- required: false
jobs:
build:
@@ -17,7 +14,7 @@ jobs:
env:
FLATPAK_APP_ID: dev.lizardbyte.app.SunshineClient
FLATPAK_ARCH: ${{ matrix.arch }}
- FLATPAK_MODULE_DIR: cmake-build-flatpak/.flatpak-builder/build/sunshine-client
+ FLATPAK_BUILD_DIR: cmake-build-flatpak/.flatpak-builder/build/sunshine-client/_flatpak_build
strategy:
fail-fast: false
matrix:
@@ -55,7 +52,6 @@ jobs:
"org.freedesktop.Sdk/${FLATPAK_ARCH}/${runtime_version}"
- name: Build Flatpak
- id: flatpak
working-directory: cmake-build-flatpak
run: |
sudo su "$(whoami)" -c "flatpak run org.flatpak.Builder \
@@ -70,14 +66,57 @@ jobs:
name: Sunshine-client-Flatpak-${{ matrix.arch }}
path: Sunshine-client-*.flatpak
- - name: Publish Flatpak test reports
- if: >-
- ${{ !cancelled() &&
- (steps.flatpak.outcome == 'success' ||
- hashFiles(format('{0}/_flatpak_build/tests/test_results.xml', env.FLATPAK_MODULE_DIR)) != '') }}
- uses: ./.github/actions/test-and-report
+ - name: Collect Flatpak test results
+ id: tests
+ if: ${{ !cancelled() && hashFiles(format('{0}/tests/test_results.xml', env.FLATPAK_BUILD_DIR)) != '' }}
+ run: cp "${FLATPAK_BUILD_DIR}/tests/test_results.xml" "${FLATPAK_BUILD_DIR}/test_results.xml"
+
+ - name: Set up Python
+ if: ${{ !cancelled() && steps.tests.outcome == 'success' }}
+ uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
+ with:
+ python-version: '3.14'
+
+ - name: Set up uv
+ if: ${{ !cancelled() && steps.tests.outcome == 'success' }}
+ uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
+ with:
+ enable-cache: true
+ cache-dependency-glob: third-party/lizardbyte-common/uv.lock
+
+ - name: Generate Flatpak coverage report
+ if: ${{ !cancelled() && steps.tests.outcome == 'success' }}
+ run: |
+ set -euo pipefail
+ uv sync --project third-party/lizardbyte-common --locked --only-group test-c \
+ --no-python-downloads --no-install-project
+ report="${PWD}/${FLATPAK_BUILD_DIR}/coverage.info"
+ module_dir="$(realpath "${FLATPAK_BUILD_DIR}/..")"
+ # The sandbox already generated gcov files using its own toolchain.
+ uv run --directory "${module_dir}" --project "${PWD}/third-party/lizardbyte-common" \
+ --locked --no-sync gcovr "${PWD}/${FLATPAK_BUILD_DIR}" -r . --gcov-use-existing-files --filter src \
+ --exclude-noncode-lines --exclude-throw-branches --exclude-unreachable-branches --lcov "${report}.raw"
+ awk -v root="${module_dir}/" '
+ /^SF:/ {
+ source = substr($0, 4)
+ if (index(source, root) != 1) {
+ print "Coverage source is outside the source tree: " source > "/dev/stderr"
+ exit 1
+ }
+ $0 = "SF:" substr(source, length(root) + 1)
+ }
+ { print }
+ ' "${report}.raw" > "${report}.tmp"
+ grep -q '^SF:src/' "${report}.tmp"
+ mv "${report}.tmp" "${report}"
+
+ - name: Upload test and coverage artifacts
+ if: ${{ !cancelled() && steps.tests.outcome == 'success' }}
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
- build-dir: ${{ env.FLATPAK_MODULE_DIR }}/_flatpak_build
- gcov-source-root: ${{ env.FLATPAK_MODULE_DIR }}
- platform: Linux-${{ matrix.arch }}
- codecov-token: ${{ secrets.CODECOV_TOKEN }}
+ name: Tests-Linux-${{ matrix.arch }}
+ path: |
+ ${{ env.FLATPAK_BUILD_DIR }}/coverage.info
+ ${{ env.FLATPAK_BUILD_DIR }}/test_results.xml
+ include-hidden-files: true
+ if-no-files-found: error
diff --git a/.github/workflows/ci-linux.yml b/.github/workflows/ci-linux.yml
index 2a3fc844..bf966b7b 100644
--- a/.github/workflows/ci-linux.yml
+++ b/.github/workflows/ci-linux.yml
@@ -4,9 +4,6 @@ permissions: {}
on:
workflow_call:
- secrets:
- CODECOV_TOKEN:
- required: false
jobs:
flatpak:
@@ -14,5 +11,3 @@ jobs:
permissions:
contents: read
uses: ./.github/workflows/ci-flatpak.yml
- secrets:
- CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
diff --git a/.github/workflows/ci-macos.yml b/.github/workflows/ci-macos.yml
index 62679ecc..f6d77eb9 100644
--- a/.github/workflows/ci-macos.yml
+++ b/.github/workflows/ci-macos.yml
@@ -9,8 +9,6 @@ on:
required: true
type: boolean
secrets:
- CODECOV_TOKEN:
- required: false
APPLE_ID:
required: false
APPLE_TEAM_ID:
@@ -30,6 +28,8 @@ jobs:
runs-on: ${{ matrix.runner }}
permissions:
contents: read
+ env:
+ CMAKE_BUILD: cmake-build-client
strategy:
fail-fast: false
matrix:
@@ -61,12 +61,49 @@ jobs:
- name: Build client and tests
run: cmake --build cmake-build-client --parallel
- - name: Test and report coverage
- uses: ./.github/actions/test-and-report
+ - name: Set up Python
+ uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
+ with:
+ python-version: '3.14'
+
+ - name: Set up uv
+ uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
+ with:
+ enable-cache: true
+ cache-dependency-glob: third-party/lizardbyte-common/uv.lock
+
+ - name: Install coverage tools
+ run: |
+ uv sync --project third-party/lizardbyte-common --locked --only-group test-c \
+ --no-python-downloads --no-install-project
+
+ - name: Run unit tests
+ id: tests
+ run: |
+ ctest --test-dir "${CMAKE_BUILD}" --output-on-failure \
+ --output-junit "${PWD}/${CMAKE_BUILD}/test_results.xml"
+
+ - name: Generate coverage report
+ if: ${{ !cancelled() && (steps.tests.outcome == 'success' || steps.tests.outcome == 'failure') }}
+ run: |
+ uv run --project third-party/lizardbyte-common --locked --no-sync gcovr \
+ "${CMAKE_BUILD}" -r . --gcov-executable 'xcrun llvm-cov gcov' --filter src \
+ --exclude-noncode-lines --exclude-throw-branches --exclude-unreachable-branches \
+ --lcov "${CMAKE_BUILD}/coverage.info.tmp"
+ test -s "${CMAKE_BUILD}/coverage.info.tmp"
+ mv "${CMAKE_BUILD}/coverage.info.tmp" "${CMAKE_BUILD}/coverage.info"
+
+ - name: Upload test and coverage artifacts
+ if: >-
+ ${{ !cancelled() &&
+ hashFiles('cmake-build-client/coverage.info', 'cmake-build-client/test_results.xml') != '' }}
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
- build-dir: cmake-build-client
- platform: macOS-${{ matrix.arch }}
- codecov-token: ${{ secrets.CODECOV_TOKEN }}
+ name: Tests-macOS-${{ matrix.arch }}
+ path: |
+ ${{ env.CMAKE_BUILD }}/coverage.info
+ ${{ env.CMAKE_BUILD }}/test_results.xml
+ if-no-files-found: error
- name: Sign app
if: inputs.publish_release
diff --git a/.github/workflows/ci-windows.yml b/.github/workflows/ci-windows.yml
index 77fb3b47..40db7465 100644
--- a/.github/workflows/ci-windows.yml
+++ b/.github/workflows/ci-windows.yml
@@ -24,8 +24,6 @@ on:
required: false
AZURE_TENANT_ID:
required: false
- CODECOV_TOKEN:
- required: false
jobs:
build:
@@ -33,6 +31,8 @@ jobs:
runs-on: ${{ matrix.runner }}
permissions:
contents: read
+ env:
+ CMAKE_BUILD: cmake-build-client
strategy:
fail-fast: false
matrix:
@@ -83,13 +83,59 @@ jobs:
- name: Build client and tests
run: cmake --build cmake-build-client --parallel
- - name: Test and report coverage
- uses: ./.github/actions/test-and-report
+ - name: Run unit tests
+ id: tests
+ run: |
+ export LLVM_PROFILE_FILE
+ LLVM_PROFILE_FILE="$(cygpath -m "${PWD}/${CMAKE_BUILD}/tests/%m-%p.profraw")"
+ ctest --test-dir "${CMAKE_BUILD}" --output-on-failure \
+ --output-junit "${PWD}/${CMAKE_BUILD}/test_results.xml"
+
+ - name: Generate coverage report
+ if: ${{ !cancelled() && (steps.tests.outcome == 'success' || steps.tests.outcome == 'failure') }}
+ run: |
+ set -euo pipefail
+ # CTest starts one process per test, which can exceed the Windows command line limit.
+ printf '%s\n' "${CMAKE_BUILD}"/tests/*.profraw > "${CMAKE_BUILD}/coverage-inputs.txt"
+ profile="${CMAKE_BUILD}/coverage.profdata"
+ llvm-profdata merge -sparse -f "${CMAKE_BUILD}/coverage-inputs.txt" -o "${profile}"
+ binaries=("${CMAKE_BUILD}"/tests/test_*.exe)
+ objects=()
+ for binary in "${binaries[@]:1}"; do
+ objects+=("-object=${binary}")
+ done
+ mapfile -t sources < <(git ls-files src)
+ raw_report="${CMAKE_BUILD}/coverage.info.raw"
+ llvm-cov export -format=lcov -instr-profile="${profile}" \
+ "${binaries[0]}" "${objects[@]}" "${sources[@]}" > "${raw_report}"
+ # LCOV source paths must resolve from the repository checkout.
+ awk -v root="$(cygpath -am "${PWD}")/" '
+ /^SF:/ {
+ source = substr($0, 4)
+ gsub(/\\/, "/", source)
+ sub(/\r$/, "", source)
+ if (index(tolower(source), tolower(root)) != 1) {
+ print "Coverage source is outside the source tree: " source > "/dev/stderr"
+ exit 1
+ }
+ $0 = "SF:" substr(source, length(root) + 1)
+ }
+ { print }
+ ' "${raw_report}" > "${CMAKE_BUILD}/coverage.info.tmp"
+ grep -q '^SF:src/' "${CMAKE_BUILD}/coverage.info.tmp"
+ mv "${CMAKE_BUILD}/coverage.info.tmp" "${CMAKE_BUILD}/coverage.info"
+
+ - name: Upload test and coverage artifacts
+ if: >-
+ ${{ !cancelled() &&
+ hashFiles('cmake-build-client/coverage.info', 'cmake-build-client/test_results.xml') != '' }}
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
- build-dir: cmake-build-client
- platform: Windows-${{ matrix.arch }}
- test-shell: 'msys2 {0}'
- codecov-token: ${{ secrets.CODECOV_TOKEN }}
+ name: Tests-Windows-${{ matrix.arch }}
+ path: |
+ ${{ env.CMAKE_BUILD }}/coverage.info
+ ${{ env.CMAKE_BUILD }}/test_results.xml
+ if-no-files-found: error
- name: Stage Windows client
run: |
diff --git a/.github/workflows/ci-xbox-original.yml b/.github/workflows/ci-xbox-original.yml
index 072ce35e..c9124342 100644
--- a/.github/workflows/ci-xbox-original.yml
+++ b/.github/workflows/ci-xbox-original.yml
@@ -4,9 +4,6 @@ permissions: {}
on:
workflow_call:
- secrets:
- CODECOV_TOKEN:
- required: false
jobs:
build:
@@ -54,10 +51,9 @@ jobs:
)
sunshine_dependencies=(
"patch"
- # Xvfb brings xauth. Mesa GLX brings the software OpenGL driver.
- "libglx-mesa0"
- "libusb-1.0-0"
- "xvfb"
+ "libglx-mesa0" # OpenGL over X11 with Mesa's software renderer.
+ "libusb-1.0-0" # Shared library used by the xemu binary.
+ "xvfb" # Virtual display for xemu. Also installs xauth.
)
dependencies=("${nxdk_dependencies[@]}" "${sunshine_dependencies[@]}")
sudo apt-get update
@@ -104,6 +100,19 @@ jobs:
mingw-w64-ucrt-x86_64-mesa
mingw-w64-ucrt-x86_64-nasm
+ - name: Set up xemu
+ shell: bash
+ run: bash scripts/setup-xemu.sh
+
+ - name: Set up software OpenGL (Windows)
+ if: runner.os == 'Windows'
+ run: |
+ cp "${MINGW_PREFIX}/bin/"{opengl32,libgallium_wgl}.dll .local/xemu/app/
+ cygpath -w "${MINGW_PREFIX}/bin" >> "${GITHUB_PATH}"
+ # The hosted runner's Microsoft Basic Render Driver can exit during xemu startup.
+ echo 'LIBGL_ALWAYS_SOFTWARE=1' >> "${GITHUB_ENV}"
+ echo 'GALLIUM_DRIVER=llvmpipe' >> "${GITHUB_ENV}"
+
- name: Build
run: |
chmod +x build.sh
@@ -123,23 +132,49 @@ jobs:
name: Sunshine-client-XboxOG-${{ runner.os }}
path: artifacts/
- - name: Set up xemu
+ - name: Set up Python
+ uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
+ with:
+ python-version: '3.14'
+
+ - name: Set up uv
+ uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
+ with:
+ enable-cache: true
+ cache-dependency-glob: third-party/lizardbyte-common/uv.lock
+
+ - name: Install coverage tools
shell: bash
- run: bash scripts/setup-xemu.sh
+ run: |
+ uv sync --project third-party/lizardbyte-common --locked --only-group test-c \
+ --no-python-downloads --no-install-project
- - name: Set up Windows software OpenGL
- if: runner.os == 'Windows'
+ - name: Run Xbox tests and recover guest coverage
+ shell: bash
+ env:
+ APPIMAGE_EXTRACT_AND_RUN: '1'
+ SDL_AUDIO_DRIVER: dummy
run: |
- cp "${MINGW_PREFIX}/bin/"{opengl32,libgallium_wgl}.dll .local/xemu/app/
- cygpath -w "${MINGW_PREFIX}/bin" >> "${GITHUB_PATH}"
- # The hosted runner's Microsoft Basic Render Driver can exit during xemu startup.
- echo 'LIBGL_ALWAYS_SOFTWARE=1' >> "${GITHUB_ENV}"
- echo 'GALLIUM_DRIVER=llvmpipe' >> "${GITHUB_ENV}"
+ tests=(uv run --project third-party/lizardbyte-common --locked --no-sync
+ python scripts/run-xbox-coverage.py "${CMAKE_BUILD}/xbox")
+ if [[ "${RUNNER_OS}" == Linux ]]; then
+ LIBGL_ALWAYS_SOFTWARE=1 SDL_VIDEO_DRIVER=x11 \
+ xvfb-run -a -s '-screen 0 1024x768x24' "${tests[@]}"
+ else
+ "${tests[@]}"
+ fi
- - name: Test and report Xbox guest coverage
- uses: ./.github/actions/test-and-report
+ - name: Upload test and coverage artifacts
+ if: >-
+ ${{ !cancelled() && hashFiles(
+ format('{0}/xbox/xemu-coverage/coverage.info', env.CMAKE_BUILD),
+ format('{0}/xbox/xemu-coverage/test_results.xml', env.CMAKE_BUILD),
+ format('{0}/xbox/xemu-coverage/*.log', env.CMAKE_BUILD)) != '' }}
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
- build-dir: ${{ env.CMAKE_BUILD }}/xbox
- platform: Xbox-guest-xemu-${{ runner.os }}
- xemu-tests: 'true'
- codecov-token: ${{ secrets.CODECOV_TOKEN }}
+ name: Tests-Xbox-guest-xemu-${{ runner.os }}
+ path: |
+ ${{ env.CMAKE_BUILD }}/xbox/xemu-coverage/coverage.info
+ ${{ env.CMAKE_BUILD }}/xbox/xemu-coverage/test_results.xml
+ ${{ env.CMAKE_BUILD }}/xbox/xemu-coverage/*.log
+ if-no-files-found: error
diff --git a/.github/workflows/ci-xbox.yml b/.github/workflows/ci-xbox.yml
index 3b15ddc0..cf9bc97f 100644
--- a/.github/workflows/ci-xbox.yml
+++ b/.github/workflows/ci-xbox.yml
@@ -4,9 +4,6 @@ permissions: {}
on:
workflow_call:
- secrets:
- CODECOV_TOKEN:
- required: false
jobs:
original:
@@ -14,5 +11,3 @@ jobs:
permissions:
contents: read
uses: ./.github/workflows/ci-xbox-original.yml
- secrets:
- CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b3123875..d78b208a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -40,8 +40,6 @@ jobs:
permissions:
contents: read
uses: ./.github/workflows/ci-xbox.yml
- secrets:
- CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
build-windows:
name: Windows
@@ -58,7 +56,6 @@ jobs:
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
- CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
build-apple:
name: Apple
@@ -69,7 +66,6 @@ jobs:
with:
publish_release: ${{ needs.setup_release.outputs.publish_release == 'true' }}
secrets:
- CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
APPLE_NOTARYTOOL_PASSWORD: ${{ secrets.APPLE_NOTARYTOOL_PASSWORD }}
@@ -84,6 +80,18 @@ jobs:
permissions:
contents: read
uses: ./.github/workflows/ci-linux.yml
+
+ publish-coverage:
+ name: Coverage
+ if: ${{ !cancelled() && startsWith(github.repository, 'SunshineStream/') }}
+ needs:
+ - build-xbox
+ - build-windows
+ - build-apple
+ - build-linux
+ permissions:
+ contents: read
+ uses: ./.github/workflows/ci-coverage.yml
secrets:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
diff --git a/README.md b/README.md
index 421fe4f9..27686b2e 100644
--- a/README.md
+++ b/README.md
@@ -515,11 +515,11 @@ uv run --locked python scripts/run-xbox-coverage.py cmake-build-release/xbox
The build creates `SunshineTests.iso` beside the release ISO. It contains the regular unit tests
from `tests/unit/` and the Xbox cases in `tests/xbox/guest/`. Desktop-only cases use platform guards.
-xemu prints each GoogleTest `[ RUN ]` line as the test starts so the last line identifies where a
-crash or hang occurred. The runner collects counters on
-the second serial port, pairs them with the coverage notes from the same build, and writes JUnit,
-LCOV, and the captured data under `xbox/xemu-coverage/`. Xbox CI runs xemu on each toolchain and
-uploads the results to Codecov under `Xbox-guest-xemu-`.
+xemu prints GoogleTest output in color, including a `[ RUN ]` line as each test starts. The last
+start line identifies the test that was running during a crash or hang. The runner collects counters
+on the second serial port and pairs them with the coverage notes from the same build. It writes
+JUnit, LCOV, and the captured data under `xbox/xemu-coverage/`. Each Xbox toolchain uploads its
+reports as CI artifacts. The coverage workflow publishes them to Codecov under `Xbox-guest-xemu-`.
## Host-native unit tests
diff --git a/src/_nxdk_compat/include/sunshine_time.h b/src/_nxdk_compat/include/sunshine_time.h
index 4930ed95..64aed09c 100644
--- a/src/_nxdk_compat/include/sunshine_time.h
+++ b/src/_nxdk_compat/include/sunshine_time.h
@@ -18,6 +18,7 @@
*
* PDCLib declares gmtime_s without supplying its implementation. Its gmtime uses
* shared static storage, so use the kernel conversion without changing libc feature macros.
+ * Check the input at the same width as the signed kernel tick calculation.
*
* @param timestamp Unix timestamp in seconds.
* @param result Receives the complete UTC calendar fields.
@@ -26,11 +27,12 @@
inline bool sunshine_gmtime(std::time_t timestamp, std::tm &result) {
constexpr std::int64_t epochOffset = 11644473600LL;
constexpr std::int64_t ticksPerSecond = 10000000;
- if (timestamp < 0 || timestamp > std::numeric_limits::max() / ticksPerSecond - epochOffset) {
+ const auto seconds = static_cast(timestamp);
+ if (seconds < 0 || seconds > std::numeric_limits::max() / ticksPerSecond - epochOffset) {
return false;
}
LARGE_INTEGER time {};
- time.QuadPart = (static_cast(timestamp) + epochOffset) * ticksPerSecond;
+ time.QuadPart = (seconds + epochOffset) * ticksPerSecond;
TIME_FIELDS fields {};
RtlTimeToTimeFields(&time, &fields);
result = {};
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 8941ab4d..e28d67f5 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -52,6 +52,7 @@ endif()
include("${CMAKE_CURRENT_SOURCE_DIR}/sources.cmake")
add_executable(${PROJECT_NAME}
+ main.cpp
${SUNSHINE_UNIT_TEST_SOURCES}
"${CMAKE_SOURCE_DIR}/src/_nxdk_compat/ffmpeg_memory.c"
${SUNSHINE_TESTABLE_SOURCES})
@@ -67,7 +68,7 @@ target_include_directories(${PROJECT_NAME}
${GTEST_SOURCE_DIR}/googlemock/include)
target_link_libraries(${PROJECT_NAME}
PRIVATE
- gtest_main
+ gtest
SunshineClient::OpenSSL
lizardbyte::test_support
moonlight-common-c)
diff --git a/tests/xbox/guest/main.cpp b/tests/main.cpp
similarity index 55%
rename from tests/xbox/guest/main.cpp
rename to tests/main.cpp
index f67ca8b8..6c7ec971 100644
--- a/tests/xbox/guest/main.cpp
+++ b/tests/main.cpp
@@ -1,21 +1,24 @@
/**
- * @file tests/xbox/guest/main.cpp
- * @brief Report GoogleTest results and coverage to the host from the Xbox test XBE.
+ * @file tests/main.cpp
+ * @brief Run the shared GoogleTest suite and export guest results from Xbox builds.
*/
-// standard includes
-#include
+#ifdef NXDK
+ // standard includes
+ #include
+#endif
// lib includes
#include
-#include
-#include
+#ifdef NXDK
+ #include
+ #include
-// local includes
-#include "gcov_serial.h"
-#include "src/platform/filesystem_utils.h"
+ // local includes
+ #include "src/platform/filesystem_utils.h"
-// test includes
-#include "tests/support/filesystem_test_utils.h"
+ // test includes
+ #include "tests/support/filesystem_test_utils.h"
+ #include "tests/xbox/guest/gcov_serial.h"
namespace {
/** @brief Emit result records on COM2 for the test runner. */
@@ -35,26 +38,38 @@ namespace {
}
};
} // namespace
+#endif
/**
- * @brief Run the instrumented guest tests and report completion after exporting counters.
- * @return This process waits for the emulator runner to shut down the guest.
+ * @brief Run GoogleTest and export guest results and counters when running on Xbox.
+ * @param argc Number of command-line arguments supplied by the runtime.
+ * @param argv Command-line arguments supplied by the runtime.
+ * @return Test status. The Xbox guest waits for the runner to stop the emulator after exporting results.
*/
-int main() {
+int main([[maybe_unused]] int argc, [[maybe_unused]] char **argv) {
+#ifdef NXDK
+ // nxdk starts main with zero arguments, which makes the argument overload skip initialization.
+ testing::InitGoogleTest();
+ // The emulated serial port carries ANSI escapes even though the guest has no terminal device.
+ GTEST_FLAG_SET(color, "yes");
sunshine_prepare_guest_records();
if (!platform::ensure_directory_exists(test_support::guest_scratch_directory)) {
DbgPrint("Failed to create the Xbox guest test directory\r\n");
sunshine_write_guest_text("SUNSHINE_TEST_DONE 1 0\r\n");
return 1;
}
- testing::InitGoogleTest();
auto *tests = testing::UnitTest::GetInstance();
tests->listeners().Append(new SerialResults);
+#else
+ testing::InitGoogleTest(&argc, argv);
+#endif
const int result = RUN_ALL_TESTS();
+#ifdef NXDK
sunshine_write_guest_coverage();
const auto done = "SUNSHINE_TEST_DONE " + std::to_string(result) + ' ' + std::to_string(tests->test_to_run_count()) + "\r\n";
sunshine_write_guest_text(done.c_str());
Sleep(INFINITE);
+#endif
return result;
}
diff --git a/tests/xbox/guest/CMakeLists.txt b/tests/xbox/guest/CMakeLists.txt
index eb38d1ef..92b297ee 100644
--- a/tests/xbox/guest/CMakeLists.txt
+++ b/tests/xbox/guest/CMakeLists.txt
@@ -1,10 +1,23 @@
# Use the vendored GoogleTest sources with only the features nxdk supplies.
set(_gtest_source "${CMAKE_SOURCE_DIR}/third-party/lizardbyte-common/third-party/googletest/googletest")
+# GoogleTest disables color when filesystem support is off. On the guest its
+# ANSI printer can honor the color flag without querying a terminal descriptor.
+set(_gtest_color_source "${_gtest_source}/src/gtest.cc")
+set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_gtest_color_source}")
+file(READ "${_gtest_color_source}" _gtest_original)
+string(REPLACE " false;\n#endif // GTEST_HAS_FILE_SYSTEM\n\n const bool use_color"
+ " ShouldUseColor(false);\n#endif // GTEST_HAS_FILE_SYSTEM\n\n const bool use_color"
+ _gtest_colored "${_gtest_original}")
+if(_gtest_colored STREQUAL _gtest_original)
+ message(FATAL_ERROR "Could not adapt GoogleTest's color check for the Xbox serial console")
+endif()
+set(_guest_gtest "${CMAKE_CURRENT_BINARY_DIR}/googletest")
+file(GENERATE OUTPUT "${_guest_gtest}/src/gtest.cc" CONTENT "${_gtest_colored}")
add_library(sunshine_xbox_gtest STATIC "${_gtest_source}/src/gtest-all.cc")
target_include_directories(sunshine_xbox_gtest SYSTEM PUBLIC
"${_gtest_source}/include"
"${CMAKE_SOURCE_DIR}/third-party/lizardbyte-common/tests/support/include")
-target_include_directories(sunshine_xbox_gtest SYSTEM PRIVATE "${_gtest_source}")
+target_include_directories(sunshine_xbox_gtest SYSTEM PRIVATE "${_guest_gtest}" "${_gtest_source}")
target_include_directories(sunshine_xbox_gtest PUBLIC "${CMAKE_SOURCE_DIR}/src/_nxdk_compat/include")
target_compile_definitions(sunshine_xbox_gtest PUBLIC
GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
@@ -37,7 +50,8 @@ target_compile_options(sunshine_xbox_coverage PRIVATE -O0 -fprofile-arcs -ftest-
set(_nxdk_flush "${NXDK_DIR}/lib/pdclib/platform/xbox/functions/_PDCLIB/_PDCLIB_flushbuffer.c")
set_source_files_properties("${_nxdk_flush}" PROPERTIES
COMPILE_DEFINITIONS "_PDCLIB_flushbuffer=sunshine_pdclib_flush_file")
-add_executable(sunshine_xbox_tests main.cpp console_serial.c gcov_serial.c ${SUNSHINE_UNIT_TEST_SOURCES}
+add_executable(sunshine_xbox_tests "${CMAKE_SOURCE_DIR}/tests/main.cpp"
+ console_serial.c gcov_serial.c ${SUNSHINE_UNIT_TEST_SOURCES}
"${_nxdk_flush}"
$
$)
diff --git a/tests/xbox/guest/time_test.cpp b/tests/xbox/guest/time_test.cpp
index b2b943f6..2201b164 100644
--- a/tests/xbox/guest/time_test.cpp
+++ b/tests/xbox/guest/time_test.cpp
@@ -8,6 +8,7 @@
// standard includes
#include
+ #include
// lib includes
#include
@@ -45,6 +46,18 @@ TEST(XboxGuestTime, RejectsNegativeTimestamps) {
EXPECT_EQ(result.tm_year, 123);
}
+/** @brief The last representable Xbox Unix second converts through the kernel without overflowing. */
+TEST(XboxGuestTime, ConvertsTheLastRepresentableUnixSecond) {
+ std::tm result {};
+ ASSERT_TRUE(sunshine_gmtime(std::numeric_limits::max(), result));
+ EXPECT_EQ(result.tm_year, 138);
+ EXPECT_EQ(result.tm_mon, 0);
+ EXPECT_EQ(result.tm_mday, 19);
+ EXPECT_EQ(result.tm_hour, 3);
+ EXPECT_EQ(result.tm_min, 14);
+ EXPECT_EQ(result.tm_sec, 7);
+}
+
/** @brief Read a normalized Unix timestamp from the running Xbox kernel. */
TEST(XboxGuestTime, ReadsKernelSystemTime) {
timeval now {};
From 0e6d7c72e5fa025ede5200c4908970260d08c99d Mon Sep 17 00:00:00 2001
From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com>
Date: Sat, 28 Nov 2026 11:46:20 -0500
Subject: [PATCH 8/9] ci: install coverage tools from locked wheels
---
.github/workflows/ci-flatpak.yml | 2 +-
.github/workflows/ci-macos.yml | 2 +-
.github/workflows/ci-xbox-original.yml | 2 +-
3 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/.github/workflows/ci-flatpak.yml b/.github/workflows/ci-flatpak.yml
index f2623cd8..f925d462 100644
--- a/.github/workflows/ci-flatpak.yml
+++ b/.github/workflows/ci-flatpak.yml
@@ -89,7 +89,7 @@ jobs:
run: |
set -euo pipefail
uv sync --project third-party/lizardbyte-common --locked --only-group test-c \
- --no-python-downloads --no-install-project
+ --no-build --no-python-downloads --no-install-project
report="${PWD}/${FLATPAK_BUILD_DIR}/coverage.info"
module_dir="$(realpath "${FLATPAK_BUILD_DIR}/..")"
# The sandbox already generated gcov files using its own toolchain.
diff --git a/.github/workflows/ci-macos.yml b/.github/workflows/ci-macos.yml
index f6d77eb9..06a6aa8b 100644
--- a/.github/workflows/ci-macos.yml
+++ b/.github/workflows/ci-macos.yml
@@ -75,7 +75,7 @@ jobs:
- name: Install coverage tools
run: |
uv sync --project third-party/lizardbyte-common --locked --only-group test-c \
- --no-python-downloads --no-install-project
+ --no-build --no-python-downloads --no-install-project
- name: Run unit tests
id: tests
diff --git a/.github/workflows/ci-xbox-original.yml b/.github/workflows/ci-xbox-original.yml
index c9124342..3459d21a 100644
--- a/.github/workflows/ci-xbox-original.yml
+++ b/.github/workflows/ci-xbox-original.yml
@@ -147,7 +147,7 @@ jobs:
shell: bash
run: |
uv sync --project third-party/lizardbyte-common --locked --only-group test-c \
- --no-python-downloads --no-install-project
+ --no-build --no-python-downloads --no-install-project
- name: Run Xbox tests and recover guest coverage
shell: bash
From 7e64f0fb04856853618f13bcae85c58df649ab8c Mon Sep 17 00:00:00 2001
From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com>
Date: Sat, 28 Nov 2026 13:38:18 -0500
Subject: [PATCH 9/9] style(ci): standardize setup step names
---
.github/workflows/ci-android.yml | 4 ++--
.github/workflows/ci-flatpak.yml | 4 ++--
.github/workflows/ci-macos.yml | 4 ++--
.github/workflows/ci-xbox-original.yml | 10 +++++-----
4 files changed, 11 insertions(+), 11 deletions(-)
diff --git a/.github/workflows/ci-android.yml b/.github/workflows/ci-android.yml
index 24339ace..461b2237 100644
--- a/.github/workflows/ci-android.yml
+++ b/.github/workflows/ci-android.yml
@@ -35,7 +35,7 @@ jobs:
with:
submodules: recursive
- - name: Set up Java
+ - name: Setup Java
uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0
with:
distribution: temurin
@@ -59,7 +59,7 @@ jobs:
echo "packages=${packages} ndk;${ndk} cmake;${cmake}"
} >> "${GITHUB_OUTPUT}"
- - name: Set up Android SDK
+ - name: Setup Android SDK
uses: android-actions/setup-android@9fc6c4e9069bf8d3d10b2204b1fb8f6ef7065407 # v3.2.2
with:
packages: ${{ steps.sdk.outputs.packages }}
diff --git a/.github/workflows/ci-flatpak.yml b/.github/workflows/ci-flatpak.yml
index f925d462..f1b0efb6 100644
--- a/.github/workflows/ci-flatpak.yml
+++ b/.github/workflows/ci-flatpak.yml
@@ -71,13 +71,13 @@ jobs:
if: ${{ !cancelled() && hashFiles(format('{0}/tests/test_results.xml', env.FLATPAK_BUILD_DIR)) != '' }}
run: cp "${FLATPAK_BUILD_DIR}/tests/test_results.xml" "${FLATPAK_BUILD_DIR}/test_results.xml"
- - name: Set up Python
+ - name: Setup Python
if: ${{ !cancelled() && steps.tests.outcome == 'success' }}
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: '3.14'
- - name: Set up uv
+ - name: Setup uv
if: ${{ !cancelled() && steps.tests.outcome == 'success' }}
uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
diff --git a/.github/workflows/ci-macos.yml b/.github/workflows/ci-macos.yml
index 06a6aa8b..a86d80ba 100644
--- a/.github/workflows/ci-macos.yml
+++ b/.github/workflows/ci-macos.yml
@@ -61,12 +61,12 @@ jobs:
- name: Build client and tests
run: cmake --build cmake-build-client --parallel
- - name: Set up Python
+ - name: Setup Python
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: '3.14'
- - name: Set up uv
+ - name: Setup uv
uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
enable-cache: true
diff --git a/.github/workflows/ci-xbox-original.yml b/.github/workflows/ci-xbox-original.yml
index 3459d21a..dac3d69a 100644
--- a/.github/workflows/ci-xbox-original.yml
+++ b/.github/workflows/ci-xbox-original.yml
@@ -53,7 +53,7 @@ jobs:
"patch"
"libglx-mesa0" # OpenGL over X11 with Mesa's software renderer.
"libusb-1.0-0" # Shared library used by the xemu binary.
- "xvfb" # Virtual display for xemu. Also installs xauth.
+ "xvfb" # Virtual display for xemu. Also installs xauth.
)
dependencies=("${nxdk_dependencies[@]}" "${sunshine_dependencies[@]}")
sudo apt-get update
@@ -100,11 +100,11 @@ jobs:
mingw-w64-ucrt-x86_64-mesa
mingw-w64-ucrt-x86_64-nasm
- - name: Set up xemu
+ - name: Setup xemu
shell: bash
run: bash scripts/setup-xemu.sh
- - name: Set up software OpenGL (Windows)
+ - name: Setup software OpenGL (Windows)
if: runner.os == 'Windows'
run: |
cp "${MINGW_PREFIX}/bin/"{opengl32,libgallium_wgl}.dll .local/xemu/app/
@@ -132,12 +132,12 @@ jobs:
name: Sunshine-client-XboxOG-${{ runner.os }}
path: artifacts/
- - name: Set up Python
+ - name: Setup Python
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: '3.14'
- - name: Set up uv
+ - name: Setup uv
uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
enable-cache: true