expectest/core/
actual.rs

1use crate::core::{Join, Matcher, SourceLocation, TestResult};
2
3/// Creates a new instance of `ActualValue` using `value`.
4///
5/// This function intended to replace an `expect!` macro if desired.
6pub fn expect<A>(value: A) -> ActualValue<A> {
7    ActualValue::new(value)
8}
9
10/// Represent an actual value and optional location of a test case in a source code.
11#[derive(Debug)]
12pub struct ActualValue<A> {
13    value: A,
14    location: Option<SourceLocation>,
15}
16
17impl<A> ActualValue<A> {
18    /// Creates a new instance of `ActualValue` using `value`.
19    ///
20    /// Also to create a new instance you can use `expect` function or `expect!` macro.
21    /// Macro is better because it can save location of a test case in a source code.
22    pub fn new(value: A) -> Self {
23        ActualValue {
24            value: value,
25            location: None,
26        }
27    }
28
29    /// Sets a new `SourceLocation`.
30    pub fn location(mut self, l: SourceLocation) -> Self {
31        self.location = Some(l);
32        self
33    }
34
35    /// Performs assertion matching using `matcher`. Returns a new instance of `TestResult`.
36    pub fn to<M, E>(self, matcher: M) -> TestResult
37    where
38        M: Matcher<A, E>,
39    {
40        self.matching(matcher, Join::To)
41    }
42
43    /// Performs negation matching using `matcher`. Returns a new instance of `TestResult`.
44    pub fn to_not<M, E>(self, matcher: M) -> TestResult
45    where
46        M: Matcher<A, E>,
47    {
48        self.matching(matcher, Join::ToNot)
49    }
50
51    /// Performs negation matching using `matcher`. Returns a new instance of `TestResult`.
52    pub fn not_to<M, E>(self, matcher: M) -> TestResult
53    where
54        M: Matcher<A, E>,
55    {
56        self.matching(matcher, Join::NotTo)
57    }
58
59    /// Performs matching using `matcher` and `join`. Returns a new instance of `TestResult`.
60    fn matching<M, E>(self, matcher: M, join: Join) -> TestResult
61    where
62        M: Matcher<A, E>,
63    {
64        let success = if join.is_assertion() {
65            matcher.matches(&self.value)
66        } else {
67            !matcher.matches(&self.value)
68        };
69        if success {
70            TestResult::new_success()
71        } else {
72            let message = matcher.failure_message(join, &self.value);
73            TestResult::new_failure(message, self.location)
74        }
75    }
76}