Debian Codegraph @

debian/rust-vendor/link-section/tests/macrotest.rs

raw
1 #![cfg(not(miri))]
2
3 /*
4
5 To overwrite the Linux expansion tests on macOS, run:
6
7 docker run --rm -v "$(pwd):/src" -w /src rust:1.88 \
8 bash -lc 'export CARGO_TARGET_DIR=/src/target/target-docker && export PATH="/usr/local/cargo/bin:$PATH" && cargo install cargo-expand && MACROTEST=overwrite cargo test -p link-section --test macrotest'
9 */
10
11 use std::{
12 fs,
13 path::{Path, PathBuf},
14 process::Command,
15 };
16
17 use tempfile::tempdir;
18
19 /// Macrotest sometimes leaves files empty when things fail to compile.
20 fn ensure_no_empty_files(path: impl AsRef<Path>) {
21 if ensure_no_empty_files_recurse(path) {
22 panic!("Empty files found");
23 }
24 }
25
26 fn ensure_no_empty_files_recurse(path: impl AsRef<Path>) -> bool {
27 if !std::fs::exists(path.as_ref()).unwrap() {
28 return false;
29 }
30 let mut empty_files = false;
31 let files = std::fs::read_dir(path).unwrap();
32 for file in files.flatten() {
33 if file.file_type().unwrap().is_dir() {
34 ensure_no_empty_files_recurse(file.path());
35 } else {
36 let content = std::fs::read_to_string(file.path()).unwrap();
37 if content.trim().is_empty() {
38 eprintln!("Empty file found: {}", file.path().display());
39 empty_files = true;
40 }
41 if content.contains("/*ERROR*/") {
42 panic!("Error found in file: {}", file.path().display());
43 }
44 }
45 }
46 empty_files
47 }
48
49 #[test]
50 #[cfg(not(linktime_used_linker))]
51 pub fn pass() {
52 macrotest::expand("tests/expand/*.rs");
53 ensure_no_empty_files("tests/expand");
54 }
55
56 #[cfg(target_vendor = "apple")]
57 #[cfg(not(linktime_used_linker))]
58 #[test]
59 pub fn pass_darwin() {
60 macrotest::expand("tests/expand-darwin/*.rs");
61 ensure_no_empty_files("tests/expand-darwin");
62 }
63
64 #[cfg(target_os = "linux")]
65 #[cfg(not(linktime_used_linker))]
66 #[test]
67 pub fn pass_linux() {
68 macrotest::expand("tests/expand-linux/*.rs");
69 ensure_no_empty_files("tests/expand-linux");
70 }
71
72 #[test]
73 pub fn trybuild() {
74 let t = trybuild::TestCases::new();
75 // TODO: whitespace issue (tabs?) in error tests
76 #[cfg(not(target_os = "openbsd"))]
77 t.compile_fail("tests/errors/*.rs");
78 t.pass("tests/pass/*.rs");
79 }
80
81 #[test]
82 pub fn target_test() {
83 let Some(toolchain) = std::env::var_os("TOOLCHAIN") else {
84 return;
85 };
86 if toolchain != "nightly" {
87 return;
88 }
89 let cases_dir = Path::new("tests/target-test");
90 let overwrite = std::env::var_os("MACROTEST")
91 .map(|v| v == "overwrite")
92 .unwrap_or(false);
93
94 let repo_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
95 .canonicalize()
96 .unwrap()
97 .parent()
98 .unwrap()
99 .to_path_buf();
100
101 let mut count = 0;
102 let mut success = 0;
103
104 let target_dir = Path::new(env!("CARGO_MANIFEST_DIR"))
105 .parent()
106 .unwrap()
107 .join("target")
108 .join("target-test");
109
110 // Each testcase is:
111 // - input: tests/target-test/<case>.rs
112 // - outputs: tests/target-test/<case>/<target-triple>.rs
113 for entry in fs::read_dir(cases_dir).unwrap().flatten() {
114 let path = entry.path();
115 if path.extension().and_then(|s| s.to_str()) != Some("rs") {
116 continue;
117 }
118
119 let case_name = path.file_stem().unwrap().to_string_lossy().to_string();
120 let outputs_dir = cases_dir.join(&case_name);
121 if !outputs_dir.is_dir() {
122 panic!(
123 "expected output directory {} for testcase {}",
124 outputs_dir.display(),
125 case_name
126 );
127 }
128
129 // Allow a testcase-specific Cargo.toml at tests/target-test/<case>/Cargo.toml
130 // (useful for additional deps or feature flags).
131 let case_cargo_toml_path = outputs_dir.join("Cargo.toml");
132 let base_cargo_toml = if case_cargo_toml_path.exists() {
133 fs::read_to_string(&case_cargo_toml_path).unwrap()
134 } else {
135 format!(
136 r#"[package]
137 name = "expand_probe"
138 version = "0.0.0"
139 edition = "2021"
140
141 [dependencies]
142 link-section = {{ path = "{repo_root}/link-section", default-features = false }}
143 "#,
144 repo_root = repo_root.display()
145 )
146 };
147
148 for out_file in fs::read_dir(&outputs_dir).unwrap().flatten() {
149 let out_path = out_file.path();
150 if out_path.extension().and_then(|s| s.to_str()) != Some("rs") {
151 continue;
152 }
153
154 count += 1;
155
156 let target = out_path.file_stem().unwrap().to_string_lossy().to_string();
157 eprintln!("testing testcase={case_name}, target={target}");
158
159 let dir = tempdir().unwrap();
160 fs::create_dir_all(dir.path().join("src")).unwrap();
161
162 fs::write(dir.path().join("Cargo.toml"), &base_cargo_toml).unwrap();
163 // Ensure the probe crate doesn't require `std` for exotic targets.
164 let input_src = fs::read_to_string(&path).unwrap();
165 fs::write(
166 dir.path().join("src/lib.rs"),
167 format!("#![no_std]\n// ***START MARKER***\n{input_src}"),
168 )
169 .unwrap();
170
171 let out = Command::new("cargo")
172 .current_dir(dir.path())
173 .env("CARGO_TERM_COLOR", "never")
174 .env("CARGO_TARGET_DIR", target_dir.join(&target))
175 .env_remove("RUSTFLAGS")
176 .args([
177 "+nightly",
178 "rustc",
179 // Build core from source so we can target triples without prebuilt std.
180 "-Zbuild-std=core,alloc",
181 "-Zbuild-std-features=compiler-builtins-mem",
182 "--target",
183 &target,
184 "--lib",
185 "--quiet",
186 "--",
187 "-Zunpretty=expanded",
188 ])
189 .output()
190 .unwrap();
191
192 // Even when compilation fails later, -Zunpretty=expanded often emits output.
193 // For debugging, include stderr on mismatch.
194 let stdout = String::from_utf8_lossy(&out.stdout).to_string();
195 let stderr = String::from_utf8_lossy(&out.stderr).to_string();
196 eprintln!("{stderr}");
197
198 if stderr.contains("error") {
199 panic!("compilation failed for testcase={case_name}, target={target}\n\n--- stderr ---\n{stderr}\n");
200 }
201
202 if stdout.trim().is_empty() {
203 panic!(
204 "no expansion output for testcase={case_name}, target={target}\n\n--- stderr ---\n{stderr}\n"
205 );
206 }
207
208 if !stdout.contains("// ***START MARKER***") {
209 panic!(
210 "no start marker in expansion output for testcase={case_name}, target={target}\n\n--- stdout ---\n{stdout}\n"
211 );
212 }
213
214 let stdout = stdout
215 .split("// ***START MARKER***\n")
216 .nth(1)
217 .unwrap()
218 .to_string();
219
220 if overwrite {
221 fs::write(&out_path, &stdout).unwrap();
222 success += 1;
223 } else {
224 let expected = fs::read_to_string(&out_path).unwrap();
225 if expected != stdout {
226 eprintln!(
227 "target-test mismatch for testcase={case_name}, target={target}\n\
228 (set MACROTEST=overwrite to update)\n\n\
229 --- expected file ---\n{expected}\n\n\
230 --- actual stdout ---\n{stdout}\n\n\
231 --- stderr ---\n{stderr}\n"
232 );
233 } else {
234 success += 1;
235 }
236 }
237 }
238 }
239
240 if count == 0 {
241 panic!("no testcases found");
242 } else if count == success {
243 println!("all {} testcases passed", count);
244 } else {
245 panic!("{} of {} testcases passed", success, count);
246 }
247
248 ensure_no_empty_files("tests/target-test");
249 }