Base: codex-main originale (prima del fork aKode)
This commit is contained in:
402
bazel/rules/testing/wine/src/lib.rs
Normal file
402
bazel/rules/testing/wine/src/lib.rs
Normal file
@@ -0,0 +1,402 @@
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
compile_error!("wine_test_support can only run on Linux");
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::fs;
|
||||
use std::future::Future;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command as StdCommand;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use tempfile::TempDir;
|
||||
use tokio::process::Child;
|
||||
use tokio::process::ChildStdout;
|
||||
use tokio::process::Command as TokioCommand;
|
||||
|
||||
/// Builds a command that runs a Windows executable in an isolated Wine prefix.
|
||||
pub struct WineTestCommand {
|
||||
executable: PathBuf,
|
||||
args: Vec<OsString>,
|
||||
env: Vec<(OsString, OsString)>,
|
||||
}
|
||||
|
||||
/// Owns a Wine process and its isolated wineserver.
|
||||
///
|
||||
/// Call [`Self::scope`] or [`Self::shutdown`] on every successful path. A
|
||||
/// normal unguarded drop panics, while a drop during unwinding performs
|
||||
/// blocking cleanup without introducing a second panic.
|
||||
pub struct WineTestProcess {
|
||||
processes: Option<WineProcesses>,
|
||||
}
|
||||
|
||||
struct WineProcesses {
|
||||
child: Child,
|
||||
cleanup_complete: bool,
|
||||
prefix: TempDir,
|
||||
runtime: WineRuntimePaths,
|
||||
}
|
||||
|
||||
struct WineRuntimePaths {
|
||||
dll_path: PathBuf,
|
||||
powershell_runtime: PathBuf,
|
||||
wine: PathBuf,
|
||||
wineserver: PathBuf,
|
||||
}
|
||||
|
||||
impl WineTestCommand {
|
||||
/// Creates a Wine command for `executable`.
|
||||
pub fn new(executable: impl Into<PathBuf>) -> Self {
|
||||
Self {
|
||||
executable: executable.into(),
|
||||
args: Vec::new(),
|
||||
env: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds an argument passed to the Windows executable.
|
||||
#[must_use]
|
||||
pub fn arg(mut self, arg: impl Into<OsString>) -> Self {
|
||||
self.args.push(arg.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds or overrides an environment variable for the Wine process.
|
||||
#[must_use]
|
||||
pub fn env(mut self, key: impl Into<OsString>, value: impl Into<OsString>) -> Self {
|
||||
self.env.push((key.into(), value.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// Starts the Windows executable with a fresh `WINEPREFIX`.
|
||||
pub fn spawn(self) -> Result<WineTestProcess> {
|
||||
let runtime = WineRuntimePaths::from_runfiles()?;
|
||||
let prefix = TempDir::new().context("create isolated Wine prefix")?;
|
||||
install_powershell_runtime(prefix.path(), &runtime.powershell_runtime)?;
|
||||
let mut command = StdCommand::new(&runtime.wine);
|
||||
configure_wine_environment(&mut command, &runtime, prefix.path());
|
||||
command
|
||||
.arg(self.executable)
|
||||
.args(self.args)
|
||||
.envs(self.env)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit());
|
||||
|
||||
let mut command = TokioCommand::from(command);
|
||||
command.kill_on_drop(true);
|
||||
let child = command
|
||||
.spawn()
|
||||
.context("start Windows process under Wine")?;
|
||||
|
||||
Ok(WineTestProcess {
|
||||
processes: Some(WineProcesses {
|
||||
child,
|
||||
cleanup_complete: false,
|
||||
prefix,
|
||||
runtime,
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl WineTestProcess {
|
||||
/// Returns the host path to this process's isolated Wine prefix.
|
||||
pub fn prefix_path(&self) -> &Path {
|
||||
let Some(processes) = self.processes.as_ref() else {
|
||||
panic!("Wine process guard is missing");
|
||||
};
|
||||
processes.prefix.path()
|
||||
}
|
||||
|
||||
/// Takes the piped standard output of the Wine process.
|
||||
///
|
||||
/// This may only be called once for a process created by
|
||||
/// [`WineTestCommand::spawn`].
|
||||
pub fn take_stdout(&mut self) -> ChildStdout {
|
||||
let Some(processes) = self.processes.as_mut() else {
|
||||
panic!("Wine process guard is missing");
|
||||
};
|
||||
let Some(stdout) = processes.child.stdout.take() else {
|
||||
panic!("Wine process stdout has already been taken");
|
||||
};
|
||||
stdout
|
||||
}
|
||||
|
||||
/// Runs `future`, then asynchronously tears down Wine before returning.
|
||||
///
|
||||
/// If both the scoped operation and teardown fail, the operation error is
|
||||
/// returned with the teardown error attached as context. A panic in the
|
||||
/// scoped operation triggers the blocking unwind-time fallback instead.
|
||||
pub async fn scope<T>(self, future: impl Future<Output = Result<T>>) -> Result<T> {
|
||||
let scope_result = future.await;
|
||||
let shutdown_result = self.shutdown().await;
|
||||
match (scope_result, shutdown_result) {
|
||||
(Ok(value), Ok(())) => Ok(value),
|
||||
(Err(error), Ok(())) => Err(error),
|
||||
(Ok(_), Err(error)) => Err(error),
|
||||
(Err(error), Err(shutdown_error)) => {
|
||||
Err(error.context(format!("Wine teardown also failed: {shutdown_error:#}")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Kills the Windows process, waits for it, and stops its wineserver.
|
||||
pub async fn shutdown(mut self) -> Result<()> {
|
||||
let Some(processes) = self.processes.as_mut() else {
|
||||
anyhow::bail!("Wine process guard is missing");
|
||||
};
|
||||
let result = processes.shutdown().await;
|
||||
self.processes.take();
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WineTestProcess {
|
||||
fn drop(&mut self) {
|
||||
// Panicking here starts unwinding, after which WineProcesses performs
|
||||
// the blocking fallback while its field is dropped.
|
||||
if self.processes.is_some() && !std::thread::panicking() {
|
||||
panic!("WineTestProcess dropped without async teardown");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WineRuntimePaths {
|
||||
fn from_runfiles() -> Result<Self> {
|
||||
let wine = codex_utils_cargo_bin::cargo_bin("wine")?;
|
||||
let runtime_marker = codex_utils_cargo_bin::cargo_bin("wine-runtime-marker")?;
|
||||
let dll_path = runtime_marker
|
||||
.parent()
|
||||
.context("locate Wine runtime directory")?
|
||||
.to_path_buf();
|
||||
let wineserver = codex_utils_cargo_bin::cargo_bin("wineserver")?;
|
||||
let powershell_runtime = codex_utils_cargo_bin::cargo_bin("pwsh-runtime-marker")?
|
||||
.parent()
|
||||
.context("locate PowerShell runtime directory")?
|
||||
.to_path_buf();
|
||||
Ok(Self {
|
||||
dll_path,
|
||||
powershell_runtime,
|
||||
wine,
|
||||
wineserver,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl WineProcesses {
|
||||
async fn shutdown(&mut self) -> Result<()> {
|
||||
let (kill_result, check_exit_status) = match self.child.try_wait() {
|
||||
Ok(Some(_)) => (Ok(()), true),
|
||||
Ok(None) => (
|
||||
self.child
|
||||
.start_kill()
|
||||
.context("kill Windows process running under Wine"),
|
||||
false,
|
||||
),
|
||||
Err(error) => (Err(error).context("check Windows process status"), false),
|
||||
};
|
||||
let wait_result = self
|
||||
.child
|
||||
.wait()
|
||||
.await
|
||||
.context("wait for Windows process running under Wine")
|
||||
.and_then(|status| {
|
||||
anyhow::ensure!(
|
||||
!check_exit_status || status.success(),
|
||||
"Windows process exited with {status}"
|
||||
);
|
||||
Ok(())
|
||||
});
|
||||
let wineserver_result = async {
|
||||
let mut command = TokioCommand::from(self.stop_wineserver_command());
|
||||
let status = command.status().await.context("stop isolated wineserver")?;
|
||||
anyhow::ensure!(status.success(), "wineserver exited with {status}");
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
|
||||
// Every cleanup action has been attempted, so an individual error
|
||||
// should not cause the blocking fallback to repeat them.
|
||||
self.cleanup_complete = true;
|
||||
kill_result?;
|
||||
wait_result?;
|
||||
wineserver_result
|
||||
}
|
||||
|
||||
fn stop_wineserver_command(&self) -> StdCommand {
|
||||
let mut command = StdCommand::new(&self.runtime.wineserver);
|
||||
configure_wine_environment(&mut command, &self.runtime, self.prefix.path());
|
||||
command
|
||||
.args(["-k", "-w"])
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
command
|
||||
}
|
||||
|
||||
fn shutdown_blocking(&mut self) {
|
||||
log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup starting for prefix {}",
|
||||
self.prefix.path().display()
|
||||
));
|
||||
if let Err(error) = self.child.start_kill() {
|
||||
log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup could not kill its child: {error}"
|
||||
));
|
||||
}
|
||||
|
||||
log_panic_cleanup(format_args!("Wine panic cleanup waiting for its child"));
|
||||
loop {
|
||||
match self.child.try_wait() {
|
||||
Ok(Some(status)) => {
|
||||
log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup child exited with {status}"
|
||||
));
|
||||
break;
|
||||
}
|
||||
Ok(None) => std::thread::sleep(Duration::from_millis(10)),
|
||||
Err(error) => {
|
||||
log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup could not wait for its child: {error}"
|
||||
));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log_panic_cleanup(format_args!("Wine panic cleanup stopping its wineserver"));
|
||||
match self.stop_wineserver_command().status() {
|
||||
Ok(status) => log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup wineserver exited with {status}"
|
||||
)),
|
||||
Err(error) => log_panic_cleanup(format_args!(
|
||||
"Wine panic cleanup could not stop its wineserver: {error}"
|
||||
)),
|
||||
}
|
||||
self.cleanup_complete = true;
|
||||
log_panic_cleanup(format_args!("Wine panic cleanup complete"));
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WineProcesses {
|
||||
fn drop(&mut self) {
|
||||
// Never introduce a second panic while unwinding. Blocking here is
|
||||
// intentional because test failures must not leak Wine children.
|
||||
if !self.cleanup_complete && std::thread::panicking() {
|
||||
self.shutdown_blocking();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn log_panic_cleanup(args: std::fmt::Arguments<'_>) {
|
||||
let _ = writeln!(std::io::stderr().lock(), "{args}");
|
||||
}
|
||||
|
||||
fn configure_wine_environment(command: &mut StdCommand, runtime: &WineRuntimePaths, prefix: &Path) {
|
||||
command
|
||||
.env_remove("DISPLAY")
|
||||
.env("HOME", prefix)
|
||||
.env("XDG_RUNTIME_DIR", prefix)
|
||||
.env("WINEARCH", "win64")
|
||||
.env("WINEPREFIX", prefix)
|
||||
.env("WINEDLLPATH", &runtime.dll_path)
|
||||
.env("WINESERVER", &runtime.wineserver)
|
||||
.env("WINEDEBUG", "-all")
|
||||
.env("WINEDLLOVERRIDES", "mscoree,mshtml,winegstreamer=")
|
||||
.env("LANG", "C.UTF-8")
|
||||
.env("LC_ALL", "C.UTF-8")
|
||||
.env("LC_CTYPE", "C.UTF-8")
|
||||
.env("TEMP", r"C:\windows\temp")
|
||||
.env("TMP", r"C:\windows\temp");
|
||||
}
|
||||
|
||||
/// Installs the complete pinned PowerShell distribution where Windows tooling
|
||||
/// expects to discover PowerShell 7.
|
||||
///
|
||||
/// `pwsh.exe` is not a standalone executable: it loads its adjacent .NET host,
|
||||
/// managed assemblies, native libraries, modules, and configuration files at
|
||||
/// startup. The Bazel archive is exposed through runfiles rather than a normal
|
||||
/// Windows installation, while shell detection deliberately probes the
|
||||
/// conventional `C:\Program Files\PowerShell\7` fallback. We therefore have to
|
||||
/// reproduce the archive's directory tree inside each isolated Wine prefix;
|
||||
/// copying only the executable would fail before a command could run.
|
||||
fn install_powershell_runtime(prefix: &Path, runtime: &Path) -> Result<()> {
|
||||
let powershell_parent = prefix
|
||||
.join("drive_c")
|
||||
.join("Program Files")
|
||||
.join("PowerShell");
|
||||
fs::create_dir_all(&powershell_parent).context("create PowerShell installation parent")?;
|
||||
let destination = powershell_parent.join("7");
|
||||
materialize_runtime_directory(runtime, &destination)
|
||||
}
|
||||
|
||||
/// Recursively reproduces a runfiles directory in a writable Wine prefix.
|
||||
///
|
||||
/// Bazel runfiles may be immutable, represented by a symlink forest, and may
|
||||
/// contain the PowerShell distribution on a different filesystem from the
|
||||
/// temporary prefix. Hard links avoid repeatedly copying the roughly
|
||||
/// hundred-megabyte runtime when both locations share a filesystem; the copy
|
||||
/// fallback preserves correctness for sandbox or remote-execution layouts
|
||||
/// where cross-device hard links are unavailable.
|
||||
fn materialize_runtime_directory(source: &Path, destination: &Path) -> Result<()> {
|
||||
fs::create_dir_all(destination).with_context(|| {
|
||||
format!(
|
||||
"create PowerShell runtime directory {}",
|
||||
destination.display()
|
||||
)
|
||||
})?;
|
||||
for entry in fs::read_dir(source)
|
||||
.with_context(|| format!("read PowerShell runtime directory {}", source.display()))?
|
||||
{
|
||||
let entry = entry.context("read PowerShell runtime entry")?;
|
||||
let source_path = entry.path();
|
||||
let destination_path = destination.join(entry.file_name());
|
||||
// Local Bazel runfiles trees expose external-repository files as
|
||||
// symlinks. Resolve those trusted runfiles entries before inspecting
|
||||
// or linking them so the writable prefix contains ordinary files.
|
||||
let resolved_source_path = fs::canonicalize(&source_path).with_context(|| {
|
||||
format!("resolve PowerShell runtime entry {}", source_path.display())
|
||||
})?;
|
||||
let file_type = fs::metadata(&resolved_source_path)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"inspect PowerShell runtime entry {}",
|
||||
resolved_source_path.display()
|
||||
)
|
||||
})?
|
||||
.file_type();
|
||||
if file_type.is_dir() {
|
||||
// PowerShell resolves assemblies and modules by their relative
|
||||
// locations, so flattening the archive is not an option.
|
||||
materialize_runtime_directory(&resolved_source_path, &destination_path)?;
|
||||
} else if file_type.is_file() {
|
||||
// A hard link gives each prefix the expected installation layout
|
||||
// without duplicating the large runtime in the common local case.
|
||||
if fs::hard_link(&resolved_source_path, &destination_path).is_err() {
|
||||
// Cross-device links are common under Bazel sandboxing and
|
||||
// remote execution, where an ordinary copy is still valid.
|
||||
fs::copy(&resolved_source_path, &destination_path).with_context(|| {
|
||||
format!(
|
||||
"copy PowerShell runtime file {} to {}",
|
||||
resolved_source_path.display(),
|
||||
destination_path.display()
|
||||
)
|
||||
})?;
|
||||
}
|
||||
} else {
|
||||
anyhow::bail!(
|
||||
"unsupported PowerShell runtime entry type at {}",
|
||||
source_path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lib_tests.rs"]
|
||||
mod tests;
|
||||
451
bazel/rules/testing/wine/src/lib_tests.rs
Normal file
451
bazel/rules/testing/wine/src/lib_tests.rs
Normal file
@@ -0,0 +1,451 @@
|
||||
use std::any::Any;
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::future::Future;
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use codex_utils_pty::SpawnedProcess;
|
||||
use codex_utils_pty::TerminalSize;
|
||||
use futures::FutureExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::process::Command as TokioCommand;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::WineRuntimePaths;
|
||||
use super::WineTestCommand;
|
||||
use super::WineTestProcess;
|
||||
use super::install_powershell_runtime;
|
||||
|
||||
async fn waiting_smoke_process() -> Result<WineTestProcess> {
|
||||
let executable = codex_utils_cargo_bin::cargo_bin("wine-smoke")?;
|
||||
let mut process = WineTestCommand::new(executable).arg("--wait").spawn()?;
|
||||
let mut lines = BufReader::new(process.take_stdout()).lines();
|
||||
let ready_line = lines
|
||||
.next_line()
|
||||
.await?
|
||||
.context("Windows smoke process exited before becoming ready")?;
|
||||
assert_eq!(ready_line, "WINE_TEST_READY");
|
||||
Ok(process)
|
||||
}
|
||||
|
||||
fn prefix_path(process: &WineTestProcess) -> PathBuf {
|
||||
process
|
||||
.processes
|
||||
.as_ref()
|
||||
.expect("Wine process guard")
|
||||
.prefix
|
||||
.path()
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
fn assert_prefix_removed(prefix: &Path) {
|
||||
assert!(
|
||||
!prefix.exists(),
|
||||
"Wine prefix remains: {}",
|
||||
prefix.display()
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_panic_message(panic: Box<dyn Any + Send>, expected: &str) {
|
||||
assert_eq!(panic.downcast_ref::<&str>(), Some(&expected));
|
||||
}
|
||||
|
||||
async fn assert_future_panics<T>(future: impl Future<Output = T>, expected: &str) {
|
||||
let panic = match AssertUnwindSafe(future).catch_unwind().await {
|
||||
Ok(_) => panic!("future should panic"),
|
||||
Err(panic) => panic,
|
||||
};
|
||||
assert_panic_message(panic, expected);
|
||||
}
|
||||
|
||||
async fn process_with_failing_wineserver_stop() -> Result<WineTestProcess> {
|
||||
let mut process = waiting_smoke_process().await?;
|
||||
let processes = process.processes.as_mut().expect("Wine process guard");
|
||||
|
||||
let mut command = TokioCommand::from(processes.stop_wineserver_command());
|
||||
let status = command
|
||||
.status()
|
||||
.await
|
||||
.context("pre-stop isolated wineserver")?;
|
||||
assert!(status.success(), "wineserver exited with {status}");
|
||||
|
||||
processes.runtime.wineserver = processes.prefix.path().join("missing-wineserver");
|
||||
Ok(process)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_without_teardown_panics() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
assert_future_panics(
|
||||
async move { drop(process) },
|
||||
"WineTestProcess dropped without async teardown",
|
||||
)
|
||||
.await;
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_while_panicking_does_not_panic_again() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
assert_future_panics(
|
||||
async move {
|
||||
let _process = process;
|
||||
panic!("sentinel panic");
|
||||
},
|
||||
"sentinel panic",
|
||||
)
|
||||
.await;
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn async_teardown_disarms_drop_bomb() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
process.shutdown().await?;
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn take_stdout_panics_when_called_twice() -> Result<()> {
|
||||
let mut process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
assert_future_panics(
|
||||
async {
|
||||
process.take_stdout();
|
||||
},
|
||||
"Wine process stdout has already been taken",
|
||||
)
|
||||
.await;
|
||||
process.shutdown().await?;
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scope_returns_value_and_tears_down() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
let value = process
|
||||
.scope(async { Ok::<_, anyhow::Error>("scope value") })
|
||||
.await?;
|
||||
assert_eq!(value, "scope value");
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scope_returns_body_error_and_tears_down() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
|
||||
let error = process
|
||||
.scope(async { Err::<(), _>(anyhow!("scope body failed")) })
|
||||
.await
|
||||
.expect_err("scope body should fail");
|
||||
|
||||
assert_eq!(error.to_string(), "scope body failed");
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scope_panic_preserves_panic_and_tears_down() -> Result<()> {
|
||||
let process = waiting_smoke_process().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
|
||||
assert_future_panics(
|
||||
process.scope::<()>(async { panic!("scope panic") }),
|
||||
"scope panic",
|
||||
)
|
||||
.await;
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_reports_nonzero_process_exit() -> Result<()> {
|
||||
let executable = codex_utils_cargo_bin::cargo_bin("wine-smoke")?;
|
||||
let mut process = WineTestCommand::new(executable).arg("--fail").spawn()?;
|
||||
let prefix = prefix_path(&process);
|
||||
let status = process
|
||||
.processes
|
||||
.as_mut()
|
||||
.expect("Wine process guard")
|
||||
.child
|
||||
.wait()
|
||||
.await?;
|
||||
assert!(
|
||||
!status.success(),
|
||||
"Windows smoke process unexpectedly passed"
|
||||
);
|
||||
|
||||
let error = process.shutdown().await.expect_err("shutdown should fail");
|
||||
|
||||
assert!(error.to_string().starts_with("Windows process exited with"));
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scope_preserves_body_error_when_teardown_also_fails() -> Result<()> {
|
||||
let process = process_with_failing_wineserver_stop().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
|
||||
let error = process
|
||||
.scope(async { Err::<(), _>(anyhow!("scope body failed")) })
|
||||
.await
|
||||
.expect_err("scope body and teardown should fail");
|
||||
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.starts_with("Wine teardown also failed: stop isolated wineserver"),
|
||||
"unexpected error: {error:#}"
|
||||
);
|
||||
assert_eq!(
|
||||
error.chain().last().map(ToString::to_string),
|
||||
Some("scope body failed".to_string())
|
||||
);
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_returns_teardown_error() -> Result<()> {
|
||||
let process = process_with_failing_wineserver_stop().await?;
|
||||
let prefix = prefix_path(&process);
|
||||
|
||||
let error = process
|
||||
.shutdown()
|
||||
.await
|
||||
.expect_err("shutdown should report a wineserver failure");
|
||||
|
||||
assert_eq!(error.to_string(), "stop isolated wineserver");
|
||||
assert_prefix_removed(&prefix);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_runtime_is_materialized_at_the_windows_fallback_path() -> Result<()> {
|
||||
let prefix = TempDir::new()?;
|
||||
let runtime = TempDir::new()?;
|
||||
fs::create_dir(runtime.path().join("Modules"))?;
|
||||
fs::write(runtime.path().join("pwsh.exe"), b"pwsh")?;
|
||||
fs::write(runtime.path().join("Modules").join("marker.txt"), b"module")?;
|
||||
|
||||
install_powershell_runtime(prefix.path(), runtime.path())?;
|
||||
|
||||
let installed = prefix
|
||||
.path()
|
||||
.join("drive_c")
|
||||
.join("Program Files")
|
||||
.join("PowerShell")
|
||||
.join("7");
|
||||
assert_eq!(fs::read(installed.join("pwsh.exe"))?, b"pwsh");
|
||||
assert_eq!(
|
||||
fs::read(installed.join("Modules").join("marker.txt"))?,
|
||||
b"module"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_runtime_follows_runfiles_symlinks() -> Result<()> {
|
||||
let prefix = TempDir::new()?;
|
||||
let runtime = TempDir::new()?;
|
||||
let backing = TempDir::new()?;
|
||||
let backing_file = backing.path().join("pwsh.exe");
|
||||
fs::write(&backing_file, b"pwsh")?;
|
||||
std::os::unix::fs::symlink(&backing_file, runtime.path().join("pwsh.exe"))?;
|
||||
|
||||
install_powershell_runtime(prefix.path(), runtime.path())?;
|
||||
|
||||
let installed = prefix
|
||||
.path()
|
||||
.join("drive_c")
|
||||
.join("Program Files")
|
||||
.join("PowerShell")
|
||||
.join("7")
|
||||
.join("pwsh.exe");
|
||||
assert_eq!(fs::read(installed)?, b"pwsh");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pinned_powershell_runs_under_wine_with_a_pty() -> Result<()> {
|
||||
// Keep this integration smoke test local to the Wine support crate. The
|
||||
// production-shaped PowerShell launch path belongs to exec-server tests.
|
||||
// The marker makes the assertion resilient to Wine or PTY startup chatter.
|
||||
const POWERSHELL_SMOKE_MARKER: &str = "WINE_PWSH_SMOKE";
|
||||
// Besides proving that the pinned runtime starts, report the properties
|
||||
// that shell detection and command construction rely on: PowerShell 7 Core
|
||||
// running with Windows semantics and a backslash path separator.
|
||||
const POWERSHELL_SMOKE_SCRIPT: &str = concat!(
|
||||
"$ErrorActionPreference = 'Stop'; ",
|
||||
"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); ",
|
||||
"$separatorCode = [int]([System.IO.Path]::DirectorySeparatorChar); ",
|
||||
"if ($PSVersionTable.PSVersion.Major -ne 7) { throw 'expected PowerShell 7' }; ",
|
||||
"if ($PSVersionTable.PSEdition -ne 'Core') { throw 'expected PowerShell Core' }; ",
|
||||
"if (-not $IsWindows) { throw 'expected Windows semantics' }; ",
|
||||
"if ($separatorCode -ne 92) { throw 'expected backslash path separator' }; ",
|
||||
"Write-Output ('WINE_PWSH_SMOKE|' + ",
|
||||
"$PSVersionTable.PSVersion.ToString() + '|' + ",
|
||||
"$PSVersionTable.PSEdition + '|' + ",
|
||||
"$IsWindows.ToString().ToLowerInvariant() + '|' + $separatorCode)",
|
||||
);
|
||||
let runtime = WineRuntimePaths::from_runfiles()?;
|
||||
let prefix = TempDir::new()?;
|
||||
install_powershell_runtime(prefix.path(), &runtime.powershell_runtime)?;
|
||||
let mut env = std::env::vars().collect::<HashMap<_, _>>();
|
||||
env.remove("DISPLAY");
|
||||
env.extend([
|
||||
(
|
||||
"HOME".to_string(),
|
||||
prefix.path().to_string_lossy().into_owned(),
|
||||
),
|
||||
(
|
||||
"XDG_RUNTIME_DIR".to_string(),
|
||||
prefix.path().to_string_lossy().into_owned(),
|
||||
),
|
||||
("WINEARCH".to_string(), "win64".to_string()),
|
||||
(
|
||||
"WINEPREFIX".to_string(),
|
||||
prefix.path().to_string_lossy().into_owned(),
|
||||
),
|
||||
(
|
||||
"WINEDLLPATH".to_string(),
|
||||
runtime.dll_path.to_string_lossy().into_owned(),
|
||||
),
|
||||
(
|
||||
"WINESERVER".to_string(),
|
||||
runtime.wineserver.to_string_lossy().into_owned(),
|
||||
),
|
||||
("WINEDEBUG".to_string(), "-all".to_string()),
|
||||
(
|
||||
"WINEDLLOVERRIDES".to_string(),
|
||||
"mscoree,mshtml,winegstreamer=".to_string(),
|
||||
),
|
||||
("LANG".to_string(), "C.UTF-8".to_string()),
|
||||
("LC_ALL".to_string(), "C.UTF-8".to_string()),
|
||||
("LC_CTYPE".to_string(), "C.UTF-8".to_string()),
|
||||
("TEMP".to_string(), r"C:\windows\temp".to_string()),
|
||||
("TMP".to_string(), r"C:\windows\temp".to_string()),
|
||||
]);
|
||||
let args = [
|
||||
r"C:\Program Files\PowerShell\7\pwsh.exe".to_string(),
|
||||
"-NoLogo".to_string(),
|
||||
"-NoProfile".to_string(),
|
||||
"-NonInteractive".to_string(),
|
||||
"-Command".to_string(),
|
||||
POWERSHELL_SMOKE_SCRIPT.to_string(),
|
||||
];
|
||||
let wine = runtime.wine.to_string_lossy().into_owned();
|
||||
let SpawnedProcess {
|
||||
session,
|
||||
mut stdout_rx,
|
||||
mut stderr_rx,
|
||||
exit_rx,
|
||||
} = codex_utils_pty::spawn_pty_process(
|
||||
&wine,
|
||||
&args,
|
||||
prefix.path(),
|
||||
&env,
|
||||
/*arg0*/ &None,
|
||||
TerminalSize::default(),
|
||||
codex_utils_pty::ChildFds::Inherited(&[]),
|
||||
)
|
||||
.await?;
|
||||
let command_result = timeout(Duration::from_secs(90), async {
|
||||
let stdout = async {
|
||||
let mut output = Vec::new();
|
||||
while let Some(chunk) = stdout_rx.recv().await {
|
||||
output.extend(chunk);
|
||||
}
|
||||
output
|
||||
};
|
||||
let stderr = async {
|
||||
let mut output = Vec::new();
|
||||
while let Some(chunk) = stderr_rx.recv().await {
|
||||
output.extend(chunk);
|
||||
}
|
||||
output
|
||||
};
|
||||
let (stdout, stderr, exit_code) = tokio::join!(stdout, stderr, exit_rx);
|
||||
Ok::<_, anyhow::Error>((stdout, stderr, exit_code.context("wait for PowerShell")?))
|
||||
})
|
||||
.await
|
||||
.context("PowerShell smoke test timed out")
|
||||
.and_then(std::convert::identity);
|
||||
drop(session);
|
||||
let shutdown_result = timeout(Duration::from_secs(10), async {
|
||||
let mut command = TokioCommand::new(&runtime.wineserver);
|
||||
command
|
||||
.args(["-k", "-w"])
|
||||
.env("HOME", prefix.path())
|
||||
.env("WINEPREFIX", prefix.path())
|
||||
.env("XDG_RUNTIME_DIR", prefix.path())
|
||||
.kill_on_drop(true);
|
||||
let status = command.status().await.context("stop isolated wineserver")?;
|
||||
anyhow::ensure!(
|
||||
status.success() || status.code() == Some(1),
|
||||
"wineserver exited with {status}"
|
||||
);
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})
|
||||
.await
|
||||
.context("stop isolated wineserver timed out")
|
||||
.and_then(std::convert::identity);
|
||||
let (stdout, stderr, exit_code) = match (command_result, shutdown_result) {
|
||||
(Ok(output), Ok(())) => output,
|
||||
(Err(error), Ok(())) => return Err(error),
|
||||
(Ok(_), Err(error)) => return Err(error),
|
||||
(Err(error), Err(shutdown_error)) => {
|
||||
return Err(error.context(format!("Wine teardown also failed: {shutdown_error:#}")));
|
||||
}
|
||||
};
|
||||
anyhow::ensure!(
|
||||
exit_code == 0,
|
||||
"PowerShell exited with {}; stderr: {}",
|
||||
exit_code,
|
||||
String::from_utf8_lossy(&stderr),
|
||||
);
|
||||
let output = String::from_utf8(stdout)?;
|
||||
let marker_start = output
|
||||
.find(POWERSHELL_SMOKE_MARKER)
|
||||
.with_context(|| format!("PowerShell smoke marker was missing from {output:?}"))?;
|
||||
let smoke = output[marker_start..]
|
||||
.lines()
|
||||
.next()
|
||||
.context("PowerShell smoke marker line was incomplete")?
|
||||
.trim_end_matches('\r');
|
||||
let fields = smoke.split('|').collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
fields.len(),
|
||||
5,
|
||||
"unexpected PowerShell smoke output: {smoke}"
|
||||
);
|
||||
assert_eq!(fields[0], POWERSHELL_SMOKE_MARKER);
|
||||
assert_eq!(
|
||||
fields[1].split('.').next(),
|
||||
Some("7"),
|
||||
"expected PowerShell 7.x, got {}",
|
||||
fields[1],
|
||||
);
|
||||
assert_eq!(&fields[2..], &["Core", "true", "92"]);
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user