From 9d982fab0f069a9b9e2c68cc884bdb16252cc180 Mon Sep 17 00:00:00 2001 From: Andrew Gallant Date: Thu, 4 Jan 2024 11:42:34 -0500 Subject: [PATCH] pep440: add tests for human visible error messages Prior to the refactoring in previous commits, tests were generally written against the rendered error message instead of the structured message. This was in part because many of the error types themselves were just a `String`, but also to explicitly test what an end user actually sees. That's valuable. While we keep most of the tests as rewritten to target the new structured error representation, we add some new tests that captures the value of testing the messages than humans will actually see. --- crates/pep440-rs/src/version_specifier.rs | 61 +++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/crates/pep440-rs/src/version_specifier.rs b/crates/pep440-rs/src/version_specifier.rs index 8887c941c376..47d1b1eebf41 100644 --- a/crates/pep440-rs/src/version_specifier.rs +++ b/crates/pep440-rs/src/version_specifier.rs @@ -1589,4 +1589,65 @@ mod tests { assert_eq!(err.inner.start, 14); assert_eq!(err.inner.end, 18); } + + /// Tests the human readable error messages generated from an invalid + /// sequence of version specifiers. + #[test] + fn error_message_version_specifiers_parse_error() { + let specs = ">=1.2.3, 5.4.3, >=3.4.5"; + let err = VersionSpecifierParseError { + kind: Box::new(ParseErrorKind::MissingOperator), + }; + let inner = Box::new(VersionSpecifiersParseErrorInner { + err, + line: specs.to_string(), + start: 8, + end: 14, + }); + let err = VersionSpecifiersParseError { inner }; + assert_eq!(err, VersionSpecifiers::from_str(specs).unwrap_err()); + assert_eq!( + err.to_string(), + "\ +Failed to parse version: Unexpected end of version specifier, expected operator: +>=1.2.3, 5.4.3, >=3.4.5 + ^^^^^^ +" + ); + } + + /// Tests the human readable error messages generated when building an + /// invalid version specifier. + #[test] + fn error_message_version_specifier_build_error() { + let err = VersionSpecifierBuildError { + kind: Box::new(BuildErrorKind::CompatibleRelease), + }; + let op = Operator::TildeEqual; + let v = Version::new([5]); + let vpat = VersionPattern::verbatim(v); + assert_eq!(err, VersionSpecifier::new(op, vpat).unwrap_err()); + assert_eq!( + err.to_string(), + "The ~= operator requires at least two segments in the release version" + ); + } + + /// Tests the human readable error messages generated from parsing invalid + /// version specifier. + #[test] + fn error_message_version_specifier_parse_error() { + let err = VersionSpecifierParseError { + kind: Box::new(ParseErrorKind::InvalidSpecifier( + VersionSpecifierBuildError { + kind: Box::new(BuildErrorKind::CompatibleRelease), + }, + )), + }; + assert_eq!(err, VersionSpecifier::from_str("~=5").unwrap_err()); + assert_eq!( + err.to_string(), + "The ~= operator requires at least two segments in the release version" + ); + } }