forked from rust-lang/cargo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
1855 lines (1650 loc) · 57.9 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
# Introduction to `support`.
Cargo has a wide variety of integration tests that execute the `cargo` binary
and verify its behavior. The `support` module contains many helpers to make
this process easy.
The general form of a test involves creating a "project", running cargo, and
checking the result. Projects are created with the `ProjectBuilder` where you
specify some files to create. The general form looks like this:
```
let p = project()
.file("src/main.rs", r#"fn main() { println!("hi!"); }"#)
.build();
```
If you do not specify a `Cargo.toml` manifest using `file()`, one is
automatically created with a project name of `foo` using `basic_manifest()`.
To run cargo, call the `cargo` method and make assertions on the execution:
```
p.cargo("run --bin foo")
.with_stderr(
"\
[COMPILING] foo [..]
[FINISHED] [..]
[RUNNING] `target/debug/foo`
",
)
.with_stdout("hi!")
.run();
```
The project creates a mini sandbox under the "cargo integration test"
directory with each test getting a separate directory such as
`/path/to/cargo/target/cit/t123/`. Each project appears as a separate
directory. There is also an empty `home` directory created that will be used
as a home directory instead of your normal home directory.
See `support::lines_match` for an explanation of the string pattern matching.
Browse the `pub` functions in the `support` module for a variety of other
helpful utilities.
## Testing Nightly Features
If you are testing a Cargo feature that only works on "nightly" cargo, then
you need to call `masquerade_as_nightly_cargo` on the process builder like
this:
```
p.cargo("build").masquerade_as_nightly_cargo()
```
If you are testing a feature that only works on *nightly rustc* (such as
benchmarks), then you should exit the test if it is not running with nightly
rust, like this:
```
if !is_nightly() {
// Add a comment here explaining why this is necessary.
return;
}
```
## Platform-specific Notes
When checking output, use `/` for paths even on Windows: the actual output
of `\` on Windows will be replaced with `/`.
Be careful when executing binaries on Windows. You should not rename, delete,
or overwrite a binary immediately after running it. Under some conditions
Windows will fail with errors like "directory not empty" or "failed to remove"
or "access is denied".
## Specifying Dependencies
You should not write any tests that use the network such as contacting
crates.io. Typically, simple path dependencies are the easiest way to add a
dependency. Example:
```
let p = project()
.file("Cargo.toml", r#"
[package]
name = "foo"
version = "1.0.0"
[dependencies]
bar = {path = "bar"}
"#)
.file("src/lib.rs", "extern crate bar;")
.file("bar/Cargo.toml", &basic_manifest("bar", "1.0.0"))
.file("bar/src/lib.rs", "")
.build();
```
If you need to test with registry dependencies, see
`support::registry::Package` for creating packages you can depend on.
If you need to test git dependencies, see `support::git` to create a git
dependency.
*/
#![allow(clippy::needless_doctest_main)] // according to @ehuss this lint is fussy
#![allow(clippy::inefficient_to_string)] // this causes suggestions that result in `(*s).to_string()`
use std::env;
use std::ffi::OsStr;
use std::fmt;
use std::fs;
use std::io::prelude::*;
use std::os;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::str;
use std::time::{self, Duration};
use std::usize;
use cargo::util::{is_ci, CargoResult, ProcessBuilder, ProcessError, Rustc};
use serde_json::{self, Value};
use url::Url;
use self::paths::CargoPathExt;
#[macro_export]
macro_rules! t {
($e:expr) => {
match $e {
Ok(e) => e,
Err(e) => panic!("{} failed with {}", stringify!($e), e),
}
};
}
pub use cargo_test_macro::cargo_test;
pub mod cross_compile;
pub mod git;
pub mod paths;
pub mod publish;
pub mod registry;
/*
*
* ===== Builders =====
*
*/
#[derive(PartialEq, Clone)]
struct FileBuilder {
path: PathBuf,
body: String,
}
impl FileBuilder {
pub fn new(path: PathBuf, body: &str) -> FileBuilder {
FileBuilder {
path,
body: body.to_string(),
}
}
fn mk(&self) {
self.dirname().mkdir_p();
let mut file = fs::File::create(&self.path)
.unwrap_or_else(|e| panic!("could not create file {}: {}", self.path.display(), e));
t!(file.write_all(self.body.as_bytes()));
}
fn dirname(&self) -> &Path {
self.path.parent().unwrap()
}
}
#[derive(PartialEq, Clone)]
struct SymlinkBuilder {
dst: PathBuf,
src: PathBuf,
src_is_dir: bool,
}
impl SymlinkBuilder {
pub fn new(dst: PathBuf, src: PathBuf) -> SymlinkBuilder {
SymlinkBuilder {
dst,
src,
src_is_dir: false,
}
}
pub fn new_dir(dst: PathBuf, src: PathBuf) -> SymlinkBuilder {
SymlinkBuilder {
dst,
src,
src_is_dir: true,
}
}
#[cfg(unix)]
fn mk(&self) {
self.dirname().mkdir_p();
t!(os::unix::fs::symlink(&self.dst, &self.src));
}
#[cfg(windows)]
fn mk(&self) {
self.dirname().mkdir_p();
if self.src_is_dir {
t!(os::windows::fs::symlink_dir(&self.dst, &self.src));
} else {
t!(os::windows::fs::symlink_file(&self.dst, &self.src));
}
}
fn dirname(&self) -> &Path {
self.src.parent().unwrap()
}
}
pub struct Project {
root: PathBuf,
}
#[must_use]
pub struct ProjectBuilder {
root: Project,
files: Vec<FileBuilder>,
symlinks: Vec<SymlinkBuilder>,
no_manifest: bool,
}
impl ProjectBuilder {
/// Root of the project, ex: `/path/to/cargo/target/cit/t0/foo`
pub fn root(&self) -> PathBuf {
self.root.root()
}
/// Project's debug dir, ex: `/path/to/cargo/target/cit/t0/foo/target/debug`
pub fn target_debug_dir(&self) -> PathBuf {
self.root.target_debug_dir()
}
pub fn new(root: PathBuf) -> ProjectBuilder {
ProjectBuilder {
root: Project { root },
files: vec![],
symlinks: vec![],
no_manifest: false,
}
}
pub fn at<P: AsRef<Path>>(mut self, path: P) -> Self {
self.root = Project {
root: paths::root().join(path),
};
self
}
/// Adds a file to the project.
pub fn file<B: AsRef<Path>>(mut self, path: B, body: &str) -> Self {
self._file(path.as_ref(), body);
self
}
fn _file(&mut self, path: &Path, body: &str) {
self.files
.push(FileBuilder::new(self.root.root().join(path), body));
}
/// Adds a symlink to a file to the project.
pub fn symlink<T: AsRef<Path>>(mut self, dst: T, src: T) -> Self {
self.symlinks.push(SymlinkBuilder::new(
self.root.root().join(dst),
self.root.root().join(src),
));
self
}
/// Create a symlink to a directory
pub fn symlink_dir<T: AsRef<Path>>(mut self, dst: T, src: T) -> Self {
self.symlinks.push(SymlinkBuilder::new_dir(
self.root.root().join(dst),
self.root.root().join(src),
));
self
}
pub fn no_manifest(mut self) -> Self {
self.no_manifest = true;
self
}
/// Creates the project.
pub fn build(mut self) -> Project {
// First, clean the directory if it already exists
self.rm_root();
// Create the empty directory
self.root.root().mkdir_p();
let manifest_path = self.root.root().join("Cargo.toml");
if !self.no_manifest && self.files.iter().all(|fb| fb.path != manifest_path) {
self._file(Path::new("Cargo.toml"), &basic_manifest("foo", "0.0.1"))
}
let past = time::SystemTime::now() - Duration::new(1, 0);
let ftime = filetime::FileTime::from_system_time(past);
for file in self.files.iter() {
file.mk();
if is_coarse_mtime() {
// Place the entire project 1 second in the past to ensure
// that if cargo is called multiple times, the 2nd call will
// see targets as "fresh". Without this, if cargo finishes in
// under 1 second, the second call will see the mtime of
// source == mtime of output and consider it dirty.
filetime::set_file_times(&file.path, ftime, ftime).unwrap();
}
}
for symlink in self.symlinks.iter() {
symlink.mk();
}
let ProjectBuilder { root, .. } = self;
root
}
fn rm_root(&self) {
self.root.root().rm_rf()
}
}
impl Project {
/// Root of the project, ex: `/path/to/cargo/target/cit/t0/foo`
pub fn root(&self) -> PathBuf {
self.root.clone()
}
/// Project's target dir, ex: `/path/to/cargo/target/cit/t0/foo/target`
pub fn build_dir(&self) -> PathBuf {
self.root().join("target")
}
/// Project's debug dir, ex: `/path/to/cargo/target/cit/t0/foo/target/debug`
pub fn target_debug_dir(&self) -> PathBuf {
self.build_dir().join("debug")
}
/// File url for root, ex: `file:///path/to/cargo/target/cit/t0/foo`
pub fn url(&self) -> Url {
path2url(self.root())
}
/// Path to an example built as a library.
/// `kind` should be one of: "lib", "rlib", "staticlib", "dylib", "proc-macro"
/// ex: `/path/to/cargo/target/cit/t0/foo/target/debug/examples/libex.rlib`
pub fn example_lib(&self, name: &str, kind: &str) -> PathBuf {
self.target_debug_dir()
.join("examples")
.join(paths::get_lib_filename(name, kind))
}
/// Path to a debug binary.
/// ex: `/path/to/cargo/target/cit/t0/foo/target/debug/foo`
pub fn bin(&self, b: &str) -> PathBuf {
self.build_dir()
.join("debug")
.join(&format!("{}{}", b, env::consts::EXE_SUFFIX))
}
/// Path to a release binary.
/// ex: `/path/to/cargo/target/cit/t0/foo/target/release/foo`
pub fn release_bin(&self, b: &str) -> PathBuf {
self.build_dir()
.join("release")
.join(&format!("{}{}", b, env::consts::EXE_SUFFIX))
}
/// Path to a debug binary for a specific target triple.
/// ex: `/path/to/cargo/target/cit/t0/foo/target/i686-apple-darwin/debug/foo`
pub fn target_bin(&self, target: &str, b: &str) -> PathBuf {
self.build_dir().join(target).join("debug").join(&format!(
"{}{}",
b,
env::consts::EXE_SUFFIX
))
}
/// Returns an iterator of paths matching the glob pattern, which is
/// relative to the project root.
pub fn glob<P: AsRef<Path>>(&self, pattern: P) -> glob::Paths {
let pattern = self.root().join(pattern);
glob::glob(pattern.to_str().expect("failed to convert pattern to str"))
.expect("failed to glob")
}
/// Changes the contents of an existing file.
pub fn change_file(&self, path: &str, body: &str) {
FileBuilder::new(self.root().join(path), body).mk()
}
/// Creates a `ProcessBuilder` to run a program in the project
/// and wrap it in an Execs to assert on the execution.
/// Example:
/// p.process(&p.bin("foo"))
/// .with_stdout("bar\n")
/// .run();
pub fn process<T: AsRef<OsStr>>(&self, program: T) -> Execs {
let mut p = process(program);
p.cwd(self.root());
execs().with_process_builder(p)
}
/// Creates a `ProcessBuilder` to run cargo.
/// Arguments can be separated by spaces.
/// Example:
/// p.cargo("build --bin foo").run();
pub fn cargo(&self, cmd: &str) -> Execs {
let mut execs = self.process(&cargo_exe());
if let Some(ref mut p) = execs.process_builder {
split_and_add_args(p, cmd);
}
execs
}
/// Safely run a process after `cargo build`.
///
/// Windows has a problem where a process cannot be reliably
/// be replaced, removed, or renamed immediately after executing it.
/// The action may fail (with errors like Access is denied), or
/// it may succeed, but future attempts to use the same filename
/// will fail with "Already Exists".
///
/// If you have a test that needs to do `cargo run` multiple
/// times, you should instead use `cargo build` and use this
/// method to run the executable. Each time you call this,
/// use a new name for `dst`.
/// See rust-lang/cargo#5481.
pub fn rename_run(&self, src: &str, dst: &str) -> Execs {
let src = self.bin(src);
let dst = self.bin(dst);
fs::rename(&src, &dst)
.unwrap_or_else(|e| panic!("Failed to rename `{:?}` to `{:?}`: {}", src, dst, e));
self.process(dst)
}
/// Returns the contents of `Cargo.lock`.
pub fn read_lockfile(&self) -> String {
self.read_file("Cargo.lock")
}
/// Returns the contents of a path in the project root
pub fn read_file(&self, path: &str) -> String {
let mut buffer = String::new();
fs::File::open(self.root().join(path))
.unwrap()
.read_to_string(&mut buffer)
.unwrap();
buffer
}
/// Modifies `Cargo.toml` to remove all commented lines.
pub fn uncomment_root_manifest(&self) {
let mut contents = String::new();
fs::File::open(self.root().join("Cargo.toml"))
.unwrap()
.read_to_string(&mut contents)
.unwrap();
fs::File::create(self.root().join("Cargo.toml"))
.unwrap()
.write_all(contents.replace("#", "").as_bytes())
.unwrap();
}
pub fn symlink(&self, src: impl AsRef<Path>, dst: impl AsRef<Path>) {
let src = self.root().join(src.as_ref());
let dst = self.root().join(dst.as_ref());
#[cfg(unix)]
{
if let Err(e) = os::unix::fs::symlink(&src, &dst) {
panic!("failed to symlink {:?} to {:?}: {:?}", src, dst, e);
}
}
#[cfg(windows)]
{
if src.is_dir() {
if let Err(e) = os::windows::fs::symlink_dir(&src, &dst) {
panic!("failed to symlink {:?} to {:?}: {:?}", src, dst, e);
}
} else {
if let Err(e) = os::windows::fs::symlink_file(&src, &dst) {
panic!("failed to symlink {:?} to {:?}: {:?}", src, dst, e);
}
}
}
}
}
// Generates a project layout
pub fn project() -> ProjectBuilder {
ProjectBuilder::new(paths::root().join("foo"))
}
// Generates a project layout inside our fake home dir
pub fn project_in_home(name: &str) -> ProjectBuilder {
ProjectBuilder::new(paths::home().join(name))
}
// === Helpers ===
pub fn main_file(println: &str, deps: &[&str]) -> String {
let mut buf = String::new();
for dep in deps.iter() {
buf.push_str(&format!("extern crate {};\n", dep));
}
buf.push_str("fn main() { println!(");
buf.push_str(println);
buf.push_str("); }\n");
buf
}
trait ErrMsg<T> {
fn with_err_msg(self, val: String) -> Result<T, String>;
}
impl<T, E: fmt::Display> ErrMsg<T> for Result<T, E> {
fn with_err_msg(self, val: String) -> Result<T, String> {
match self {
Ok(val) => Ok(val),
Err(err) => Err(format!("{}; original={}", val, err)),
}
}
}
// Path to cargo executables
pub fn cargo_dir() -> PathBuf {
env::var_os("CARGO_BIN_PATH")
.map(PathBuf::from)
.or_else(|| {
env::current_exe().ok().map(|mut path| {
path.pop();
if path.ends_with("deps") {
path.pop();
}
path
})
})
.unwrap_or_else(|| panic!("CARGO_BIN_PATH wasn't set. Cannot continue running test"))
}
pub fn cargo_exe() -> PathBuf {
cargo_dir().join(format!("cargo{}", env::consts::EXE_SUFFIX))
}
/*
*
* ===== Matchers =====
*
*/
pub type MatchResult = Result<(), String>;
#[must_use]
#[derive(Clone)]
pub struct Execs {
ran: bool,
process_builder: Option<ProcessBuilder>,
expect_stdout: Option<String>,
expect_stdin: Option<String>,
expect_stderr: Option<String>,
expect_exit_code: Option<i32>,
expect_stdout_contains: Vec<String>,
expect_stderr_contains: Vec<String>,
expect_either_contains: Vec<String>,
expect_stdout_contains_n: Vec<(String, usize)>,
expect_stdout_not_contains: Vec<String>,
expect_stderr_not_contains: Vec<String>,
expect_stderr_unordered: Vec<String>,
expect_neither_contains: Vec<String>,
expect_stderr_with_without: Vec<(Vec<String>, Vec<String>)>,
expect_json: Option<Vec<String>>,
expect_json_contains_unordered: Vec<String>,
stream_output: bool,
}
impl Execs {
pub fn with_process_builder(mut self, p: ProcessBuilder) -> Execs {
self.process_builder = Some(p);
self
}
/// Verifies that stdout is equal to the given lines.
/// See `lines_match` for supported patterns.
pub fn with_stdout<S: ToString>(&mut self, expected: S) -> &mut Self {
self.expect_stdout = Some(expected.to_string());
self
}
/// Verifies that stderr is equal to the given lines.
/// See `lines_match` for supported patterns.
pub fn with_stderr<S: ToString>(&mut self, expected: S) -> &mut Self {
self.expect_stderr = Some(expected.to_string());
self
}
/// Verifies the exit code from the process.
///
/// This is not necessary if the expected exit code is `0`.
pub fn with_status(&mut self, expected: i32) -> &mut Self {
self.expect_exit_code = Some(expected);
self
}
/// Removes exit code check for the process.
///
/// By default, the expected exit code is `0`.
pub fn without_status(&mut self) -> &mut Self {
self.expect_exit_code = None;
self
}
/// Verifies that stdout contains the given contiguous lines somewhere in
/// its output.
/// See `lines_match` for supported patterns.
pub fn with_stdout_contains<S: ToString>(&mut self, expected: S) -> &mut Self {
self.expect_stdout_contains.push(expected.to_string());
self
}
/// Verifies that stderr contains the given contiguous lines somewhere in
/// its output.
/// See `lines_match` for supported patterns.
pub fn with_stderr_contains<S: ToString>(&mut self, expected: S) -> &mut Self {
self.expect_stderr_contains.push(expected.to_string());
self
}
/// Verifies that either stdout or stderr contains the given contiguous
/// lines somewhere in its output.
/// See `lines_match` for supported patterns.
pub fn with_either_contains<S: ToString>(&mut self, expected: S) -> &mut Self {
self.expect_either_contains.push(expected.to_string());
self
}
/// Verifies that stdout contains the given contiguous lines somewhere in
/// its output, and should be repeated `number` times.
/// See `lines_match` for supported patterns.
pub fn with_stdout_contains_n<S: ToString>(&mut self, expected: S, number: usize) -> &mut Self {
self.expect_stdout_contains_n
.push((expected.to_string(), number));
self
}
/// Verifies that stdout does not contain the given contiguous lines.
/// See `lines_match` for supported patterns.
/// See note on `with_stderr_does_not_contain`.
pub fn with_stdout_does_not_contain<S: ToString>(&mut self, expected: S) -> &mut Self {
self.expect_stdout_not_contains.push(expected.to_string());
self
}
/// Verifies that stderr does not contain the given contiguous lines.
/// See `lines_match` for supported patterns.
///
/// Care should be taken when using this method because there is a
/// limitless number of possible things that *won't* appear. A typo means
/// your test will pass without verifying the correct behavior. If
/// possible, write the test first so that it fails, and then implement
/// your fix/feature to make it pass.
pub fn with_stderr_does_not_contain<S: ToString>(&mut self, expected: S) -> &mut Self {
self.expect_stderr_not_contains.push(expected.to_string());
self
}
/// Verifies that all of the stderr output is equal to the given lines,
/// ignoring the order of the lines.
/// See `lines_match` for supported patterns.
/// This is useful when checking the output of `cargo build -v` since
/// the order of the output is not always deterministic.
/// Recommend use `with_stderr_contains` instead unless you really want to
/// check *every* line of output.
///
/// Be careful when using patterns such as `[..]`, because you may end up
/// with multiple lines that might match, and this is not smart enough to
/// do anything like longest-match. For example, avoid something like:
///
/// [RUNNING] `rustc [..]
/// [RUNNING] `rustc --crate-name foo [..]
///
/// This will randomly fail if the other crate name is `bar`, and the
/// order changes.
pub fn with_stderr_unordered<S: ToString>(&mut self, expected: S) -> &mut Self {
self.expect_stderr_unordered.push(expected.to_string());
self
}
/// Verify that a particular line appears in stderr with and without the
/// given substrings. Exactly one line must match.
///
/// The substrings are matched as `contains`. Example:
///
/// ```no_run
/// execs.with_stderr_line_without(
/// &[
/// "[RUNNING] `rustc --crate-name build_script_build",
/// "-C opt-level=3",
/// ],
/// &["-C debuginfo", "-C incremental"],
/// )
/// ```
///
/// This will check that a build line includes `-C opt-level=3` but does
/// not contain `-C debuginfo` or `-C incremental`.
///
/// Be careful writing the `without` fragments, see note in
/// `with_stderr_does_not_contain`.
pub fn with_stderr_line_without<S: ToString>(
&mut self,
with: &[S],
without: &[S],
) -> &mut Self {
let with = with.iter().map(|s| s.to_string()).collect();
let without = without.iter().map(|s| s.to_string()).collect();
self.expect_stderr_with_without.push((with, without));
self
}
/// Verifies the JSON output matches the given JSON.
/// Typically used when testing cargo commands that emit JSON.
/// Each separate JSON object should be separated by a blank line.
/// Example:
/// assert_that(
/// p.cargo("metadata"),
/// execs().with_json(r#"
/// {"example": "abc"}
///
/// {"example": "def"}
/// "#)
/// );
/// Objects should match in the order given.
/// The order of arrays is ignored.
/// Strings support patterns described in `lines_match`.
/// Use `{...}` to match any object.
pub fn with_json(&mut self, expected: &str) -> &mut Self {
self.expect_json = Some(
expected
.split("\n\n")
.map(|line| line.to_string())
.collect(),
);
self
}
/// Verifies JSON output contains the given objects (in any order) somewhere
/// in its output.
///
/// CAUTION: Be very careful when using this. Make sure every object is
/// unique (not a subset of one another). Also avoid using objects that
/// could possibly match multiple output lines unless you're very sure of
/// what you are doing.
///
/// See `with_json` for more detail.
pub fn with_json_contains_unordered(&mut self, expected: &str) -> &mut Self {
self.expect_json_contains_unordered
.extend(expected.split("\n\n").map(|line| line.to_string()));
self
}
/// Forward subordinate process stdout/stderr to the terminal.
/// Useful for printf debugging of the tests.
/// CAUTION: CI will fail if you leave this in your test!
#[allow(unused)]
pub fn stream(&mut self) -> &mut Self {
self.stream_output = true;
self
}
pub fn arg<T: AsRef<OsStr>>(&mut self, arg: T) -> &mut Self {
if let Some(ref mut p) = self.process_builder {
p.arg(arg);
}
self
}
pub fn cwd<T: AsRef<OsStr>>(&mut self, path: T) -> &mut Self {
if let Some(ref mut p) = self.process_builder {
if let Some(cwd) = p.get_cwd() {
let new_path = cwd.join(path.as_ref());
p.cwd(new_path);
} else {
p.cwd(path);
}
}
self
}
pub fn env<T: AsRef<OsStr>>(&mut self, key: &str, val: T) -> &mut Self {
if let Some(ref mut p) = self.process_builder {
p.env(key, val);
}
self
}
pub fn env_remove(&mut self, key: &str) -> &mut Self {
if let Some(ref mut p) = self.process_builder {
p.env_remove(key);
}
self
}
pub fn exec_with_output(&mut self) -> CargoResult<Output> {
self.ran = true;
// TODO avoid unwrap
let p = (&self.process_builder).clone().unwrap();
p.exec_with_output()
}
pub fn build_command(&mut self) -> Command {
self.ran = true;
// TODO avoid unwrap
let p = (&self.process_builder).clone().unwrap();
p.build_command()
}
pub fn masquerade_as_nightly_cargo(&mut self) -> &mut Self {
if let Some(ref mut p) = self.process_builder {
p.masquerade_as_nightly_cargo();
}
self
}
pub fn run(&mut self) {
self.ran = true;
let p = (&self.process_builder).clone().unwrap();
if let Err(e) = self.match_process(&p) {
panic!("\nExpected: {:?}\n but: {}", self, e)
}
}
pub fn run_output(&mut self, output: &Output) {
self.ran = true;
if let Err(e) = self.match_output(output) {
panic!("\nExpected: {:?}\n but: {}", self, e)
}
}
fn verify_checks_output(&self, output: &Output) {
if self.expect_exit_code.unwrap_or(0) != 0
&& self.expect_stdout.is_none()
&& self.expect_stdin.is_none()
&& self.expect_stderr.is_none()
&& self.expect_stdout_contains.is_empty()
&& self.expect_stderr_contains.is_empty()
&& self.expect_either_contains.is_empty()
&& self.expect_stdout_contains_n.is_empty()
&& self.expect_stdout_not_contains.is_empty()
&& self.expect_stderr_not_contains.is_empty()
&& self.expect_stderr_unordered.is_empty()
&& self.expect_neither_contains.is_empty()
&& self.expect_stderr_with_without.is_empty()
&& self.expect_json.is_none()
&& self.expect_json_contains_unordered.is_empty()
{
panic!(
"`with_status()` is used, but no output is checked.\n\
The test must check the output to ensure the correct error is triggered.\n\
--- stdout\n{}\n--- stderr\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
}
}
fn match_process(&self, process: &ProcessBuilder) -> MatchResult {
println!("running {}", process);
let res = if self.stream_output {
if is_ci() {
panic!("`.stream()` is for local debugging")
}
process.exec_with_streaming(
&mut |out| {
println!("{}", out);
Ok(())
},
&mut |err| {
eprintln!("{}", err);
Ok(())
},
true,
)
} else {
process.exec_with_output()
};
match res {
Ok(out) => self.match_output(&out),
Err(e) => {
let err = e.downcast_ref::<ProcessError>();
if let Some(&ProcessError {
output: Some(ref out),
..
}) = err
{
return self.match_output(out);
}
Err(format!("could not exec process {}: {:?}", process, e))
}
}
}
fn match_output(&self, actual: &Output) -> MatchResult {
self.verify_checks_output(actual);
self.match_status(actual)
.and(self.match_stdout(actual))
.and(self.match_stderr(actual))
}
fn match_status(&self, actual: &Output) -> MatchResult {
match self.expect_exit_code {
None => Ok(()),
Some(code) if actual.status.code() == Some(code) => Ok(()),
Some(_) => Err(format!(
"exited with {}\n--- stdout\n{}\n--- stderr\n{}",
actual.status,
String::from_utf8_lossy(&actual.stdout),
String::from_utf8_lossy(&actual.stderr)
)),
}
}
fn match_stdout(&self, actual: &Output) -> MatchResult {
self.match_std(
self.expect_stdout.as_ref(),
&actual.stdout,
"stdout",
&actual.stderr,
MatchKind::Exact,
)?;
for expect in self.expect_stdout_contains.iter() {
self.match_std(
Some(expect),
&actual.stdout,
"stdout",
&actual.stderr,
MatchKind::Partial,
)?;
}
for expect in self.expect_stderr_contains.iter() {
self.match_std(
Some(expect),
&actual.stderr,
"stderr",
&actual.stdout,
MatchKind::Partial,
)?;
}
for &(ref expect, number) in self.expect_stdout_contains_n.iter() {
self.match_std(
Some(expect),
&actual.stdout,
"stdout",
&actual.stderr,
MatchKind::PartialN(number),
)?;
}
for expect in self.expect_stdout_not_contains.iter() {
self.match_std(
Some(expect),
&actual.stdout,
"stdout",
&actual.stderr,
MatchKind::NotPresent,
)?;
}
for expect in self.expect_stderr_not_contains.iter() {
self.match_std(
Some(expect),
&actual.stderr,
"stderr",
&actual.stdout,
MatchKind::NotPresent,
)?;
}
for expect in self.expect_stderr_unordered.iter() {
self.match_std(
Some(expect),
&actual.stderr,
"stderr",
&actual.stdout,