Debian Codegraph @

tests/test.rs

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