use crate::e2e::fixture::Fixture;
use super::super::helpers::is_skipped;
use super::references_identifier;
pub(super) fn compute_pytest_and_sys_import_needs(
fixtures: &[&Fixture],
client_factory: Option<&str>,
has_error_test: bool,
is_async: bool,
) -> (bool, bool) {
let has_skipped_fixture = fixtures
.iter()
.filter(|f| !f.is_http_test())
.any(|f| is_skipped(f, "python"));
let has_pytest_skip_call = client_factory.is_some()
&& fixtures.iter().filter(|f| !f.is_http_test()).any(|f| {
let has_mock = f.mock_response.is_some() || f.http.is_some();
!has_mock && f.env.as_ref().and_then(|e| e.api_key_var.as_ref()).is_some()
});
let needs_pytest = has_error_test || is_async || has_skipped_fixture || has_pytest_skip_call;
let needs_sys_import = client_factory.is_some()
&& fixtures.iter().filter(|f| !f.is_http_test()).any(|f| {
let has_mock = f.mock_response.is_some() || f.http.is_some();
has_mock && f.env.as_ref().and_then(|e| e.api_key_var.as_ref()).is_some()
});
(needs_pytest, needs_sys_import)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn finalize_stdlib_and_bare_imports(
fixtures_body: &str,
has_http_tests: bool,
needs_base64_import: bool,
needs_json_import: bool,
needs_os_import: bool,
needs_path_import: bool,
needs_sys_import: bool,
needs_pytest: bool,
stdlib_imports: &mut Vec<String>,
thirdparty_bare: &mut Vec<String>,
) {
let needs_json_import = needs_json_import
|| references_identifier(fixtures_body, "json.dumps")
|| references_identifier(fixtures_body, "json.loads");
let needs_re_import =
references_identifier(fixtures_body, "re.match") || references_identifier(fixtures_body, "re.search");
if needs_base64_import {
stdlib_imports.push("import base64".to_string());
}
if needs_json_import {
stdlib_imports.push("import json".to_string());
}
if needs_os_import {
stdlib_imports.push("import os".to_string());
}
if needs_path_import {
stdlib_imports.push("from pathlib import Path".to_string());
}
if needs_re_import {
stdlib_imports.push("import re".to_string());
}
if has_http_tests {
stdlib_imports.push("import urllib.request".to_string());
}
if needs_sys_import {
stdlib_imports.push("import sys".to_string());
}
if needs_pytest {
thirdparty_bare.push("import pytest".to_string());
}
stdlib_imports.sort_by(|a, b| (a.starts_with("from "), a).cmp(&(b.starts_with("from "), b)));
thirdparty_bare.sort();
}
pub(super) fn prune_unreferenced_from_imports(imports: &mut Vec<String>, emitted: &[&str]) {
let pruned: Vec<String> = imports
.iter()
.filter_map(|line| {
let Some((prefix, names)) = line.split_once(" import ") else {
return Some(line.clone());
};
let kept: Vec<&str> = names
.split(", ")
.map(str::trim)
.filter(|name| emitted.iter().any(|source| references_identifier(source, name)))
.collect();
if kept.is_empty() {
return None;
}
Some(format!("{prefix} import {}", kept.join(", ")))
})
.collect();
*imports = pruned;
}