Skip to content

Commit 5d1b0f9

Browse files
committed
Switch cargo-test-support to anyhow.
1 parent 81537ee commit 5d1b0f9

File tree

1 file changed

+55
-72
lines changed
  • crates/cargo-test-support/src

1 file changed

+55
-72
lines changed

crates/cargo-test-support/src/lib.rs

Lines changed: 55 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use std::process::{Command, Output};
1616
use std::str;
1717
use std::time::{self, Duration};
1818

19+
use anyhow::{bail, format_err, Result};
1920
use cargo_util::{is_ci, ProcessBuilder, ProcessError};
2021
use serde_json::{self, Value};
2122
use url::Url;
@@ -413,19 +414,6 @@ pub fn main_file(println: &str, deps: &[&str]) -> String {
413414
buf
414415
}
415416

416-
trait ErrMsg<T> {
417-
fn with_err_msg(self, val: String) -> Result<T, String>;
418-
}
419-
420-
impl<T, E: fmt::Display> ErrMsg<T> for Result<T, E> {
421-
fn with_err_msg(self, val: String) -> Result<T, String> {
422-
match self {
423-
Ok(val) => Ok(val),
424-
Err(err) => Err(format!("{}; original={}", val, err)),
425-
}
426-
}
427-
}
428-
429417
// Path to cargo executables
430418
pub fn cargo_dir() -> PathBuf {
431419
env::var_os("CARGO_BIN_PATH")
@@ -452,8 +440,6 @@ pub fn cargo_exe() -> PathBuf {
452440
*
453441
*/
454442

455-
pub type MatchResult = Result<(), String>;
456-
457443
#[must_use]
458444
#[derive(Clone)]
459445
pub struct Execs {
@@ -703,7 +689,7 @@ impl Execs {
703689
self
704690
}
705691

706-
pub fn exec_with_output(&mut self) -> anyhow::Result<Output> {
692+
pub fn exec_with_output(&mut self) -> Result<Output> {
707693
self.ran = true;
708694
// TODO avoid unwrap
709695
let p = (&self.process_builder).clone().unwrap();
@@ -778,7 +764,7 @@ impl Execs {
778764
}
779765
}
780766

781-
fn match_process(&self, process: &ProcessBuilder) -> MatchResult {
767+
fn match_process(&self, process: &ProcessBuilder) -> Result<()> {
782768
println!("running {}", process);
783769
let res = if self.stream_output {
784770
if is_ci() {
@@ -814,32 +800,32 @@ impl Execs {
814800
.and(self.match_stdout(stdout, stderr))
815801
.and(self.match_stderr(stdout, stderr));
816802
}
817-
Err(format!("could not exec process {}: {:?}", process, e))
803+
bail!("could not exec process {}: {:?}", process, e)
818804
}
819805
}
820806
}
821807

822-
fn match_output(&self, actual: &Output) -> MatchResult {
808+
fn match_output(&self, actual: &Output) -> Result<()> {
823809
self.verify_checks_output(actual);
824810
self.match_status(actual.status.code(), &actual.stdout, &actual.stderr)
825811
.and(self.match_stdout(&actual.stdout, &actual.stderr))
826812
.and(self.match_stderr(&actual.stdout, &actual.stderr))
827813
}
828814

829-
fn match_status(&self, code: Option<i32>, stdout: &[u8], stderr: &[u8]) -> MatchResult {
815+
fn match_status(&self, code: Option<i32>, stdout: &[u8], stderr: &[u8]) -> Result<()> {
830816
match self.expect_exit_code {
831817
None => Ok(()),
832818
Some(expected) if code == Some(expected) => Ok(()),
833-
Some(_) => Err(format!(
819+
Some(_) => bail!(
834820
"exited with {:?}\n--- stdout\n{}\n--- stderr\n{}",
835821
code,
836822
String::from_utf8_lossy(stdout),
837823
String::from_utf8_lossy(stderr)
838-
)),
824+
),
839825
}
840826
}
841827

842-
fn match_stdout(&self, stdout: &[u8], stderr: &[u8]) -> MatchResult {
828+
fn match_stdout(&self, stdout: &[u8], stderr: &[u8]) -> Result<()> {
843829
self.match_std(
844830
self.expect_stdout.as_ref(),
845831
stdout,
@@ -908,12 +894,12 @@ impl Execs {
908894
self.match_std(Some(expect), stderr, "stderr", stderr, MatchKind::Partial);
909895

910896
if let (Err(_), Err(_)) = (match_std, match_err) {
911-
return Err(format!(
897+
bail!(
912898
"expected to find:\n\
913899
{}\n\n\
914900
did not find in either output.",
915901
expect
916-
));
902+
);
917903
}
918904
}
919905

@@ -923,18 +909,18 @@ impl Execs {
923909

924910
if let Some(ref objects) = self.expect_json {
925911
let stdout =
926-
str::from_utf8(stdout).map_err(|_| "stdout was not utf8 encoded".to_owned())?;
912+
str::from_utf8(stdout).map_err(|_| format_err!("stdout was not utf8 encoded"))?;
927913
let lines = stdout
928914
.lines()
929915
.filter(|line| line.starts_with('{'))
930916
.collect::<Vec<_>>();
931917
if lines.len() != objects.len() {
932-
return Err(format!(
918+
bail!(
933919
"expected {} json lines, got {}, stdout:\n{}",
934920
objects.len(),
935921
lines.len(),
936922
stdout
937-
));
923+
);
938924
}
939925
for (obj, line) in objects.iter().zip(lines) {
940926
self.match_json(obj, line)?;
@@ -943,7 +929,7 @@ impl Execs {
943929

944930
if !self.expect_json_contains_unordered.is_empty() {
945931
let stdout =
946-
str::from_utf8(stdout).map_err(|_| "stdout was not utf8 encoded".to_owned())?;
932+
str::from_utf8(stdout).map_err(|_| format_err!("stdout was not utf8 encoded"))?;
947933
let mut lines = stdout
948934
.lines()
949935
.filter(|line| line.starts_with('{'))
@@ -955,22 +941,22 @@ impl Execs {
955941
{
956942
Some(index) => lines.remove(index),
957943
None => {
958-
return Err(format!(
944+
bail!(
959945
"Did not find expected JSON:\n\
960946
{}\n\
961947
Remaining available output:\n\
962948
{}\n",
963949
serde_json::to_string_pretty(obj).unwrap(),
964950
lines.join("\n")
965-
));
951+
);
966952
}
967953
};
968954
}
969955
}
970956
Ok(())
971957
}
972958

973-
fn match_stderr(&self, stdout: &[u8], stderr: &[u8]) -> MatchResult {
959+
fn match_stderr(&self, stdout: &[u8], stderr: &[u8]) -> Result<()> {
974960
self.match_std(
975961
self.expect_stderr.as_ref(),
976962
stderr,
@@ -980,9 +966,9 @@ impl Execs {
980966
)
981967
}
982968

983-
fn normalize_actual(&self, description: &str, actual: &[u8]) -> Result<String, String> {
969+
fn normalize_actual(&self, description: &str, actual: &[u8]) -> Result<String> {
984970
let actual = match str::from_utf8(actual) {
985-
Err(..) => return Err(format!("{} was not utf8 encoded", description)),
971+
Err(..) => bail!("{} was not utf8 encoded", description),
986972
Ok(actual) => actual,
987973
};
988974
Ok(self.normalize_matcher(actual))
@@ -1002,7 +988,7 @@ impl Execs {
1002988
description: &str,
1003989
extra: &[u8],
1004990
kind: MatchKind,
1005-
) -> MatchResult {
991+
) -> Result<()> {
1006992
let out = match expected {
1007993
Some(out) => self.normalize_matcher(out),
1008994
None => return Ok(()),
@@ -1019,14 +1005,14 @@ impl Execs {
10191005
if diffs.is_empty() {
10201006
Ok(())
10211007
} else {
1022-
Err(format!(
1008+
bail!(
10231009
"differences:\n\
10241010
{}\n\n\
10251011
other output:\n\
10261012
`{}`",
10271013
diffs.join("\n"),
10281014
String::from_utf8_lossy(extra)
1029-
))
1015+
)
10301016
}
10311017
}
10321018
MatchKind::Partial => {
@@ -1043,13 +1029,14 @@ impl Execs {
10431029
if diffs.is_empty() {
10441030
Ok(())
10451031
} else {
1046-
Err(format!(
1032+
bail!(
10471033
"expected to find:\n\
10481034
{}\n\n\
10491035
did not find in output:\n\
10501036
{}",
1051-
out, actual
1052-
))
1037+
out,
1038+
actual
1039+
)
10531040
}
10541041
}
10551042
MatchKind::PartialN(number) => {
@@ -1068,13 +1055,15 @@ impl Execs {
10681055
if matches == number {
10691056
Ok(())
10701057
} else {
1071-
Err(format!(
1058+
bail!(
10721059
"expected to find {} occurrences:\n\
10731060
{}\n\n\
10741061
did not find in output:\n\
10751062
{}",
1076-
number, out, actual
1077-
))
1063+
number,
1064+
out,
1065+
actual
1066+
)
10781067
}
10791068
}
10801069
MatchKind::NotPresent => {
@@ -1089,13 +1078,14 @@ impl Execs {
10891078
}
10901079
}
10911080
if diffs.is_empty() {
1092-
Err(format!(
1081+
bail!(
10931082
"expected not to find:\n\
10941083
{}\n\n\
10951084
but found in output:\n\
10961085
{}",
1097-
out, actual
1098-
))
1086+
out,
1087+
actual
1088+
)
10991089
} else {
11001090
Ok(())
11011091
}
@@ -1104,12 +1094,7 @@ impl Execs {
11041094
}
11051095
}
11061096

1107-
fn match_with_without(
1108-
&self,
1109-
actual: &[u8],
1110-
with: &[String],
1111-
without: &[String],
1112-
) -> MatchResult {
1097+
fn match_with_without(&self, actual: &[u8], with: &[String], without: &[String]) -> Result<()> {
11131098
let actual = self.normalize_actual("stderr", actual)?;
11141099
let contains = |s, line| {
11151100
let mut s = self.normalize_matcher(s);
@@ -1123,16 +1108,18 @@ impl Execs {
11231108
.filter(|line| !without.iter().any(|without| contains(without, line)))
11241109
.collect();
11251110
match matches.len() {
1126-
0 => Err(format!(
1111+
0 => bail!(
11271112
"Could not find expected line in output.\n\
11281113
With contents: {:?}\n\
11291114
Without contents: {:?}\n\
11301115
Actual stderr:\n\
11311116
{}\n",
1132-
with, without, actual
1133-
)),
1117+
with,
1118+
without,
1119+
actual
1120+
),
11341121
1 => Ok(()),
1135-
_ => Err(format!(
1122+
_ => bail!(
11361123
"Found multiple matching lines, but only expected one.\n\
11371124
With contents: {:?}\n\
11381125
Without contents: {:?}\n\
@@ -1141,17 +1128,17 @@ impl Execs {
11411128
with,
11421129
without,
11431130
matches.join("\n")
1144-
)),
1131+
),
11451132
}
11461133
}
11471134

1148-
fn match_json(&self, expected: &str, line: &str) -> MatchResult {
1135+
fn match_json(&self, expected: &str, line: &str) -> Result<()> {
11491136
let actual = match line.parse() {
1150-
Err(e) => return Err(format!("invalid json, {}:\n`{}`", e, line)),
1137+
Err(e) => bail!("invalid json, {}:\n`{}`", e, line),
11511138
Ok(actual) => actual,
11521139
};
11531140
let expected = match expected.parse() {
1154-
Err(e) => return Err(format!("invalid json, {}:\n`{}`", e, line)),
1141+
Err(e) => bail!("invalid json, {}:\n`{}`", e, line),
11551142
Ok(expected) => expected,
11561143
};
11571144

@@ -1231,7 +1218,7 @@ pub fn lines_match(expected: &str, mut actual: &str) -> bool {
12311218
actual.is_empty() || expected.ends_with("[..]")
12321219
}
12331220

1234-
pub fn lines_match_unordered(expected: &str, actual: &str) -> Result<(), String> {
1221+
pub fn lines_match_unordered(expected: &str, actual: &str) -> Result<()> {
12351222
let mut a = actual.lines().collect::<Vec<_>>();
12361223
// match more-constrained lines first, although in theory we'll
12371224
// need some sort of recursive match here. This handles the case
@@ -1252,19 +1239,19 @@ pub fn lines_match_unordered(expected: &str, actual: &str) -> Result<(), String>
12521239
}
12531240
}
12541241
if !failures.is_empty() {
1255-
return Err(format!(
1242+
bail!(
12561243
"Did not find expected line(s):\n{}\n\
12571244
Remaining available output:\n{}\n",
12581245
failures.join("\n"),
12591246
a.join("\n")
1260-
));
1247+
);
12611248
}
12621249
if !a.is_empty() {
1263-
Err(format!(
1250+
bail!(
12641251
"Output included extra lines:\n\
12651252
{}\n",
12661253
a.join("\n")
1267-
))
1254+
)
12681255
} else {
12691256
Ok(())
12701257
}
@@ -1334,19 +1321,15 @@ fn lines_match_works() {
13341321
/// as paths). You can use a `"{...}"` string literal as a wildcard for
13351322
/// arbitrary nested JSON (useful for parts of object emitted by other programs
13361323
/// (e.g., rustc) rather than Cargo itself).
1337-
pub fn find_json_mismatch(
1338-
expected: &Value,
1339-
actual: &Value,
1340-
cwd: Option<&Path>,
1341-
) -> Result<(), String> {
1324+
pub fn find_json_mismatch(expected: &Value, actual: &Value, cwd: Option<&Path>) -> Result<()> {
13421325
match find_json_mismatch_r(expected, actual, cwd) {
1343-
Some((expected_part, actual_part)) => Err(format!(
1326+
Some((expected_part, actual_part)) => bail!(
13441327
"JSON mismatch\nExpected:\n{}\nWas:\n{}\nExpected part:\n{}\nActual part:\n{}\n",
13451328
serde_json::to_string_pretty(expected).unwrap(),
13461329
serde_json::to_string_pretty(&actual).unwrap(),
13471330
serde_json::to_string_pretty(expected_part).unwrap(),
13481331
serde_json::to_string_pretty(actual_part).unwrap(),
1349-
)),
1332+
),
13501333
None => Ok(()),
13511334
}
13521335
}

0 commit comments

Comments
 (0)