Line data Source code
1 : // Copyright 2014 the V8 project authors. All rights reserved.
2 : // Use of this source code is governed by a BSD-style license that can be
3 : // found in the LICENSE file.
4 :
5 : #ifndef V8_TESTING_GMOCK_SUPPORT_H_
6 : #define V8_TESTING_GMOCK_SUPPORT_H_
7 :
8 : #include <cmath>
9 : #include <cstring>
10 : #include <string>
11 :
12 : #include "testing/gmock/include/gmock/gmock.h"
13 :
14 : namespace testing {
15 :
16 : template <typename T>
17 : class Capture {
18 : public:
19 19 : Capture() : value_(), has_value_(false) {}
20 :
21 : const T& value() const { return value_; }
22 : bool has_value() const { return has_value_; }
23 :
24 : void SetValue(const T& value) {
25 : DCHECK(!has_value());
26 22 : value_ = value;
27 22 : has_value_ = true;
28 : }
29 :
30 : private:
31 : T value_;
32 : bool has_value_;
33 : };
34 :
35 :
36 : namespace internal {
37 :
38 : template <typename T>
39 94 : class CaptureEqMatcher : public MatcherInterface<T> {
40 : public:
41 47 : explicit CaptureEqMatcher(Capture<T>* capture) : capture_(capture) {}
42 :
43 0 : virtual void DescribeTo(std::ostream* os) const {
44 0 : *os << "captured by " << static_cast<const void*>(capture_);
45 0 : if (capture_->has_value()) *os << " which has value " << capture_->value();
46 0 : }
47 :
48 48 : virtual bool MatchAndExplain(T value, MatchResultListener* listener) const {
49 48 : if (!capture_->has_value()) {
50 : capture_->SetValue(value);
51 22 : return true;
52 : }
53 26 : if (value != capture_->value()) {
54 : *listener << "which is not equal to " << capture_->value();
55 : return false;
56 : }
57 : return true;
58 : }
59 :
60 : private:
61 : Capture<T>* capture_;
62 : };
63 :
64 : } // namespace internal
65 :
66 :
67 : // Creates a polymorphic matcher that matches anything whose bit representation
68 : // is equal to that of {x}.
69 63336 : MATCHER_P(BitEq, x, std::string(negation ? "isn't" : "is") +
70 : " bitwise equal to " + PrintToString(x)) {
71 : static_assert(sizeof(x) == sizeof(arg), "Size mismatch");
72 10556 : return std::memcmp(&arg, &x, sizeof(x)) == 0;
73 : }
74 :
75 :
76 : // CaptureEq(capture) captures the value passed in during matching as long as it
77 : // is unset, and once set, compares the value for equality with the argument.
78 : template <typename T>
79 47 : inline Matcher<T> CaptureEq(Capture<T>* capture) {
80 94 : return MakeMatcher(new internal::CaptureEqMatcher<T>(capture));
81 : }
82 :
83 :
84 : // Creates a polymorphic matcher that matches any floating point NaN value.
85 402 : MATCHER(IsNaN, std::string(negation ? "isn't" : "is") + " not a number") {
86 134 : return std::isnan(arg);
87 : }
88 :
89 : } // namespace testing
90 :
91 : #endif // V8_TESTING_GMOCK_SUPPORT_H_
|