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:
Capture()19   Capture() : value_(), has_value_(false) {}
20 
value()21   const T& value() const { return value_; }
has_value()22   bool has_value() const { return has_value_; }
23 
SetValue(const T & value)24   void SetValue(const T& value) {
25     DCHECK(!has_value());
26     value_ = value;
27     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 class CaptureEqMatcher : public MatcherInterface<T> {
40  public:
CaptureEqMatcher(Capture<T> * capture)41   explicit CaptureEqMatcher(Capture<T>* capture) : capture_(capture) {}
42 
DescribeTo(std::ostream * os)43   virtual void DescribeTo(std::ostream* os) const {
44     *os << "captured by " << static_cast<const void*>(capture_);
45     if (capture_->has_value()) *os << " which has value " << capture_->value();
46   }
47 
MatchAndExplain(T value,MatchResultListener * listener)48   virtual bool MatchAndExplain(T value, MatchResultListener* listener) const {
49     if (!capture_->has_value()) {
50       capture_->SetValue(value);
51       return true;
52     }
53     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 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   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>
CaptureEq(Capture<T> * capture)79 inline Matcher<T> CaptureEq(Capture<T>* capture) {
80   return MakeMatcher(new internal::CaptureEqMatcher<T>(capture));
81 }
82 
83 
84 // Creates a polymorphic matcher that matches any floating point NaN value.
85 MATCHER(IsNaN, std::string(negation ? "isn't" : "is") + " not a number") {
86   return std::isnan(arg);
87 }
88 
89 }  // namespace testing
90 
91 #endif  // V8_TESTING_GMOCK_SUPPORT_H_
92