test: Exercise surface configuration in CI (#10427)

This commit is contained in:
Andy Leiserson authored and GitHub committed 2026-11-05 17:20:14 +00:00
1 parent 66d5a64f2e
commit 2ffde61c55
6 files changed
+297

No files matched your search

Generated
+1
View File
@@ -5171,6 +5171,7 @@ dependencies = [
"wgpu-sync",
"wgpu-types",
"windows",
"winit",
]
[[package]]
+12
View File
@@ -40,6 +40,7 @@ This is a table of contents, in the form of the repository's directory structure
- [compile](#wgpu-compile-tests)
- [dependency](#wgpu-dependency-tests)
- [gpu](#wgpu-gpu-tests)
- [surface](#wgpu-surface-tests)
- [trace](#wgpu-trace-tests)
- [validation](#wgpu-validation-tests)
@@ -209,6 +210,17 @@ Normal `#[test]`s will not be found in this test crate, as we use a custom harne
See also the [example tests](#example-tests) for additional GPU tests.
## `wgpu` Surface Tests
- Located in: `tests/tests/wgpu_surface.rs`
- Run with `cargo nextest run --test wgpu_surface`
- Use the standard `#[test]` harness.
These tests exercise configuration of a presentation surface in a real window.
Because they interact with the window system, they are not compatible with
the regular GPU test harness, do not build for wasm or mobile targets, and
are skipped on headless Linux systems.
## `wgpu` Trace Tests
- Located in: `tests/tests/wgpu_trace.rs`
+5
View File
@@ -30,6 +30,10 @@ harness = true
name = "wgpu-validation"
harness = true
[[test]]
name = "wgpu_surface"
harness = false
[features]
webgl = ["wgpu/webgl"]
exhaust = ["wgpu/exhaust"]
@@ -77,6 +81,7 @@ serde.workspace = true
serde_json.workspace = true
[dev-dependencies]
winit.workspace = true
approx.workspace = true
glam.workspace = true
half = { workspace = true, features = ["bytemuck", "std"] }
+3
View File
@@ -74,6 +74,7 @@ mod shader_barycentric;
mod shader_primitive_index;
mod shader_view_format;
mod subgroup_operations;
mod surface_configure_web;
mod texture_binding;
mod texture_blit;
mod texture_bounds;
@@ -165,6 +166,8 @@ fn all_tests() -> Vec<wgpu_test::GpuTestInitializer> {
shader_view_format::all_tests(&mut tests);
shader::all_tests(&mut tests);
subgroup_operations::all_tests(&mut tests);
#[cfg(wasm_test)]
surface_configure_web::all_tests(&mut tests);
texture_binding::all_tests(&mut tests);
texture_blit::all_tests(&mut tests);
texture_bounds::all_tests(&mut tests);
@@ -0,0 +1,86 @@
//! Surface configuration tests for the web backends.
//!
//! On the web a surface target is a canvas, so these can run as ordinary gpu
//! tests: no OS window, no main thread, no display server. The native
//! equivalent cannot work that way, and lives in its own binary that owns the
//! main thread so it can drive `winit`; see `tests/tests/wgpu-surface.rs`.
#![cfg(wasm_test)]
use wgpu_test::GpuTestInitializer;
use wgpu_test::{apply, gpu_test, GpuTestConfiguration};
pub fn all_tests(vec: &mut Vec<GpuTestInitializer>) {
vec.push(SURFACE_CONFIGURE);
}
/// Configure a canvas surface and then reconfigure it at a new size.
///
/// Similar to the native `surface_configure` test in `tests/tests/wgpu-surface.rs`,
/// but doesn't do any rendering.
#[apply(gpu_test!)]
static SURFACE_CONFIGURE: GpuTestConfiguration = GpuTestConfiguration::new()
.parameters(wgpu_test::TestParameters::default())
.run_async(|ctx| async move {
#[cfg(not(target_arch = "wasm32"))]
let _ = ctx;
#[cfg(target_arch = "wasm32")]
{
// Not using the normal testing infrastructure: it creates a canvas for
// adapter initialization but never exposes the resulting surface, and on
// WebGL a surface is bound to its own canvas' context, so we cannot pair a
// fresh canvas with the context's device. Instead, mirror the harness'
// backend, features, and limits.
let instance = wgpu_test::initialize_instance(
wgpu::Backends::from(ctx.adapter_info.backend),
&wgpu_test::TestParameters::default(),
);
let canvas = wgpu_test::initialize_html_canvas();
let surface = instance
.create_surface(wgpu::SurfaceTarget::Canvas(canvas))
.expect("could not create surface from canvas");
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
compatible_surface: Some(&surface),
..Default::default()
})
.await
.expect("no adapter supports the canvas surface");
let (device, _queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: None,
required_features: ctx.device_features,
required_limits: ctx.device_limits.clone(),
default_queue: wgpu::QueueDescriptor { label: None },
experimental_features: wgpu::ExperimentalFeatures::disabled(),
memory_hints: wgpu::MemoryHints::MemoryUsage,
trace: wgpu::Trace::Off,
})
.await
.expect("failed to create device");
assert!(
!surface.get_capabilities(&adapter).formats.is_empty(),
"surface reported no supported formats"
);
let mut config = surface
.get_default_config(&adapter, 256, 256)
.expect("surface is not supported by the adapter");
surface.configure(&device, &config);
// Reconfiguring an already-configured surface tears down the previous
// swapchain, which is a distinct path from the first configure.
config.width = 512;
config.height = 512;
surface.configure(&device, &config);
let wgpu::CurrentSurfaceTexture::Success(frame) = surface.get_current_texture() else {
panic!("could not acquire a surface texture");
};
assert_eq!(frame.texture.width(), 512);
assert_eq!(frame.texture.height(), 512);
}
});
+190
View File
@@ -0,0 +1,190 @@
//! Surface tests that need a real window.
//!
//! These cannot live in the `wgpu-gpu` harness: that harness runs each test on a
//! worker thread, and `winit` requires the main thread. This binary therefore
//! forces `libtest-mimic` to run trials inline on the main thread.
//!
//! For web, this is covered by an ordinary gpu test,
//! `tests/tests/wgpu-gpu/surface_configure_web.rs`.
//!
//! This test only supports environments where creating a window and running
//! integration tests is readily supported, meaning it:
//! - does not build for wasm,
//! - does not build for iOS, tvOS, watchOS, or Android,
//! - marks itself as "ignored" on Linux if none of `WAYLAND_DISPLAY`, `WAYLAND_SOCKET`, or
//! `DISPLAY` is set.
#[cfg(any(
target_arch = "wasm32",
all(target_vendor = "apple", not(target_os = "macos")),
target_os = "android",
))]
fn main() {}
#[cfg(all(
not(target_arch = "wasm32"),
any(not(target_vendor = "apple"), target_os = "macos"),
not(target_os = "android"),
))]
fn main() {
native::main();
}
#[cfg(all(
not(target_arch = "wasm32"),
any(not(target_vendor = "apple"), target_os = "macos"),
not(target_os = "android"),
))]
mod native {
use std::sync::Arc;
use winit::{
application::ApplicationHandler,
event_loop::{ActiveEventLoop, EventLoop, OwnedDisplayHandle},
platform::run_on_demand::EventLoopExtRunOnDemand,
window::{Window, WindowAttributes},
};
struct Harness {
failure: Option<String>,
}
impl ApplicationHandler for Harness {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
let window = Arc::new(
event_loop
.create_window(WindowAttributes::default().with_visible(false))
.expect("failed to create window"),
);
let display_handle = event_loop.owned_display_handle();
if let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
surface_configure(window, display_handle)
})) {
let message = if let Some(s) = e.downcast_ref::<&str>() {
(*s).to_owned()
} else if let Some(s) = e.downcast_ref::<String>() {
s.clone()
} else {
"panic with non-string payload".to_owned()
};
self.failure = Some(message);
}
event_loop.exit();
}
fn window_event(
&mut self,
_: &ActiveEventLoop,
_: winit::window::WindowId,
_: winit::event::WindowEvent,
) {
}
}
fn surface_configure(window: Arc<Window>, display_handle: OwnedDisplayHandle) {
let instance = wgpu::Instance::new(
wgpu::InstanceDescriptor::new_with_display_handle_from_env(Box::new(display_handle)),
);
let surface = instance.create_surface(window).unwrap();
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
compatible_surface: Some(&surface),
..Default::default()
}))
.expect("no adapter supports the window surface");
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
label: None,
required_features: wgpu::Features::empty(),
required_limits:
wgpu::Limits::downlevel_webgl2_defaults().using_resolution(adapter.limits()),
default_queue: wgpu::QueueDescriptor { label: None },
experimental_features: wgpu::ExperimentalFeatures::disabled(),
memory_hints: wgpu::MemoryHints::MemoryUsage,
trace: wgpu::Trace::Off,
}))
.unwrap();
let mut config = surface.get_default_config(&adapter, 256, 256).unwrap();
surface.configure(&device, &config);
// Reconfigure the surface (regression test for https://github.com/gfx-rs/wgpu/issues/10410).
config.width = 512;
config.height = 512;
surface.configure(&device, &config);
let current = surface.get_current_texture();
let wgpu::CurrentSurfaceTexture::Success(frame) = current else {
panic!("Unexpected get_current_texture result: {:?}", current);
};
let view = frame
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
enc.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::GREEN),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
queue.submit(Some(enc.finish()));
queue.present(frame);
}
pub fn main() {
let mut args = libtest_mimic::Arguments::from_args();
// `winit` requires the main thread; this makes libtest-mimic run inline.
args.test_threads = Some(1);
let trial = libtest_mimic::Trial::test("surface_configure", || {
let mut builder = EventLoop::builder();
#[cfg(target_os = "macos")]
{
use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS};
// Keep the test process out of the Dock and stop it stealing focus.
builder.with_activation_policy(ActivationPolicy::Prohibited);
}
let mut event_loop = match builder.build() {
Ok(event_loop) => event_loop,
Err(e) => panic!("could not create event loop (no display?): {e}"),
};
let mut harness = Harness { failure: None };
event_loop.run_app_on_demand(&mut harness).unwrap();
match harness.failure {
Some(failure) => Err(libtest_mimic::Failed::from(failure)),
None => Ok(()),
}
});
// Similar to logic in [`winit::event_loop::EventLoop::new`][winit], but we do it
// up front so we can mark the test as ignored if there is no display.
//
// [winit]: <https://github.com/rust-windowing/winit/blob/2fd05d48b521846c5ae22c6f0a66e10bc0c91ca6/winit/src/platform_impl/linux/mod.rs#L89>.
#[cfg(any(
target_os = "linux",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
let trial = {
let have_display = ["WAYLAND_DISPLAY", "WAYLAND_SOCKET", "DISPLAY"]
.iter()
.any(|var| std::env::var(var).is_ok_and(|s| !s.is_empty()));
trial.with_ignored_flag(!have_display)
};
libtest_mimic::run(&args, vec![trial]).exit_if_failed();
}
}