Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
263 changes: 259 additions & 4 deletions rust/execution/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3448,6 +3448,10 @@ impl Boundary {
"default".to_owned(),
];
noadd_args.extend(test_files.clone());
if let Some(f) = filter {
noadd_args.push("-k".to_owned());
noadd_args.push(f.to_owned());
}
result.commands.push(format!(
"python3 -B -m pytest -o addopts= -W default {}",
test_files.join(" ")
Expand Down Expand Up @@ -3482,6 +3486,10 @@ impl Boundary {
noconf_args.extend(extra_pytest_flags.iter().cloned());
noconf_args.push("--noconftest".to_owned());
noconf_args.extend(test_files.clone());
if let Some(f) = filter {
noconf_args.push("-k".to_owned());
noconf_args.push(f.to_owned());
}
result.commands.push(format!(
"python3 -B -m pytest --noconftest {}",
test_files.join(" ")
Expand All @@ -3502,6 +3510,46 @@ impl Boundary {
String::from_utf8_lossy(&active_out.stderr)
);
}
if active_out.exit != 0
&& Self::is_pytest_unbuilt_c_extension_errors(&pytest_combined)
&& Self::has_c_extension_marker(&self.root)
{
let mut pyonly_args = vec![
"-B".to_owned(),
"-m".to_owned(),
"pytest".to_owned(),
"-p".to_owned(),
"no:cacheprovider".to_owned(),
];
pyonly_args.extend(extra_pytest_flags.iter().cloned());
pyonly_args.push("-m".to_owned());
pyonly_args.push("not c_extension".to_owned());
pyonly_args.extend(test_files.clone());
if let Some(f) = filter {
pyonly_args.push("-k".to_owned());
pyonly_args.push(f.to_owned());
}
result.commands.push(format!(
"python3 -B -m pytest -m \"not c_extension\" {}",
test_files.join(" ")
));
active_out = self
.process(
&python,
&pyonly_args,
&environment,
policy::FULL_TEST_TIMEOUT_MS,
4 * 1024 * 1024,
)
.await?;
extra_pytest_flags.push("-m".to_owned());
extra_pytest_flags.push("not c_extension".to_owned());
pytest_combined = format!(
"{}\n{}",
String::from_utf8_lossy(&active_out.stdout),
String::from_utf8_lossy(&active_out.stderr)
);
}
if active_out.exit != 0 && Self::is_pytest_missing_fixture_only(&pytest_combined) {
let changed_tests = self.changed_python_tests(&test_files).await;
if !changed_tests.is_empty() {
Expand Down Expand Up @@ -3563,6 +3611,43 @@ impl Boundary {
&& output.contains("ModuleNotFoundError:")
}

pub(crate) fn is_pytest_unbuilt_c_extension_errors(output: &str) -> bool {
let has_internal_c_ext = output.lines().any(|line| {
let Some(rest) = line.split("ModuleNotFoundError: No module named '").nth(1) else {
return false;
};
let Some(module_name) = rest.split('\'').next() else {
return false;
};
module_name.contains("._")
});
if !has_internal_c_ext {
return false;
}
let summary = output
.lines()
.rev()
.find(|line| line.contains(" in ") && line.contains("===="))
.unwrap_or_default();
summary.contains(" error") || output.contains("ERROR ")
}

fn has_c_extension_marker(root: &Path) -> bool {
[
"tests/conftest.py",
"conftest.py",
"pytest.ini",
"pyproject.toml",
"setup.cfg",
]
.iter()
.any(|rel| {
fs::read_to_string(root.join(rel))
.ok()
.is_some_and(|text| text.contains("c_extension"))
})
}

pub(crate) fn is_pytest_missing_fixture_only(output: &str) -> bool {
let has_missing_fixture = (output.contains("fixture '") && output.contains("' not found"))
|| output.contains("recursive dependency involving fixture '");
Expand Down Expand Up @@ -4207,6 +4292,136 @@ impl Boundary {
false
}

pub(crate) fn cargo_executed_test_count(output: &str) -> u64 {
let mut total = 0_u64;
for line in output.lines() {
let trimmed = line.trim();
if let Some(rest) = trimmed.strip_prefix("running ")
&& let Some(num) = rest.split_whitespace().next()
&& (rest.ends_with(" test") || rest.ends_with(" tests"))
&& let Ok(count) = num.parse::<u64>()
{
total = total.saturating_add(count);
}
}
total
}

pub(crate) fn detect_cargo_features_for_files(
root: &Path,
sub_crate: Option<&str>,
files: &[String],
) -> Vec<String> {
let manifest_path = match sub_crate {
Some(sc) => root.join(sc).join("Cargo.toml"),
None => root.join("Cargo.toml"),
};
let Ok(manifest_text) = fs::read_to_string(&manifest_path) else {
return Vec::new();
};
let mut available = BTreeSet::new();
let mut in_features = false;
for line in manifest_text.lines() {
let trimmed = line.trim();
if trimmed.starts_with('[') {
in_features = trimmed == "[features]";
continue;
}
if !in_features || trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
if let Some((key, _)) = trimmed.split_once('=') {
let name = key.trim().trim_matches('"').trim_matches('\'');
if !name.is_empty() && name != "default" {
available.insert(name.to_owned());
}
}
}
if available.is_empty() {
return Vec::new();
}
let mut detected = BTreeSet::new();
let extract_cfg_features = |line: &str, out: &mut BTreeSet<String>| {
let mut rest = line;
while let Some(pos) = rest.find("feature = \"") {
let after = &rest[pos + "feature = \"".len()..];
if let Some(end) = after.find('"') {
let feat = &after[..end];
if available.contains(feat) {
out.insert(feat.to_owned());
}
rest = &after[end + 1..];
} else {
break;
}
}
};
for file in files {
if !file.ends_with(".rs") {
continue;
}
let full_path = root.join(file);
if let Ok(content) = fs::read_to_string(&full_path) {
for line in content.lines().take(32) {
if line.contains("#![cfg(") && line.contains("feature = \"") {
extract_cfg_features(line, &mut detected);
}
}
}
let norm = file.replace('\\', "/");
let Some((parent_dir, file_name)) = norm.rsplit_once('/') else {
continue;
};
let stem = if file_name == "mod.rs" {
parent_dir.rsplit('/').next().unwrap_or("")
} else {
file_name.strip_suffix(".rs").unwrap_or("")
};
if stem.is_empty() || matches!(stem, "lib" | "main") {
continue;
}
let mut parent_candidates = vec![
root.join(format!("{parent_dir}.rs")),
root.join(parent_dir).join("mod.rs"),
root.join(parent_dir).join("lib.rs"),
];
if file_name == "mod.rs"
&& let Some((grand, _)) = parent_dir.rsplit_once('/')
{
parent_candidates.push(root.join(format!("{grand}.rs")));
parent_candidates.push(root.join(grand).join("mod.rs"));
parent_candidates.push(root.join(grand).join("lib.rs"));
}
let mod_decl = format!("mod {stem};");
for cand in parent_candidates {
let Ok(text) = fs::read_to_string(&cand) else {
continue;
};
let lines: Vec<&str> = text.lines().collect();
for (idx, line) in lines.iter().enumerate() {
if line.contains(&mod_decl) {
let mut back = idx;
while back > 0 {
back -= 1;
let prev = lines[back].trim();
if prev.is_empty() || prev.starts_with("//") {
continue;
}
if prev.starts_with('#') {
if prev.contains("feature = \"") {
extract_cfg_features(prev, &mut detected);
}
continue;
}
break;
}
}
}
}
}
detected.into_iter().collect()
}

async fn node_checks(
&self,
scope: &[String],
Expand Down Expand Up @@ -5204,9 +5419,39 @@ impl Boundary {
.iter()
.any(|file| file.starts_with("benches/") || file.contains("/benches/"));
let mut fetched_online = false;
let mut scope_rs: Vec<String> = requirements
.files
.iter()
.chain(self.written.iter())
.filter(|f| f.ends_with(".rs"))
.cloned()
.collect();
scope_rs.sort();
scope_rs.dedup();
let required_cargo_features = if !is_roster_self {
Self::detect_cargo_features_for_files(&self.root, sub_crate.as_deref(), &scope_rs)
} else {
Vec::new()
};
for mut args in cargo_steps {
let is_metadata = args.first().map(String::as_str) == Some("metadata");
let is_check = args.first().map(String::as_str) == Some("check");
let is_test = args.first().map(String::as_str) == Some("test");
if (is_check || is_test)
&& !required_cargo_features.is_empty()
&& !args
.iter()
.any(|arg| arg == "--features" || arg == "--all-features")
{
let feat_val = required_cargo_features.join(",");
if let Some(sep) = args.iter().position(|arg| arg == "--") {
args.insert(sep, feat_val);
args.insert(sep, "--features".to_owned());
} else {
args.push("--features".to_owned());
args.push(feat_val);
}
}
if is_test && let Some(f) = filter {
if !args.iter().any(|arg| arg == "--") {
args.push("--".to_owned());
Expand Down Expand Up @@ -5313,12 +5558,22 @@ impl Boundary {
if is_test
&& !is_roster_self
&& !args.iter().any(|a| a == "--all-features")
&& (output.exit == 0
&& String::from_utf8_lossy(&output.stdout).contains("running 0 tests"))
&& output.exit == 0
&& Self::cargo_executed_test_count(&String::from_utf8_lossy(&output.stdout))
== 0
{
let mut feat_args = Vec::with_capacity(args.len() + 1);
let mut inserted = false;
let mut skip_next = false;
for a in &args {
if skip_next {
skip_next = false;
continue;
}
if a == "--features" {
skip_next = true;
continue;
}
if !inserted && a == "--" {
feat_args.push("--all-features".to_owned());
inserted = true;
Expand All @@ -5338,8 +5593,8 @@ impl Boundary {
4 * 1024 * 1024,
)
.await?;
if feat_out.exit == 0
&& !String::from_utf8_lossy(&feat_out.stdout).contains("running 0 tests")
if Self::cargo_executed_test_count(&String::from_utf8_lossy(&feat_out.stdout))
> 0
{
output = feat_out;
}
Expand Down
Loading
Loading