Debian Codegraph @

tests/test.rs

raw ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 // SPDX-License-Identifier: Apache-2.0 OR MIT
2
3 #![allow(clippy::needless_pass_by_value)]
4
5 mod helper;
6
7 use std::{collections::HashMap, path::Path, process::Command};
8
9 use build_context::TARGET;
10 use cargo_config2::*;
11
12 use self::helper::*;
13
14 fn test_options() -> ResolveOptions {
15 ResolveOptions::default()
16 .env(HashMap::<String, String>::default())
17 .cargo_home(None)
18 .rustc(PathAndArgs::new("rustc"))
19 }
20
21 fn assert_reference_example(de: fn(&Path, ResolveOptions) -> Result<Config, Error>) {
22 let (_tmp, root) = test_project("reference");
23 let dir = &root;
24 let base_config = &de(dir, test_options()).unwrap();
25 let config = base_config.clone();
26
27 // [alias]
28 for (k, v) in &config.alias {
29 match k.as_str() {
30 "b" => assert_eq!(*v, "build".into()),
31 "c" => assert_eq!(*v, "check".into()),
32 "t" => assert_eq!(*v, "test".into()),
33 "r" => assert_eq!(*v, "run".into()),
34 "rr" => assert_eq!(*v, "run --release".into()),
35 "recursive_example" => assert_eq!(*v, "rr --example recursions".into()),
36 "space_example" => {
37 assert_eq!(*v, ["run", "--release", "--", "\"command list\""].into());
38 }
39 _ => panic!("unexpected alias: name={k}, value={v:?}"),
40 }
41 }
42
43 // [build]
44 assert_eq!(config.build.rustc.as_ref().unwrap().as_os_str(), "rustc");
45 assert_eq!(config.build.rustc_wrapper.as_ref().unwrap().as_os_str(), "…");
46 assert_eq!(config.build.rustc_workspace_wrapper.as_ref().unwrap().as_os_str(), "…");
47 assert_eq!(config.build.rustdoc.as_ref().unwrap().as_os_str(), "rustdoc");
48 assert_eq!(config.build.target.as_ref().unwrap(), &vec!["triple".into()]);
49 assert_eq!(config.build.target_dir.as_ref().unwrap(), &dir.join("target"));
50 assert_eq!(config.build.build_dir.as_ref().unwrap(), &dir.join("target"));
51 assert_eq!(config.build.rustflags, Some(["…", "…"].into()));
52 assert_eq!(config.build.rustdocflags, Some(["…", "…"].into()));
53 assert_eq!(config.build.incremental, Some(true));
54 assert_eq!(config.build.dep_info_basedir.as_ref().unwrap(), &dir.join("…"));
55
56 // [credential-alias]
57 for (k, v) in &config.credential_alias {
58 match k.as_str() {
59 "my-alias" => {
60 // TODO
61 #[cfg(windows)]
62 assert_eq!(
63 *v,
64 *PathAndArgs::new("C:/usr/bin/cargo-credential-example").args([
65 "--argument",
66 "value",
67 "--flag"
68 ])
69 );
70 #[cfg(not(windows))]
71 assert_eq!(
72 *v,
73 *PathAndArgs::new("/usr/bin/cargo-credential-example").args([
74 "--argument",
75 "value",
76 "--flag"
77 ])
78 );
79 }
80 _ => panic!("unexpected credential-alias: name={k}, value={v:?}"),
81 }
82 }
83
84 // [doc]
85 assert_eq!(config.doc.browser.as_ref().unwrap().path.as_os_str(), "chromium");
86 assert!(config.doc.browser.as_ref().unwrap().args.is_empty());
87
88 // [env]
89 assert_eq!(config.env["ENV_VAR_NAME"].value, "value");
90 assert_eq!(config.env["ENV_VAR_NAME"].force, false);
91 assert_eq!(config.env["ENV_VAR_NAME"].relative, false);
92 assert_eq!(config.env["ENV_VAR_NAME_2"].value, "value");
93 assert_eq!(config.env["ENV_VAR_NAME_2"].force, true);
94 assert_eq!(config.env["ENV_VAR_NAME_2"].relative, false);
95 assert_eq!(config.env["ENV_VAR_NAME_3"].value, dir.join("relative/path"));
96 assert_eq!(config.env["ENV_VAR_NAME_3"].force, false);
97 assert_eq!(config.env["ENV_VAR_NAME_3"].relative, false); // false because it has been resolved
98
99 // [future-incompat-report]
100 assert_eq!(config.future_incompat_report.frequency, Some(Frequency::Always));
101
102 // TODO:
103 // [cache]
104
105 // [cargo-new]
106 assert_eq!(config.cargo_new.vcs, Some(VersionControlSoftware::None));
107
108 // [http]
109 assert_eq!(config.http.debug, Some(false));
110 assert_eq!(config.http.proxy.as_deref(), Some("host:port"));
111 assert_eq!(config.http.timeout, Some(30));
112 assert_eq!(config.http.low_speed_limit, Some(10));
113 assert_eq!(config.http.cainfo.as_deref(), Some("cert.pem"));
114 assert_eq!(config.http.check_revoke, Some(true));
115 assert_eq!(config.http.multiplexing, Some(true));
116 assert_eq!(config.http.user_agent.as_deref(), Some("foo-usr-agt"));
117
118 // TODO
119 // [install]
120
121 // [net]
122 assert_eq!(config.net.retry, Some(3));
123 assert_eq!(config.net.git_fetch_with_cli, Some(true));
124 assert_eq!(config.net.offline, Some(true));
125 // TODO
126 // [net.ssh]
127
128 // TODO
129 // [patch.<registry>]
130 // [profile.<name>]
131 // [resolver]
132
133 // [registries.<name>]
134 assert_eq!(config.registries.len(), 6);
135 assert_eq!(config.registries["custom-token"].index.as_deref(), Some("registry-index"));
136 assert_eq!(
137 config.registries["custom-token"].token.as_deref(),
138 Some("00000000000000000000000000000000001")
139 );
140 assert_eq!(config.registries["custom-token"].protocol, None);
141 assert_eq!(
142 config.registries["custom-single-word-plugin"].credential_provider,
143 Some(CredentialProvider::Plugin(PathAndArgs::new("cargo-credential-example"))),
144 );
145 assert_eq!(
146 config.registries["alias"].credential_provider,
147 Some(CredentialProvider::Alias("my-alias".into())),
148 );
149 let mut many_word_plugins = PathAndArgs::new("cargo-credential-example");
150 many_word_plugins.arg("--some-argument");
151 assert_eq!(
152 config.registries["custom-many-words-plugin"].credential_provider,
153 Some(CredentialProvider::Plugin(many_word_plugins)),
154 );
155 assert_eq!(
156 config.registries["custom-token-from-stdout"].credential_provider,
157 Some(CredentialProvider::CargoTokenFromStdout(PathAndArgs::new(
158 "cargo-credential-example"
159 ))),
160 );
161 assert_eq!(
162 config.registries["crates-io"].index.as_deref(),
163 Some("https://github.com/rust-lang/crates.io-index")
164 );
165 assert_eq!(
166 config.registries["crates-io"].token.as_deref(),
167 Some("00000000000000000000000000000000000")
168 );
169 assert_eq!(config.registries["crates-io"].protocol, Some(RegistriesProtocol::Git));
170 assert_eq!(config.registries["crates-io"].credential_provider, None);
171 // [registry]
172 assert_eq!(config.registry.default.as_deref(), Some("crates-io"));
173 assert_eq!(config.registry.token.as_deref(), Some("00000000000000000000000000000000000"));
174 assert_eq!(config.registry.credential_provider, Some(CredentialProvider::CargoToken));
175 assert_eq!(config.registry.global_credential_providers.as_ref(), [
176 CredentialProvider::CargoToken
177 ]);
178
179 // [source.<name>]
180 assert_eq!(config.source["vendored-sources"].directory, Some(dir.join("vendor")));
181 assert_eq!(config.source["crates-io"].replace_with.as_deref(), Some("vendored-sources"));
182 assert_eq!(
183 config.source["git+https://github.com/taiki-e/test-helper.git?rev=f38a7f5"].git.as_deref(),
184 Some("https://github.com/taiki-e/test-helper.git"),
185 );
186 assert_eq!(
187 config.source["git+https://github.com/taiki-e/test-helper.git?rev=f38a7f5"].rev.as_deref(),
188 Some("f38a7f5"),
189 );
190 assert_eq!(
191 config.source["git+https://github.com/taiki-e/test-helper.git?rev=f38a7f5"]
192 .replace_with
193 .as_deref(),
194 Some("vendored-sources")
195 );
196
197 // [target.<triple>] and [target.<cfg>]
198 assert_eq!(config.target("x86_64-unknown-linux-gnu").unwrap().linker.unwrap().as_os_str(), "b");
199 assert_eq!(
200 config.target("x86_64-unknown-linux-gnu").unwrap().runner.unwrap().path.as_os_str(),
201 "b"
202 );
203 assert!(config.target("x86_64-unknown-linux-gnu").unwrap().runner.unwrap().args.is_empty());
204 assert_eq!(
205 config.target("x86_64-unknown-linux-gnu").unwrap().rustflags,
206 Some(["b", "bb", "c", "cc"].into())
207 );
208 assert_eq!(
209 config.target("x86_64-unknown-linux-gnu").unwrap().rustdocflags,
210 Some(["d", "dd", "e", "ee"].into())
211 );
212 assert_eq!(config.linker("x86_64-unknown-linux-gnu").unwrap().unwrap().as_os_str(), "b");
213 assert_eq!(config.runner("x86_64-unknown-linux-gnu").unwrap().unwrap().path.as_os_str(), "b");
214 assert!(config.runner("x86_64-unknown-linux-gnu").unwrap().unwrap().args.is_empty());
215 assert_eq!(
216 config.rustflags("x86_64-unknown-linux-gnu").unwrap(),
217 Some(["b", "bb", "c", "cc"].into())
218 );
219 assert_eq!(
220 config.rustdocflags("x86_64-unknown-linux-gnu").unwrap(),
221 Some(["d", "dd", "e", "ee"].into())
222 );
223 assert_eq!(
224 config.rustflags("thumbv8m.main-none-eabi").unwrap(),
225 Some(["-Z", "panic-abort-tests"].into())
226 );
227 assert_eq!(
228 config.rustflags("thumbv8m.base-none-eabi").unwrap(),
229 Some(["-Z", "panic-abort-tests"].into())
230 );
231 // TODO: [target.<triple>.<links>]
232
233 // resolved target config cannot be accessed by cfg(...)
234 assert!(
235 config
236 .target("cfg(target_arch = \"x86_64\")")
237 .unwrap_err()
238 .to_string()
239 .contains("not valid target triple")
240 );
241 assert!(
242 config
243 .linker("cfg(target_arch = \"x86_64\")")
244 .unwrap_err()
245 .to_string()
246 .contains("not valid target triple")
247 );
248 assert!(
249 config
250 .runner("cfg(target_arch = \"x86_64\")")
251 .unwrap_err()
252 .to_string()
253 .contains("not valid target triple")
254 );
255 assert!(
256 config
257 .rustflags("cfg(target_arch = \"x86_64\")")
258 .unwrap_err()
259 .to_string()
260 .contains("not valid target triple")
261 );
262
263 // [term]
264 assert_eq!(config.term.quiet, Some(false));
265 assert_eq!(config.term.verbose, Some(false));
266 assert_eq!(config.term.color, Some(Color::Auto));
267 // TODO: hyperlinks, unicode
268 assert_eq!(config.term.progress.when, Some(When::Auto));
269 assert_eq!(config.term.progress.width, Some(80));
270 // TODO: progress.term-integration
271
272 let _config = toml::to_string(&config).unwrap();
273 }
274
275 fn easy_load(dir: &Path, options: ResolveOptions) -> Result<Config, Error> {
276 Config::load_with_options(dir, options)
277 }
278 #[test]
279 #[cfg_attr(miri, ignore)] // Miri doesn't support std::process::Command: https://github.com/rust-lang/miri/issues/3374
280 fn easy() {
281 use easy_load as de;
282
283 assert_reference_example(de);
284 }
285
286 #[test]
287 fn no_manifest_dir() {
288 let tmpdir = tempfile::tempdir().unwrap();
289 assert_eq!(
290 "",
291 toml::to_string(&Config::load_with_options(tmpdir.path(), test_options()).unwrap())
292 .unwrap()
293 );
294 }
295
296 #[test]
297 #[cfg_attr(miri, ignore)] // Miri doesn't support std::process::Command: https://github.com/rust-lang/miri/issues/3374
298 fn empty_target_flags_fall_back_to_build() {
299 let (_tmp, root) = test_project("empty");
300 fs::write(
301 root.join(".cargo/config.toml"),
302 r#"
303 [build]
304 rustflags = ["--cfg", "from_build_rustflags"]
305 rustdocflags = ["--cfg", "from_build_rustdocflags"]
306
307 [target.'cfg(target_arch = "x86_64")']
308 rustflags = []
309 rustdocflags = []
310 "#,
311 )
312 .unwrap();
313
314 let config = Config::load_with_options(&root, test_options()).unwrap();
315 assert_eq!(
316 config.rustflags("x86_64-unknown-linux-gnu").unwrap(),
317 Some(["--cfg", "from_build_rustflags"].into())
318 );
319 assert_eq!(
320 config.rustdocflags("x86_64-unknown-linux-gnu").unwrap(),
321 Some(["--cfg", "from_build_rustdocflags"].into())
322 );
323 }
324
325 #[test]
326 fn flags_from_encoded() {
327 for (encoded, expected) in [
328 ("", Flags::default()),
329 ("\x1f", ["", ""].into()),
330 ("\x1fa\x1f", ["", "a", ""].into()),
331 ("a\x1fb", ["a", "b"].into()),
332 ] {
333 assert_eq!(Flags::from_encoded(encoded), expected);
334 }
335 }
336
337 #[test]
338 #[cfg_attr(miri, ignore)] // Miri doesn't support std::process::Command: https://github.com/rust-lang/miri/issues/3374
339 fn empty_encoded_flags_override_other_sources() {
340 let (_tmp, root) = test_project("empty");
341 fs::write(
342 root.join(".cargo/config.toml"),
343 r#"
344 [build]
345 rustflags = ["from_build_rustflags"]
346 rustdocflags = ["from_build_rustdocflags"]
347
348 [target.x86_64-unknown-linux-gnu]
349 rustflags = ["from_target_rustflags"]
350 rustdocflags = ["from_target_rustdocflags"]
351 "#,
352 )
353 .unwrap();
354
355 let options =
356 test_options().env([("CARGO_ENCODED_RUSTFLAGS", ""), ("CARGO_ENCODED_RUSTDOCFLAGS", "")]);
357 let config = Config::load_with_options(&root, options).unwrap();
358 assert_eq!(config.rustflags("x86_64-unknown-linux-gnu").unwrap(), Some(Flags::default()));
359 assert_eq!(config.rustdocflags("x86_64-unknown-linux-gnu").unwrap(), Some(Flags::default()));
360 }
361
362 fn de_load(dir: &Path, _cx: ResolveOptions) -> Result<de::Config, Error> {
363 de::Config::load_with_options(dir, None)
364 }
365 #[test]
366 #[cfg_attr(miri, ignore)] // Miri doesn't support std::process::Command: https://github.com/rust-lang/miri/issues/3374
367 fn de() {
368 use de_load as de;
369
370 let (_tmp, root) = test_project("reference");
371 let dir = &root;
372 let base_config = &de(dir, test_options()).unwrap();
373 let config = base_config.clone();
374
375 let _config = toml::to_string(&config).unwrap();
376
377 assert_eq!("", toml::to_string(&de::Config::default()).unwrap());
378 }
379
380 #[rustversion::attr(not(nightly), ignore)]
381 #[test]
382 #[cfg_attr(miri, ignore)] // Miri doesn't support std::process::Command: https://github.com/rust-lang/miri/issues/3374
383 fn custom_target() {
384 use easy_load as de;
385 struct IsBuiltin(bool);
386 #[track_caller]
387 fn t(target: &str, IsBuiltin(is_builtin): IsBuiltin) {
388 let (_tmp, root) = test_project("empty");
389 let dir = &root;
390 fs::write(
391 root.join(".cargo/config.toml"),
392 r#"
393 target.'cfg(target_arch = "avr")'.linker = "avr-gcc"
394 target.'cfg(target_arch = "avr")'.rustflags = "-C opt-level=s"
395 "#,
396 )
397 .unwrap();
398 let spec_path = fixtures_dir().join(format!("target-specs/{target}.json"));
399 assert_eq!(spec_path.exists(), !is_builtin);
400 let cli_target = if spec_path.exists() { spec_path.to_str().unwrap() } else { target };
401
402 let config = de(dir, test_options()).unwrap();
403 assert_eq!(
404 config
405 .build_target_for_config([cli_target])
406 .unwrap()
407 .iter()
408 .map(|t| t.triple().to_owned())
409 .collect::<Vec<_>>(),
410 vec![target.to_owned()]
411 );
412 assert_eq!(config.build_target_for_cli([cli_target]).unwrap(), vec![cli_target.to_owned()]);
413
414 assert_eq!(config.linker(cli_target).unwrap().unwrap().as_os_str(), "avr-gcc");
415 assert_eq!(config.rustflags(cli_target).unwrap(), Some(["-C", "opt-level=s"].into()));
416
417 // only resolve relative path from config or environment variables
418 let spec_file_name = spec_path.file_name().unwrap().to_str().unwrap();
419 assert_eq!(
420 config.build_target_for_config([spec_file_name]).unwrap()[0]
421 .spec_path()
422 .unwrap()
423 .as_os_str(),
424 spec_file_name
425 );
426 assert_eq!(config.build_target_for_cli([spec_file_name]).unwrap(), vec![
427 spec_file_name.to_owned()
428 ]);
429
430 let _config = toml::to_string(&config).unwrap();
431 }
432
433 if rustversion::cfg!(since(1.87)) {
434 t("avr-none", IsBuiltin(true));
435 } else {
436 t("avr-unknown-gnu-atmega328", IsBuiltin(true));
437 }
438 // Skip pre-1.91 because target-pointer-width change
439 if rustversion::cfg!(since(1.91)) {
440 t("avr-unknown-gnu-atmega2560", IsBuiltin(false));
441 }
442 }
443
444 #[test]
445 #[cfg_attr(miri, ignore)] // Miri doesn't support std::process::Command: https://github.com/rust-lang/miri/issues/3374
446 fn target_cfg_boolean_literals() {
447 let (_tmp, root) = test_project("empty");
448 fs::write(
449 root.join(".cargo/config.toml"),
450 r#"
451 [target.'cfg(true)']
452 rustflags = ["--cfg", "cfg_true"]
453
454 [target.'cfg(false)']
455 rustflags = ["--cfg", "cfg_false"]
456
457 [target.'cfg(all(true, not(false)))']
458 rustflags = ["--cfg", "cfg_nested"]
459 "#,
460 )
461 .unwrap();
462
463 // `false` remains a literal even if rustc reports a same-named user cfg.
464 let mut rustc = PathAndArgs::new("rustc");
465 rustc.args(["--cfg", "r#false"]);
466 let options = test_options().rustc(rustc);
467 let config = Config::load_with_options(&root, options).unwrap();
468 assert_eq!(
469 config.rustflags(TARGET).unwrap(),
470 Some(["--cfg", "cfg_nested", "--cfg", "cfg_true",].into())
471 );
472 }
473
474 #[test]
475 #[cfg_attr(miri, ignore)] // Miri doesn't support std::process::Command: https://github.com/rust-lang/miri/issues/3374
476 fn empty_target_cfg_expression_does_not_match() {
477 let (_tmp, root) = test_project("empty");
478 fs::write(
479 root.join(".cargo/config.toml"),
480 r#"
481 [target.'cfg()']
482 rustflags = ["--cfg", "cfg_empty"]
483 "#,
484 )
485 .unwrap();
486
487 let config = Config::load_with_options(&root, test_options()).unwrap();
488 assert_eq!(config.rustflags(TARGET).unwrap(), None);
489 }
490
491 #[rustversion::attr(not(nightly), ignore)]
492 #[test]
493 #[cfg_attr(miri, ignore)] // Miri doesn't support std::process::Command: https://github.com/rust-lang/miri/issues/3374
494 #[cfg_attr(careful, ignore)] // TODO: Unexpected TomlError (bug in toml crate?)
495 fn cargo_config_toml() {
496 fn de(dir: &Path) -> de::Config {
497 // remove CARGO_PKG_DESCRIPTION -- if field in Cargo.toml contains newline, --format=toml display invalid toml
498 let output = Command::new("cargo")
499 .args(["-Z", "unstable-options", "config", "get", "--format=toml"])
500 .current_dir(dir)
501 .env_remove("CARGO_PKG_DESCRIPTION")
502 .output()
503 .unwrap();
504 assert!(output.status.success());
505 let s = str::from_utf8(&output.stdout).unwrap();
506 toml::from_str(s).unwrap()
507 }
508
509 let _config = de(&fixtures_dir().join("reference"));
510 }
511
512 #[rustversion::attr(not(nightly), ignore)]
513 #[test]
514 #[cfg_attr(miri, ignore)] // Miri doesn't support std::process::Command: https://github.com/rust-lang/miri/issues/3374
515 fn cargo_config_json() {
516 fn de(dir: &Path) -> de::Config {
517 let output = Command::new("cargo")
518 .args(["-Z", "unstable-options", "config", "get", "--format=json"])
519 .current_dir(dir)
520 .output()
521 .unwrap();
522 assert!(output.status.success());
523 let s = str::from_utf8(&output.stdout).unwrap();
524 serde_json::from_str(s).unwrap()
525 }
526
527 let _config = de(&fixtures_dir().join("reference"));
528 }
529
530 #[test]
531 #[cfg_attr(miri, ignore)] // Miri doesn't support std::process::Command: https://github.com/rust-lang/miri/issues/3374
532 fn test_cargo_behavior() {
533 let (_tmp, root) = test_project("empty");
534 let dir = &root;
535
536 // [env] table doesn't affect config resolution
537 // https://github.com/taiki-e/cargo-config2/issues/2
538 fs::write(
539 root.join(".cargo/config.toml"),
540 r#"
541 [env]
542 RUSTFLAGS = "--cfg a"
543 [build]
544 rustflags = "--cfg b"
545 "#,
546 )
547 .unwrap();
548 let output = Command::new("cargo")
549 .args(["build", "-v"])
550 .current_dir(dir)
551 .env("CARGO_HOME", root.join(".cargo"))
552 .env_remove("CARGO_ENCODED_RUSTFLAGS")
553 .env_remove("RUSTFLAGS")
554 .env_remove(format!("CARGO_TARGET_{}_RUSTFLAGS", TARGET.replace(['-', '.'], "_")))
555 .env_remove("CARGO_BUILD_RUSTFLAGS")
556 .output()
557 .unwrap();
558 assert!(output.status.success());
559 let stderr = str::from_utf8(&output.stderr).unwrap();
560 assert!(!stderr.contains("--cfg a"), "actual:\n---\n{stderr}\n---\n");
561 assert!(stderr.contains("--cfg b"), "actual:\n---\n{stderr}\n---\n");
562 }