1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25
   26
   27
   28
   29
   30
   31
   32
   33
   34
   35
   36
   37
   38
   39
   40
   41
   42
   43
   44
   45
   46
   47
   48
   49
   50
   51
   52
   53
   54
   55
   56
   57
   58
   59
   60
   61
   62
   63
   64
   65
   66
   67
   68
   69
   70
   71
   72
   73
   74
   75
   76
   77
   78
   79
   80
   81
   82
   83
   84
   85
   86
   87
   88
   89
   90
   91
   92
   93
   94
   95
   96
   97
   98
   99
  100
  101
  102
  103
  104
  105
  106
  107
  108
  109
  110
  111
  112
  113
  114
  115
  116
  117
  118
  119
  120
  121
  122
  123
  124
  125
  126
  127
  128
  129
  130
  131
  132
  133
  134
  135
  136
  137
  138
  139
  140
  141
  142
  143
  144
  145
  146
  147
  148
  149
  150
  151
  152
  153
  154
  155
  156
  157
  158
  159
  160
  161
  162
  163
  164
  165
  166
  167
  168
  169
  170
  171
  172
  173
  174
  175
  176
  177
  178
  179
  180
  181
  182
  183
  184
  185
  186
  187
  188
  189
  190
  191
  192
  193
  194
  195
  196
  197
  198
  199
  200
  201
  202
  203
  204
  205
  206
  207
  208
  209
  210
  211
  212
  213
  214
  215
  216
  217
  218
  219
  220
  221
  222
  223
  224
  225
  226
  227
  228
  229
  230
  231
  232
  233
  234
  235
  236
  237
  238
  239
  240
  241
  242
  243
  244
  245
  246
  247
  248
  249

base / test / gmock_expected_support.h [blame]

// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef BASE_TEST_GMOCK_EXPECTED_SUPPORT_H_
#define BASE_TEST_GMOCK_EXPECTED_SUPPORT_H_

#include <ostream>
#include <string>
#include <type_traits>
#include <utility>

#include "base/strings/strcat.h"
#include "base/strings/to_string.h"
#include "base/types/expected.h"
#include "base/types/expected_internal.h"
#include "base/types/expected_macros.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace base::test {

namespace internal {

// `HasVoidValueType<T>` is true iff `T` satisfies
// `base::internal::IsExpected<T>` and `T`'s `value_type` is `void`.
template <typename T>
concept HasVoidValueType =
    base::internal::IsExpected<T> &&
    std::is_void_v<typename std::remove_cvref_t<T>::value_type>;

// Implementation for matcher `HasValue`.
class HasValueMatcher {
 public:
  HasValueMatcher() = default;

  template <typename T>
  operator ::testing::Matcher<T>() const {  // NOLINT
    return ::testing::Matcher<T>(new Impl<const T&>());
  }

 private:
  template <typename T>
    requires(base::internal::IsExpected<T>)
  class Impl : public ::testing::MatcherInterface<T> {
   public:
    Impl() = default;

    void DescribeTo(std::ostream* os) const override {
      *os << "is an 'expected' type with a value";
    }

    void DescribeNegationTo(std::ostream* os) const override {
      *os << "is an 'expected' type with an error";
    }

    bool MatchAndExplain(
        T actual_value,
        ::testing::MatchResultListener* listener) const override {
      if (!actual_value.has_value()) {
        *listener << "which has the error " << ToString(actual_value.error());
      }
      return actual_value.has_value();
    }
  };
};

// Implementation for matcher `ValueIs`.
template <typename T>
class ValueIsMatcher {
 public:
  explicit ValueIsMatcher(T matcher) : matcher_(std::move(matcher)) {}

  template <typename U>
  operator ::testing::Matcher<U>() const {  // NOLINT
    return ::testing::Matcher<U>(new Impl<const U&>(matcher_));
  }

 private:
  template <typename U>
    requires(base::internal::IsExpected<U> && !HasVoidValueType<U>)
  class Impl : public ::testing::MatcherInterface<U> {
   public:
    explicit Impl(const T& matcher)
        : matcher_(::testing::SafeMatcherCast<const V&>(matcher)) {}

    void DescribeTo(std::ostream* os) const override {
      *os << "is an 'expected' type with a value which ";
      matcher_.DescribeTo(os);
    }

    void DescribeNegationTo(std::ostream* os) const override {
      *os << "is an 'expected' type with an error or a value which ";
      matcher_.DescribeNegationTo(os);
    }

    bool MatchAndExplain(
        U actual_value,
        ::testing::MatchResultListener* listener) const override {
      if (!actual_value.has_value()) {
        *listener << "which has the error " << ToString(actual_value.error());
        return false;
      }

      ::testing::StringMatchResultListener inner_listener;
      const bool match =
          matcher_.MatchAndExplain(actual_value.value(), &inner_listener);
      const std::string explanation = inner_listener.str();
      if (!explanation.empty()) {
        *listener << "which has the value " << ToString(actual_value.value())
                  << ", " << explanation;
      }
      return match;
    }

   private:
    using V = typename std::remove_cvref_t<U>::value_type;

    const ::testing::Matcher<const V&> matcher_;
  };

  const T matcher_;
};

// Implementation for matcher `ErrorIs`.
template <typename T>
class ErrorIsMatcher {
 public:
  explicit ErrorIsMatcher(T matcher) : matcher_(std::move(matcher)) {}

  template <typename U>
  operator ::testing::Matcher<U>() const {  // NOLINT
    return ::testing::Matcher<U>(new Impl<const U&>(matcher_));
  }

 private:
  template <typename U>
    requires(base::internal::IsExpected<U>)
  class Impl : public ::testing::MatcherInterface<U> {
   public:
    explicit Impl(const T& matcher)
        : matcher_(::testing::SafeMatcherCast<const E&>(matcher)) {}

    void DescribeTo(std::ostream* os) const override {
      *os << "is an 'expected' type with an error which ";
      matcher_.DescribeTo(os);
    }

    void DescribeNegationTo(std::ostream* os) const override {
      *os << "is an 'expected' type with a value or an error which ";
      matcher_.DescribeNegationTo(os);
    }

    bool MatchAndExplain(
        U actual_value,
        ::testing::MatchResultListener* listener) const override {
      if (actual_value.has_value()) {
        if constexpr (HasVoidValueType<U>) {
          *listener << "which has a value";
        } else {
          *listener << "which has the value " << ToString(actual_value.value());
        }
        return false;
      }

      ::testing::StringMatchResultListener inner_listener;
      const bool match =
          matcher_.MatchAndExplain(actual_value.error(), &inner_listener);
      const std::string explanation = inner_listener.str();
      if (!explanation.empty()) {
        *listener << "which has the error " << ToString(actual_value.error())
                  << ", " << explanation;
      }
      return match;
    }

   private:
    using E = typename std::remove_cvref_t<U>::error_type;

    const ::testing::Matcher<const E&> matcher_;
  };

 private:
  const T matcher_;
};

}  // namespace internal

// Returns a gMock matcher that matches an `expected<T, E>` which has a value.
inline internal::HasValueMatcher HasValue() {
  return internal::HasValueMatcher();
}

// Returns a gMock matcher that matches an `expected<T, E>` which has a non-void
// value which matches the inner matcher.
template <typename T>
inline internal::ValueIsMatcher<typename std::decay_t<T>> ValueIs(T&& matcher) {
  return internal::ValueIsMatcher<typename std::decay_t<T>>(
      std::forward<T>(matcher));
}

// Returns a gMock matcher that matches an `expected<T, E>` which has an error
// which matches the inner matcher.
template <typename T>
inline internal::ErrorIsMatcher<typename std::decay_t<T>> ErrorIs(T&& matcher) {
  return internal::ErrorIsMatcher<typename std::decay_t<T>>(
      std::forward<T>(matcher));
}

}  // namespace base::test

// Executes an expression that returns an `expected<T, E>` or some subclass
// thereof, and assigns the contained `T` to `lhs` if the result is a value. If
// the result is an error, generates a test failure and returns from the current
// function, which must have a `void` return type. For more usage examples and
// caveats, see the documentation for `ASSIGN_OR_RETURN`.
//
// Example: Declaring and initializing a new value:
//   ASSERT_OK_AND_ASSIGN(ValueType value, MaybeGetValue(arg));
//
// Example: Assigning to an existing value:
//   ValueType value;
//   ASSERT_OK_AND_ASSIGN(value, MaybeGetValue(arg));
#define ASSERT_OK_AND_ASSIGN(lhs, rexpr)                               \
  ASSIGN_OR_RETURN(lhs, rexpr, [](const auto& e) {                     \
    return GTEST_MESSAGE_(                                             \
        base::StrCat({#rexpr, " returned error: ", base::ToString(e)}) \
            .c_str(),                                                  \
        ::testing::TestPartResult::kFatalFailure);                     \
  })

namespace base {
template <typename T, typename E>
void PrintTo(const expected<T, E>& expected, ::std::ostream* os) {
  *os << expected.ToString();
}

template <typename T>
void PrintTo(const ok<T>& a, ::std::ostream* os) {
  *os << a.ToString();
}

template <typename T>
void PrintTo(const unexpected<T>& a, ::std::ostream* os) {
  *os << a.ToString();
}
}  // namespace base

#endif  // BASE_TEST_GMOCK_EXPECTED_SUPPORT_H_