test_that/matcher.rs
1// Copyright 2022 Google LLC
2// Copyright 2026 Bradford Hovinen <bradford@hovinen.me>
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! The components required to implement matchers.
17
18use crate::{
19 description::Description,
20 internal::{source_location::SourceLocation, test_outcome::TestAssertionFailure},
21 matchers::__internal::{ConjunctionMatcher, DisjunctionMatcher},
22};
23use core::fmt::Debug;
24
25/// Represents an arbitrary condition on data of the given type which can be
26/// checked to perform an assertion.
27///
28/// Matchers are the core of the assertion language of Test That!. They can be
29/// combined and composed to assert on complex data structures. The variety
30/// of available matchers allows precise specification of the intent of the
31/// assertion.
32///
33/// Matchers can be logically combined with the [`and`] and [`or`] methods as
34/// well as the [`not`] matcher.
35///
36/// This trait is implemented for tuples of up to twelve arbitrary
37/// implementations of `Matcher`. So one can match tuples of up to twelve
38/// items using corresponding tuple of matchers.
39///
40/// ```rust
41/// # use test_that::prelude::*;
42/// let value = (1, "Hello, world");
43/// assert_that!(value, (eq(1), ends_with("world")));
44/// ```
45///
46/// Tuples of more than twelve items do not automatically inherit the `Debug`
47/// trait from their members, so are generally not supported; see
48/// [Rust by Example](https://doc.rust-lang.org/rust-by-example/primitives/tuples.html#tuples).
49///
50/// [`and`]: crate::matcher::MatcherExt::and
51/// [`or`]: crate::matcher::MatcherExt::or
52/// [`not`]: crate::matchers::not
53pub trait Matcher<ActualT: Debug + ?Sized>: Describable {
54 /// Returns whether the condition matches the datum `actual`.
55 ///
56 /// The trait implementation defines what it means to "match". Often the
57 /// matching condition is based on data stored in the matcher. For example,
58 /// `eq` matches when its stored expected value is equal (in the sense of
59 /// the `==` operator) to the value `actual`.
60 fn matches(&self, actual: &ActualT) -> MatcherResult;
61
62 /// Builds a [`String`] describing how the expected value
63 /// encoded in this instance matches or does not match the given value
64 /// `actual`.
65 ///
66 /// This should be in the form of a relative clause, i.e. something starting
67 /// with a relative pronoun such as "which" or "whose". It will appear next
68 /// to the actual value in an assertion failure. For example:
69 ///
70 /// ```text
71 /// Value of: ...
72 /// Expected: ...
73 /// Actual: ["Something"], which does not contain "Something else"
74 /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
75 /// ```
76 ///
77 /// The default implementation relies on
78 /// [`describe`][Describable::describe]. Thus it does not make any use
79 /// of the actual value itself, but rather only whether the value is
80 /// matched.
81 ///
82 /// Override the default implementation to provide additional context on why
83 /// a particular value matched or did not match. For example, the
84 /// [`container_eq`][crate::matchers::containers::container_eq] matcher
85 /// displays information on which elements of the actual value were not
86 /// present in the expected value and vice versa.
87 ///
88 /// This implementation should be overridden in any matcher which contains
89 /// one or more inner matchers. The implementation should invoke
90 /// `explain_match` on the inner matchers, so that the generated match
91 /// explanation also reflects their implementation. Without this, the match
92 /// explanation of the inner matchers will not be able to make use of the
93 /// actual value at all.
94 ///
95 /// For example, the `explain_match` implementation of the matcher
96 /// [`points_to`][crate::matchers::points_to] defers immediately to the
97 /// inner matcher and appears as follows:
98 ///
99 /// ```ignore
100 /// fn explain_match(&self, actual: &Self::ActualT) -> Description {
101 /// self.expected.explain_match(actual.deref())
102 /// }
103 /// ```
104 ///
105 /// The matcher can also provide some additional context before deferring to
106 /// an inner matcher. In that case it should invoke `explain_match` on the
107 /// inner matcher at a point where a relative clause would fit. For example:
108 ///
109 /// ```ignore
110 /// fn explain_match(&self, actual: &Self::ActualT) -> Description {
111 /// Description::new()
112 /// .text("which points to a value")
113 /// .nested(self.expected.explain_match(actual.deref()))
114 /// }
115 /// ```
116 ///
117 /// [`String`]: alloc::string::String
118 fn explain_match(&self, actual: &ActualT) -> Description {
119 format!("which {}", self.describe(self.matches(actual))).into()
120 }
121}
122
123/// Extension methods for composing matchers.
124///
125/// This trait is implemented for all [`Sized`] types, but the resulting
126/// combinators are only useful when the underlying types implement [`Matcher`].
127//
128// This is kept separate from [`Matcher`] so that the type parameter `ActualT`
129// does not need to be known at the `.and()` / `.or()` call site. Type
130// inference determines `ActualT` later, when the combined matcher is applied
131// to an actual value.
132pub trait MatcherExt: Sized {
133 /// Constructs a matcher that matches both `self` and `right`.
134 ///
135 /// ```
136 /// # use test_that::prelude::*;
137 /// # fn should_pass() -> TestResult<()> {
138 /// verify_that!("A string", starts_with("A").and(ends_with("string")))?; // Passes
139 /// # Ok(())
140 /// # }
141 /// # fn should_fail_1() -> TestResult<()> {
142 /// verify_that!("A string", starts_with("Another").and(ends_with("string")))?; // Fails
143 /// # Ok(())
144 /// # }
145 /// # fn should_fail_2() -> TestResult<()> {
146 /// verify_that!("A string", starts_with("A").and(ends_with("non-string")))?; // Fails
147 /// # Ok(())
148 /// # }
149 /// # should_pass().unwrap();
150 /// # should_fail_1().unwrap_err();
151 /// # should_fail_2().unwrap_err();
152 /// ```
153 fn and<Right>(self, right: Right) -> ConjunctionMatcher<Self, Right> {
154 ConjunctionMatcher::new(self, right)
155 }
156
157 /// Constructs a matcher that matches when at least one of `self` or `right`
158 /// matches the input.
159 ///
160 /// ```
161 /// # use test_that::prelude::*;
162 /// # fn should_pass() -> TestResult<()> {
163 /// verify_that!(10, eq(2).or(ge(5)))?; // Passes
164 /// verify_that!(10, eq(2).or(eq(5)).or(ge(9)))?; // Passes
165 /// # Ok(())
166 /// # }
167 /// # fn should_fail() -> TestResult<()> {
168 /// verify_that!(10, eq(2).or(ge(15)))?; // Fails
169 /// # Ok(())
170 /// # }
171 /// # should_pass().unwrap();
172 /// # should_fail().unwrap_err();
173 /// ```
174 fn or<Right>(self, right: Right) -> DisjunctionMatcher<Self, Right> {
175 DisjunctionMatcher::new(self, right)
176 }
177}
178
179impl<M: Sized> MatcherExt for M {}
180
181/// An item, normally a [Matcher] with positive and negative valences which can
182/// be turned into a [Description] for human consumption.
183pub trait Describable {
184 /// Returns a description of `self` or a negative description if
185 /// `matcher_result` is `DoesNotMatch`.
186 ///
187 /// The function should print a verb phrase that describes the property
188 /// that a value which matches (or, respectively, does not match) this
189 /// matcher should have. The subject of the verb phrase is the value being
190 /// matched.
191 ///
192 /// The output appears next to `Expected` in an assertion failure message.
193 /// For example:
194 ///
195 /// ```text
196 /// Value of: ...
197 /// Expected: is equal to 7
198 /// ^^^^^^^^^^^^^
199 /// Actual: ...
200 /// ```
201 ///
202 /// When the matcher contains one or more inner matchers, the implementation
203 /// should invoke [`Self::describe`] on the inner matchers to complete the
204 /// description. It should place the inner description at a point where a
205 /// verb phrase would fit. For example, the matcher
206 /// [`some`][crate::matchers::some] implements `describe` as follows:
207 ///
208 /// ```ignore
209 /// fn describe(&self, matcher_result: MatcherResult) -> Description {
210 /// match matcher_result {
211 /// MatcherResult::Matches => {
212 /// Description::new()
213 /// .text("has a value which")
214 /// .nested(self.inner.describe(MatcherResult::Matches))
215 /// // Inner matcher: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
216 /// }
217 /// MatcherResult::DoesNotMatch => {...} // Similar to the above
218 /// }
219 /// }
220 /// ```
221 ///
222 /// The output expectation differs from that of
223 /// [`explain_match`][Matcher::explain_match] in that it is a verb phrase
224 /// (beginning with a verb like "is") rather than a relative clause
225 /// (beginning with "which" or "whose"). This difference is because the
226 /// output of `explain_match` is always used adjectivally to describe the
227 /// actual value, while `describe` is used in contexts where a relative
228 /// clause would not make sense.
229 fn describe(&self, matcher_result: MatcherResult) -> Description;
230}
231
232/// Any actual value whose debug length is greater than this value will be
233/// pretty-printed. Otherwise, it will have normal debug output formatting.
234const PRETTY_PRINT_LENGTH_THRESHOLD: usize = 60;
235
236/// Constructs a [`TestAssertionFailure`] reporting that the given `matcher`
237/// does not match the value `actual`.
238///
239/// The parameter `actual_expr` contains the expression which was evaluated to
240/// obtain `actual`.
241pub(crate) fn create_assertion_failure<T: Debug + ?Sized>(
242 matcher: &impl Matcher<T>,
243 actual: &T,
244 actual_expr: &'static str,
245 source_location: SourceLocation,
246) -> TestAssertionFailure {
247 let actual_formatted = format!("{actual:?}");
248 let actual_formatted = if actual_formatted.len() > PRETTY_PRINT_LENGTH_THRESHOLD {
249 format!("{actual:#?}")
250 } else {
251 actual_formatted
252 };
253 TestAssertionFailure::create(format!(
254 "\
255Value of: {actual_expr}
256Expected: {}
257Actual: {actual_formatted},
258{}
259{source_location}",
260 matcher.describe(MatcherResult::Match),
261 matcher.explain_match(actual).indent(),
262 ))
263}
264
265/// The result of applying a [`Matcher`] on an actual value.
266#[derive(Debug, PartialEq, Clone, Copy)]
267pub enum MatcherResult {
268 /// The actual value matches according to the [`Matcher`] definition.
269 Match,
270 /// The actual value does not match according to the [`Matcher`] definition.
271 NoMatch,
272}
273
274impl From<bool> for MatcherResult {
275 fn from(b: bool) -> Self {
276 if b { MatcherResult::Match } else { MatcherResult::NoMatch }
277 }
278}
279
280impl From<MatcherResult> for bool {
281 fn from(matcher_result: MatcherResult) -> Self {
282 matcher_result.is_match()
283 }
284}
285
286impl MatcherResult {
287 /// Returns `true` if `self` is [`MatcherResult::Match`], otherwise
288 /// `false`.
289 pub fn is_match(self) -> bool {
290 matches!(self, MatcherResult::Match)
291 }
292
293 /// Returns `true` if `self` is [`MatcherResult::NoMatch`], otherwise
294 /// `false`.
295 pub fn is_no_match(self) -> bool {
296 matches!(self, MatcherResult::NoMatch)
297 }
298}