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 "testing/gmock/include/gmock/gmock.h"
9
10namespace testing {
11
12template <typename T>
13class Capture {
14 public:
15  Capture() : value_(), has_value_(false) {}
16
17  const T& value() const { return value_; }
18  bool has_value() const { return has_value_; }
19
20  void SetValue(const T& value) {
21    DCHECK(!has_value());
22    value_ = value;
23    has_value_ = true;
24  }
25
26 private:
27  T value_;
28  bool has_value_;
29};
30
31
32namespace internal {
33
34template <typename T>
35class CaptureEqMatcher : public MatcherInterface<T> {
36 public:
37  explicit CaptureEqMatcher(Capture<T>* capture) : capture_(capture) {}
38
39  virtual void DescribeTo(std::ostream* os) const {
40    *os << "captured by " << static_cast<const void*>(capture_);
41    if (capture_->has_value()) *os << " which has value " << capture_->value();
42  }
43
44  virtual bool MatchAndExplain(T value, MatchResultListener* listener) const {
45    if (!capture_->has_value()) {
46      capture_->SetValue(value);
47      return true;
48    }
49    if (value != capture_->value()) {
50      *listener << "which is not equal to " << capture_->value();
51      return false;
52    }
53    return true;
54  }
55
56 private:
57  Capture<T>* capture_;
58};
59
60}  // namespace internal
61
62
63// CaptureEq(capture) captures the value passed in during matching as long as it
64// is unset, and once set, compares the value for equality with the argument.
65template <typename T>
66Matcher<T> CaptureEq(Capture<T>* capture) {
67  return MakeMatcher(new internal::CaptureEqMatcher<T>(capture));
68}
69
70}  // namespace testing
71
72#endif  // V8_TESTING_GMOCK_SUPPORT_H_
73