Debian Codegraph @

debian/rust-vendor/jobserver/tests/client.rs

raw
1 use std::env;
2 use std::fs::File;
3 use std::io::Write;
4 use std::process::{Command, Output};
5 use std::sync::atomic::{AtomicBool, Ordering};
6 use std::sync::mpsc;
7 use std::sync::Arc;
8 use std::thread;
9
10 use jobserver::Client;
11
12 macro_rules! t {
13 ($e:expr) => {
14 match $e {
15 Ok(e) => e,
16 Err(e) => panic!("{} failed with {}", stringify!($e), e),
17 }
18 };
19 }
20
21 struct Test {
22 name: &'static str,
23 f: &'static (dyn Fn() + Send + Sync),
24 make_args: &'static [&'static str],
25 rule: &'static (dyn Fn(&str) -> String + Send + Sync),
26 }
27
28 const TESTS: &[Test] = &[
29 Test {
30 name: "no j args",
31 make_args: &[],
32 rule: &|me| me.to_string(),
33 f: &|| {
34 assert!(unsafe { Client::from_env().is_none() });
35 },
36 },
37 Test {
38 name: "no j args with plus",
39 make_args: &[],
40 rule: &|me| format!("+{}", me),
41 f: &|| {
42 assert!(unsafe { Client::from_env().is_none() });
43 },
44 },
45 Test {
46 name: "j args with plus",
47 make_args: &["-j2"],
48 rule: &|me| format!("+{}", me),
49 f: &|| {
50 assert!(unsafe { Client::from_env().is_some() });
51 },
52 },
53 Test {
54 name: "acquire",
55 make_args: &["-j2"],
56 rule: &|me| format!("+{}", me),
57 f: &|| {
58 let c = unsafe { Client::from_env().unwrap() };
59 drop(c.acquire().unwrap());
60 drop(c.acquire().unwrap());
61 },
62 },
63 Test {
64 name: "acquire3",
65 make_args: &["-j3"],
66 rule: &|me| format!("+{}", me),
67 f: &|| {
68 let c = unsafe { Client::from_env().unwrap() };
69 let a = c.acquire().unwrap();
70 let b = c.acquire().unwrap();
71 drop((a, b));
72 },
73 },
74 Test {
75 name: "acquire blocks",
76 make_args: &["-j2"],
77 rule: &|me| format!("+{}", me),
78 f: &|| {
79 let c = unsafe { Client::from_env().unwrap() };
80 let a = c.acquire().unwrap();
81 let hit = Arc::new(AtomicBool::new(false));
82 let hit2 = hit.clone();
83 let (tx, rx) = mpsc::channel();
84 let t = thread::spawn(move || {
85 tx.send(()).unwrap();
86 let _b = c.acquire().unwrap();
87 hit2.store(true, Ordering::SeqCst);
88 });
89 rx.recv().unwrap();
90 assert!(!hit.load(Ordering::SeqCst));
91 drop(a);
92 t.join().unwrap();
93 assert!(hit.load(Ordering::SeqCst));
94 },
95 },
96 Test {
97 name: "acquire_raw",
98 make_args: &["-j2"],
99 rule: &|me| format!("+{}", me),
100 f: &|| {
101 let c = unsafe { Client::from_env().unwrap() };
102 c.acquire_raw().unwrap();
103 c.release_raw().unwrap();
104 },
105 },
106 ];
107
108 /// The make binary under test, overridable via the `MAKE` env var.
109 fn make() -> String {
110 env::var("MAKE").unwrap_or_else(|_| "make".to_string())
111 }
112
113 /// Whether we are running in a Continuous Integration environment.
114 pub fn is_ci() -> bool {
115 env::var_os("CI").is_some()
116 }
117
118 /// The jobserver wire formats to exercise as `make`'s server.
119 ///
120 /// The `fifo`/`pipe` distinction is Unix-only: on Unix, GNU Make >= 4.4
121 /// defaults to the named-pipe (`fifo:PATH`) form but can be told to use the
122 /// legacy `R,W` pipe form via `--jobserver-style`, so we run every test under
123 /// both to cover both [`Client::from_env`] parse paths. CI must use a make new
124 /// enough to support both; locally an older make falls back to a single run.
125 ///
126 /// Windows has neither style (its jobserver is a named semaphore), so just run
127 /// once with whatever make defaults to.
128 #[cfg(unix)]
129 fn jobserver_styles() -> Vec<&'static str> {
130 let supports_style = Command::new(make())
131 .args(["--jobserver-style=fifo", "--version"])
132 .output()
133 .map(|o| o.status.success())
134 .unwrap_or(false);
135
136 if supports_style {
137 vec!["--jobserver-style=fifo", "--jobserver-style=pipe"]
138 } else if is_ci() {
139 panic!(
140 "CI requires a GNU Make supporting `--jobserver-style` (>= 4.4) \
141 so both jobserver wire formats are tested; `{}` does not",
142 make()
143 );
144 } else {
145 // Older make defaults to a single style; pass no extra flag.
146 vec![""]
147 }
148 }
149
150 #[cfg(windows)]
151 fn jobserver_styles() -> Vec<&'static str> {
152 vec![""]
153 }
154
155 fn main() {
156 if let Ok(test) = env::var("TEST_TO_RUN") {
157 return (TESTS.iter().find(|t| t.name == test).unwrap().f)();
158 }
159
160 let me = t!(env::current_exe());
161 let me = me.to_str().unwrap();
162 let filter = env::args().nth(1);
163
164 let styles = jobserver_styles();
165
166 let join_handles = TESTS
167 .iter()
168 .filter(|test| match filter {
169 Some(ref s) => test.name.contains(s),
170 None => true,
171 })
172 .flat_map(|test| {
173 styles.iter().map(move |style| {
174 let td = t!(tempfile::tempdir());
175 let makefile = format!(
176 "\
177 all: export TEST_TO_RUN={}
178 all:
179 \t{}
180 ",
181 test.name,
182 (test.rule)(me)
183 );
184 t!(t!(File::create(td.path().join("Makefile"))).write_all(makefile.as_bytes()));
185 let style = *style;
186 thread::spawn(move || {
187 let mut cmd = Command::new(make());
188 if !style.is_empty() {
189 cmd.arg(style);
190 }
191 cmd.args(test.make_args);
192 cmd.current_dir(td.path());
193
194 (test, style, cmd.output().unwrap())
195 })
196 })
197 })
198 .collect::<Vec<_>>();
199
200 println!("\nrunning {} tests\n", join_handles.len());
201
202 let failures = join_handles
203 .into_iter()
204 .filter_map(|join_handle| {
205 let (test, style, output): (&Test, &str, Output) = join_handle.join().unwrap();
206 let name = format!("{} {}", test.name, style);
207
208 if output.status.success() {
209 println!("test {} ... ok", name);
210 None
211 } else {
212 println!("test {} ... FAIL", name);
213 Some((name, output))
214 }
215 })
216 .collect::<Vec<_>>();
217
218 if failures.is_empty() {
219 println!("\ntest result: ok\n");
220 return;
221 }
222
223 println!("\n----------- failures");
224
225 for (name, output) in failures {
226 println!("test {}", name);
227 let stdout = String::from_utf8_lossy(&output.stdout);
228 let stderr = String::from_utf8_lossy(&output.stderr);
229
230 println!("\texit status: {}", output.status);
231 if !stdout.is_empty() {
232 println!("\tstdout ===");
233 for line in stdout.lines() {
234 println!("\t\t{}", line);
235 }
236 }
237
238 if !stderr.is_empty() {
239 println!("\tstderr ===");
240 for line in stderr.lines() {
241 println!("\t\t{}", line);
242 }
243 }
244 }
245
246 std::process::exit(4);
247 }