| 1 |
use anyhow::{bail, Result}; |
| 2 |
use fs_err as fs; |
| 3 |
use maturin::Target; |
| 4 |
use normpath::PathExt as _; |
| 5 |
use std::path::Path; |
| 6 |
use std::path::PathBuf; |
| 7 |
use std::process::{Command, Stdio}; |
| 8 |
use std::{env, io, str}; |
| 9 |
|
| 10 |
pub mod develop; |
| 11 |
pub mod errors; |
| 12 |
pub mod integration; |
| 13 |
pub mod metadata; |
| 14 |
pub mod other; |
| 15 |
|
| 16 |
#[derive(Clone, Copy, PartialEq, Eq)] |
| 17 |
pub enum TestInstallBackend { |
| 18 |
Pip, |
| 19 |
Uv, |
| 20 |
} |
| 21 |
|
| 22 |
/// Check that the package is either not installed or works correctly |
| 23 |
pub fn check_installed(package: &Path, python: &Path) -> Result<()> { |
| 24 |
let path = if cfg!(windows) { |
| 25 |
// on Windows, also add Scripts to PATH |
| 26 |
let python_dir = python.parent().unwrap(); |
| 27 |
env::join_paths([&python_dir.join("Scripts"), python_dir])?.into() |
| 28 |
} else { |
| 29 |
python.parent().unwrap().to_path_buf() |
| 30 |
}; |
| 31 |
let mut check_installed = Path::new(package) |
| 32 |
.join("check_installed") |
| 33 |
.join("check_installed.py"); |
| 34 |
if !check_installed.is_file() { |
| 35 |
check_installed = Path::new(package) |
| 36 |
.parent() |
| 37 |
.unwrap() |
| 38 |
.join("check_installed") |
| 39 |
.join("check_installed.py"); |
| 40 |
} |
| 41 |
let output = Command::new(python) |
| 42 |
.arg(check_installed) |
| 43 |
.env("PATH", path) |
| 44 |
.output() |
| 45 |
.unwrap(); |
| 46 |
if !output.status.success() { |
| 47 |
bail!( |
| 48 |
"Check install fail: {} \n--- Stdout:\n{}\n--- Stderr:\n{}", |
| 49 |
output.status, |
| 50 |
str::from_utf8(&output.stdout)?, |
| 51 |
str::from_utf8(&output.stderr)? |
| 52 |
); |
| 53 |
} |
| 54 |
|
| 55 |
let message = str::from_utf8(&output.stdout).unwrap().trim(); |
| 56 |
|
| 57 |
if message != "SUCCESS" { |
| 58 |
panic!("Not SUCCESS: {message}"); |
| 59 |
} |
| 60 |
|
| 61 |
Ok(()) |
| 62 |
} |
| 63 |
|
| 64 |
/// Replaces the real cargo with cargo-mock if the mock crate has been compiled |
| 65 |
/// |
| 66 |
/// If the mock crate hasn't been compile this does nothing |
| 67 |
pub fn maybe_mock_cargo() { |
| 68 |
// libtest spawns multiple threads to run the tests in parallel, but all of those threads share |
| 69 |
// the same environment variables, so this uses the also global stdout lock to |
| 70 |
// make this region exclusive |
| 71 |
let stdout = io::stdout(); |
| 72 |
let handle = stdout.lock(); |
| 73 |
let mock_cargo_path = PathBuf::from("test-crates/cargo-mock/target/release/"); |
| 74 |
if mock_cargo_path.join("cargo").is_file() || mock_cargo_path.join("cargo.exe").is_file() { |
| 75 |
let old_path = env::var_os("PATH").expect("PATH must be set"); |
| 76 |
let mut path_split: Vec<PathBuf> = env::split_paths(&old_path).collect(); |
| 77 |
// Another thread might have already modified the path |
| 78 |
if mock_cargo_path != path_split[0] { |
| 79 |
path_split.insert(0, mock_cargo_path); |
| 80 |
let new_path = |
| 81 |
env::join_paths(path_split).expect("Expected to be able to re-join PATH"); |
| 82 |
env::set_var("PATH", new_path); |
| 83 |
} |
| 84 |
} |
| 85 |
drop(handle); |
| 86 |
} |
| 87 |
|
| 88 |
/// Better error formatting |
| 89 |
#[track_caller] |
| 90 |
pub fn handle_result<T>(result: Result<T>) -> T { |
| 91 |
match result { |
| 92 |
Err(e) => { |
| 93 |
for cause in e.chain().rev() { |
| 94 |
eprintln!("Cause: {cause}"); |
| 95 |
} |
| 96 |
panic!("{}", e); |
| 97 |
} |
| 98 |
Ok(result) => result, |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
/// Get Python implementation |
| 103 |
pub fn get_python_implementation(python_interp: &Path) -> Result<String> { |
| 104 |
let code = "import sys; print(sys.implementation.name, end='')"; |
| 105 |
let output = Command::new(python_interp).arg("-c").arg(code).output()?; |
| 106 |
let python_impl = String::from_utf8(output.stdout).unwrap(); |
| 107 |
Ok(python_impl) |
| 108 |
} |
| 109 |
|
| 110 |
/// Get the current tested Python implementation |
| 111 |
pub fn test_python_implementation() -> Result<String> { |
| 112 |
let python = test_python_path().map(PathBuf::from).unwrap_or_else(|| { |
| 113 |
let target = Target::from_target_triple(None).unwrap(); |
| 114 |
target.get_python() |
| 115 |
}); |
| 116 |
get_python_implementation(&python) |
| 117 |
} |
| 118 |
|
| 119 |
/// Create virtualenv |
| 120 |
pub fn create_virtualenv(name: &str, python_interp: Option<PathBuf>) -> Result<(PathBuf, PathBuf)> { |
| 121 |
let interp = python_interp.or_else(|| test_python_path().map(PathBuf::from)); |
| 122 |
let venv_interp = interp.clone().unwrap_or_else(|| { |
| 123 |
let target = Target::from_target_triple(None).unwrap(); |
| 124 |
target.get_python() |
| 125 |
}); |
| 126 |
let venv_name = match get_python_implementation(&venv_interp) { |
| 127 |
Ok(python_impl) => format!("{name}-{python_impl}"), |
| 128 |
Err(_) => name.to_string(), |
| 129 |
}; |
| 130 |
|
| 131 |
let venv_dir = create_named_virtualenv(&venv_name, interp)?; |
| 132 |
|
| 133 |
let target = Target::from_target_triple(None)?; |
| 134 |
let python = target.get_venv_python(&venv_dir); |
| 135 |
Ok((venv_dir, python)) |
| 136 |
} |
| 137 |
|
| 138 |
pub fn create_named_virtualenv(venv_name: &str, interp: Option<PathBuf>) -> Result<PathBuf> { |
| 139 |
let venv_dir = PathBuf::from("test-crates") |
| 140 |
.normalize()? |
| 141 |
.into_path_buf() |
| 142 |
.join("venvs") |
| 143 |
.join(venv_name); |
| 144 |
|
| 145 |
if venv_dir.is_dir() { |
| 146 |
fs::remove_dir_all(&venv_dir)?; |
| 147 |
} |
| 148 |
|
| 149 |
let mut cmd = { |
| 150 |
if let Ok(uv) = which::which("uv") { |
| 151 |
let mut cmd = Command::new(uv); |
| 152 |
cmd.args(["venv", "--seed"]); |
| 153 |
cmd |
| 154 |
} else { |
| 155 |
Command::new("virtualenv") |
| 156 |
} |
| 157 |
}; |
| 158 |
if let Some(interp) = interp { |
| 159 |
cmd.arg("-p").arg(interp); |
| 160 |
} |
| 161 |
let output = cmd |
| 162 |
.arg(dunce::simplified(&venv_dir)) |
| 163 |
.stderr(Stdio::inherit()) |
| 164 |
.output() |
| 165 |
.expect("Failed to create a virtualenv"); |
| 166 |
if !output.status.success() { |
| 167 |
panic!( |
| 168 |
"Failed to run virtualenv: {}\n---stdout:\n{}---stderr:\n{}", |
| 169 |
output.status, |
| 170 |
str::from_utf8(&output.stdout)?, |
| 171 |
str::from_utf8(&output.stderr)? |
| 172 |
); |
| 173 |
} |
| 174 |
Ok(venv_dir) |
| 175 |
} |
| 176 |
|
| 177 |
/// Creates conda environments |
| 178 |
pub fn create_conda_env(name: &str, major: usize, minor: usize) -> Result<(PathBuf, PathBuf)> { |
| 179 |
use serde::Deserialize; |
| 180 |
|
| 181 |
#[derive(Deserialize)] |
| 182 |
struct CondaCreateResult { |
| 183 |
prefix: PathBuf, |
| 184 |
success: bool, |
| 185 |
} |
| 186 |
|
| 187 |
let mut cmd = if cfg!(windows) { |
| 188 |
let mut cmd = Command::new("cmd.exe"); |
| 189 |
cmd.arg("/c").arg("conda"); |
| 190 |
cmd |
| 191 |
} else { |
| 192 |
Command::new("conda") |
| 193 |
}; |
| 194 |
let output = cmd |
| 195 |
.arg("create") |
| 196 |
.arg("-n") |
| 197 |
.arg(name) |
| 198 |
.arg(format!("python={major}.{minor}")) |
| 199 |
.arg("-q") |
| 200 |
.arg("-y") |
| 201 |
.arg("--json") |
| 202 |
.output() |
| 203 |
.expect("Conda not available."); |
| 204 |
if !output.status.success() { |
| 205 |
panic!( |
| 206 |
"Failed to create conda environment: {}\n---stdout:\n{}---stderr:\n{}", |
| 207 |
output.status, |
| 208 |
str::from_utf8(&output.stdout)?, |
| 209 |
str::from_utf8(&output.stderr)? |
| 210 |
); |
| 211 |
} |
| 212 |
let result: CondaCreateResult = serde_json::from_slice(&output.stdout)?; |
| 213 |
if !result.success { |
| 214 |
bail!("Failed to create conda environment {}.", name); |
| 215 |
} |
| 216 |
let target = Target::from_target_triple(None)?; |
| 217 |
let python = target.get_venv_python(&result.prefix); |
| 218 |
Ok((result.prefix, python)) |
| 219 |
} |
| 220 |
|
| 221 |
/// Path to the python interpreter for testing |
| 222 |
pub fn test_python_path() -> Option<String> { |
| 223 |
env::var("MATURIN_TEST_PYTHON").ok() |
| 224 |
} |