Path: blob/main/contrib/googletest/googlemock/test/gmock-matchers-misc_test.cc
110285 views
// Copyright 2007, Google Inc.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above10// copyright notice, this list of conditions and the following disclaimer11// in the documentation and/or other materials provided with the12// distribution.13// * Neither the name of Google Inc. nor the names of its14// contributors may be used to endorse or promote products derived from15// this software without specific prior written permission.16//17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2829// Google Mock - a framework for writing C++ mock classes.30//31// This file tests some commonly used argument matchers.3233#include <array>34#include <cstdint>35#include <memory>36#include <ostream>37#include <string>38#include <tuple>39#include <utility>40#include <vector>4142#include "gmock/gmock.h"43#include "test/gmock-matchers_test.h"44#include "gtest/gtest.h"4546// Silence warning C4244: 'initializing': conversion from 'int' to 'short',47// possible loss of data and C4100, unreferenced local parameter48GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)4950namespace testing {51namespace gmock_matchers_test {52namespace {5354TEST(AddressTest, NonConst) {55int n = 1;56const Matcher<int> m = Address(Eq(&n));5758EXPECT_TRUE(m.Matches(n));5960int other = 5;6162EXPECT_FALSE(m.Matches(other));6364int& n_ref = n;6566EXPECT_TRUE(m.Matches(n_ref));67}6869TEST(AddressTest, Const) {70const int n = 1;71const Matcher<int> m = Address(Eq(&n));7273EXPECT_TRUE(m.Matches(n));7475int other = 5;7677EXPECT_FALSE(m.Matches(other));78}7980TEST(AddressTest, MatcherDoesntCopy) {81std::unique_ptr<int> n(new int(1));82const Matcher<std::unique_ptr<int>> m = Address(Eq(&n));8384EXPECT_TRUE(m.Matches(n));85}8687TEST(AddressTest, Describe) {88Matcher<int> matcher = Address(_);89EXPECT_EQ("has address that is anything", Describe(matcher));90EXPECT_EQ("does not have address that is anything",91DescribeNegation(matcher));92}9394// The following two tests verify that values without a public copy95// ctor can be used as arguments to matchers like Eq(), Ge(), and etc96// with the help of ByRef().9798class NotCopyable {99public:100explicit NotCopyable(int a_value) : value_(a_value) {}101102int value() const { return value_; }103104bool operator==(const NotCopyable& rhs) const {105return value() == rhs.value();106}107108bool operator>=(const NotCopyable& rhs) const {109return value() >= rhs.value();110}111112private:113int value_;114115NotCopyable(const NotCopyable&) = delete;116NotCopyable& operator=(const NotCopyable&) = delete;117};118119TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {120const NotCopyable const_value1(1);121const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));122123const NotCopyable n1(1), n2(2);124EXPECT_TRUE(m.Matches(n1));125EXPECT_FALSE(m.Matches(n2));126}127128TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {129NotCopyable value2(2);130const Matcher<NotCopyable&> m = Ge(ByRef(value2));131132NotCopyable n1(1), n2(2);133EXPECT_FALSE(m.Matches(n1));134EXPECT_TRUE(m.Matches(n2));135}136137TEST(IsEmptyTest, ImplementsIsEmpty) {138vector<int> container;139EXPECT_THAT(container, IsEmpty());140container.push_back(0);141EXPECT_THAT(container, Not(IsEmpty()));142container.push_back(1);143EXPECT_THAT(container, Not(IsEmpty()));144}145146TEST(IsEmptyTest, WorksWithString) {147std::string text;148EXPECT_THAT(text, IsEmpty());149text = "foo";150EXPECT_THAT(text, Not(IsEmpty()));151text = std::string("\0", 1);152EXPECT_THAT(text, Not(IsEmpty()));153}154155TEST(IsEmptyTest, CanDescribeSelf) {156Matcher<vector<int>> m = IsEmpty();157EXPECT_EQ("is empty", Describe(m));158EXPECT_EQ("isn't empty", DescribeNegation(m));159}160161TEST(IsEmptyTest, ExplainsResult) {162Matcher<vector<int>> m = IsEmpty();163vector<int> container;164EXPECT_EQ("", Explain(m, container));165container.push_back(0);166EXPECT_EQ("whose size is 1", Explain(m, container));167}168169TEST(IsEmptyTest, WorksWithMoveOnly) {170ContainerHelper helper;171EXPECT_CALL(helper, Call(IsEmpty()));172helper.Call({});173}174175TEST(IsTrueTest, IsTrueIsFalse) {176EXPECT_THAT(true, IsTrue());177EXPECT_THAT(false, IsFalse());178EXPECT_THAT(true, Not(IsFalse()));179EXPECT_THAT(false, Not(IsTrue()));180EXPECT_THAT(0, Not(IsTrue()));181EXPECT_THAT(0, IsFalse());182EXPECT_THAT(nullptr, Not(IsTrue()));183EXPECT_THAT(nullptr, IsFalse());184EXPECT_THAT(-1, IsTrue());185EXPECT_THAT(-1, Not(IsFalse()));186EXPECT_THAT(1, IsTrue());187EXPECT_THAT(1, Not(IsFalse()));188EXPECT_THAT(2, IsTrue());189EXPECT_THAT(2, Not(IsFalse()));190int a = 42;191EXPECT_THAT(a, IsTrue());192EXPECT_THAT(a, Not(IsFalse()));193EXPECT_THAT(&a, IsTrue());194EXPECT_THAT(&a, Not(IsFalse()));195EXPECT_THAT(false, Not(IsTrue()));196EXPECT_THAT(true, Not(IsFalse()));197EXPECT_THAT(std::true_type(), IsTrue());198EXPECT_THAT(std::true_type(), Not(IsFalse()));199EXPECT_THAT(std::false_type(), IsFalse());200EXPECT_THAT(std::false_type(), Not(IsTrue()));201EXPECT_THAT(nullptr, Not(IsTrue()));202EXPECT_THAT(nullptr, IsFalse());203std::unique_ptr<int> null_unique;204std::unique_ptr<int> nonnull_unique(new int(0));205EXPECT_THAT(null_unique, Not(IsTrue()));206EXPECT_THAT(null_unique, IsFalse());207EXPECT_THAT(nonnull_unique, IsTrue());208EXPECT_THAT(nonnull_unique, Not(IsFalse()));209}210211#ifdef GTEST_HAS_TYPED_TEST212// Tests ContainerEq with different container types, and213// different element types.214215template <typename T>216class ContainerEqTest : public testing::Test {};217218typedef testing::Types<set<int>, vector<size_t>, multiset<size_t>, list<int>>219ContainerEqTestTypes;220221TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes);222223// Tests that the filled container is equal to itself.224TYPED_TEST(ContainerEqTest, EqualsSelf) {225static const int vals[] = {1, 1, 2, 3, 5, 8};226TypeParam my_set(vals, vals + 6);227const Matcher<TypeParam> m = ContainerEq(my_set);228EXPECT_TRUE(m.Matches(my_set));229EXPECT_EQ("", Explain(m, my_set));230}231232// Tests that missing values are reported.233TYPED_TEST(ContainerEqTest, ValueMissing) {234static const int vals[] = {1, 1, 2, 3, 5, 8};235static const int test_vals[] = {2, 1, 8, 5};236TypeParam my_set(vals, vals + 6);237TypeParam test_set(test_vals, test_vals + 4);238const Matcher<TypeParam> m = ContainerEq(my_set);239EXPECT_FALSE(m.Matches(test_set));240EXPECT_EQ("which doesn't have these expected elements: 3",241Explain(m, test_set));242}243244// Tests that added values are reported.245TYPED_TEST(ContainerEqTest, ValueAdded) {246static const int vals[] = {1, 1, 2, 3, 5, 8};247static const int test_vals[] = {1, 2, 3, 5, 8, 46};248TypeParam my_set(vals, vals + 6);249TypeParam test_set(test_vals, test_vals + 6);250const Matcher<const TypeParam&> m = ContainerEq(my_set);251EXPECT_FALSE(m.Matches(test_set));252EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));253}254255// Tests that added and missing values are reported together.256TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {257static const int vals[] = {1, 1, 2, 3, 5, 8};258static const int test_vals[] = {1, 2, 3, 8, 46};259TypeParam my_set(vals, vals + 6);260TypeParam test_set(test_vals, test_vals + 5);261const Matcher<TypeParam> m = ContainerEq(my_set);262EXPECT_FALSE(m.Matches(test_set));263EXPECT_EQ(264"which has these unexpected elements: 46,\n"265"and doesn't have these expected elements: 5",266Explain(m, test_set));267}268269// Tests duplicated value -- expect no explanation.270TYPED_TEST(ContainerEqTest, DuplicateDifference) {271static const int vals[] = {1, 1, 2, 3, 5, 8};272static const int test_vals[] = {1, 2, 3, 5, 8};273TypeParam my_set(vals, vals + 6);274TypeParam test_set(test_vals, test_vals + 5);275const Matcher<const TypeParam&> m = ContainerEq(my_set);276// Depending on the container, match may be true or false277// But in any case there should be no explanation.278EXPECT_EQ("", Explain(m, test_set));279}280#endif // GTEST_HAS_TYPED_TEST281282// Tests that multiple missing values are reported.283// Using just vector here, so order is predictable.284TEST(ContainerEqExtraTest, MultipleValuesMissing) {285static const int vals[] = {1, 1, 2, 3, 5, 8};286static const int test_vals[] = {2, 1, 5};287vector<int> my_set(vals, vals + 6);288vector<int> test_set(test_vals, test_vals + 3);289const Matcher<vector<int>> m = ContainerEq(my_set);290EXPECT_FALSE(m.Matches(test_set));291EXPECT_EQ("which doesn't have these expected elements: 3, 8",292Explain(m, test_set));293}294295// Tests that added values are reported.296// Using just vector here, so order is predictable.297TEST(ContainerEqExtraTest, MultipleValuesAdded) {298static const int vals[] = {1, 1, 2, 3, 5, 8};299static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};300list<size_t> my_set(vals, vals + 6);301list<size_t> test_set(test_vals, test_vals + 7);302const Matcher<const list<size_t>&> m = ContainerEq(my_set);303EXPECT_FALSE(m.Matches(test_set));304EXPECT_EQ("which has these unexpected elements: 92, 46",305Explain(m, test_set));306}307308// Tests that added and missing values are reported together.309TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {310static const int vals[] = {1, 1, 2, 3, 5, 8};311static const int test_vals[] = {1, 2, 3, 92, 46};312list<size_t> my_set(vals, vals + 6);313list<size_t> test_set(test_vals, test_vals + 5);314const Matcher<const list<size_t>> m = ContainerEq(my_set);315EXPECT_FALSE(m.Matches(test_set));316EXPECT_EQ(317"which has these unexpected elements: 92, 46,\n"318"and doesn't have these expected elements: 5, 8",319Explain(m, test_set));320}321322// Tests to see that duplicate elements are detected,323// but (as above) not reported in the explanation.324TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {325static const int vals[] = {1, 1, 2, 3, 5, 8};326static const int test_vals[] = {1, 2, 3, 5, 8};327vector<int> my_set(vals, vals + 6);328vector<int> test_set(test_vals, test_vals + 5);329const Matcher<vector<int>> m = ContainerEq(my_set);330EXPECT_TRUE(m.Matches(my_set));331EXPECT_FALSE(m.Matches(test_set));332// There is nothing to report when both sets contain all the same values.333EXPECT_EQ("", Explain(m, test_set));334}335336// Tests that ContainerEq works for non-trivial associative containers,337// like maps.338TEST(ContainerEqExtraTest, WorksForMaps) {339map<int, std::string> my_map;340my_map[0] = "a";341my_map[1] = "b";342343map<int, std::string> test_map;344test_map[0] = "aa";345test_map[1] = "b";346347const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);348EXPECT_TRUE(m.Matches(my_map));349EXPECT_FALSE(m.Matches(test_map));350351EXPECT_EQ(352"which has these unexpected elements: (0, \"aa\"),\n"353"and doesn't have these expected elements: (0, \"a\")",354Explain(m, test_map));355}356357TEST(ContainerEqExtraTest, WorksForNativeArray) {358int a1[] = {1, 2, 3};359int a2[] = {1, 2, 3};360int b[] = {1, 2, 4};361362EXPECT_THAT(a1, ContainerEq(a2));363EXPECT_THAT(a1, Not(ContainerEq(b)));364}365366TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {367const char a1[][3] = {"hi", "lo"};368const char a2[][3] = {"hi", "lo"};369const char b[][3] = {"lo", "hi"};370371// Tests using ContainerEq() in the first dimension.372EXPECT_THAT(a1, ContainerEq(a2));373EXPECT_THAT(a1, Not(ContainerEq(b)));374375// Tests using ContainerEq() in the second dimension.376EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));377EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));378}379380TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {381const int a1[] = {1, 2, 3};382const int a2[] = {1, 2, 3};383const int b[] = {1, 2, 3, 4};384385const int* const p1 = a1;386EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2));387EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b)));388389const int c[] = {1, 3, 2};390EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c)));391}392393TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {394std::string a1[][3] = {{"hi", "hello", "ciao"}, {"bye", "see you", "ciao"}};395396std::string a2[][3] = {{"hi", "hello", "ciao"}, {"bye", "see you", "ciao"}};397398const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);399EXPECT_THAT(a1, m);400401a2[0][0] = "ha";402EXPECT_THAT(a1, m);403}404405namespace {406407// Used as a check on the more complex max flow method used in the408// real testing::internal::FindMaxBipartiteMatching. This method is409// compatible but runs in worst-case factorial time, so we only410// use it in testing for small problem sizes.411template <typename Graph>412class BacktrackingMaxBPMState {413public:414// Does not take ownership of 'g'.415explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) {}416417ElementMatcherPairs Compute() {418if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {419return best_so_far_;420}421lhs_used_.assign(graph_->LhsSize(), kUnused);422rhs_used_.assign(graph_->RhsSize(), kUnused);423for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {424matches_.clear();425RecurseInto(irhs);426if (best_so_far_.size() == graph_->RhsSize()) break;427}428return best_so_far_;429}430431private:432static const size_t kUnused = static_cast<size_t>(-1);433434void PushMatch(size_t lhs, size_t rhs) {435matches_.push_back(ElementMatcherPair(lhs, rhs));436lhs_used_[lhs] = rhs;437rhs_used_[rhs] = lhs;438if (matches_.size() > best_so_far_.size()) {439best_so_far_ = matches_;440}441}442443void PopMatch() {444const ElementMatcherPair& back = matches_.back();445lhs_used_[back.first] = kUnused;446rhs_used_[back.second] = kUnused;447matches_.pop_back();448}449450bool RecurseInto(size_t irhs) {451if (rhs_used_[irhs] != kUnused) {452return true;453}454for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {455if (lhs_used_[ilhs] != kUnused) {456continue;457}458if (!graph_->HasEdge(ilhs, irhs)) {459continue;460}461PushMatch(ilhs, irhs);462if (best_so_far_.size() == graph_->RhsSize()) {463return false;464}465for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {466if (!RecurseInto(mi)) return false;467}468PopMatch();469}470return true;471}472473const Graph* graph_; // not owned474std::vector<size_t> lhs_used_;475std::vector<size_t> rhs_used_;476ElementMatcherPairs matches_;477ElementMatcherPairs best_so_far_;478};479480template <typename Graph>481const size_t BacktrackingMaxBPMState<Graph>::kUnused;482483} // namespace484485// Implement a simple backtracking algorithm to determine if it is possible486// to find one element per matcher, without reusing elements.487template <typename Graph>488ElementMatcherPairs FindBacktrackingMaxBPM(const Graph& g) {489return BacktrackingMaxBPMState<Graph>(&g).Compute();490}491492class BacktrackingBPMTest : public ::testing::Test {};493494// Tests the MaxBipartiteMatching algorithm with square matrices.495// The single int param is the # of nodes on each of the left and right sides.496class BipartiteTest : public ::testing::TestWithParam<size_t> {};497498// Verify all match graphs up to some moderate number of edges.499TEST_P(BipartiteTest, Exhaustive) {500size_t nodes = GetParam();501MatchMatrix graph(nodes, nodes);502do {503ElementMatcherPairs matches = internal::FindMaxBipartiteMatching(graph);504EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())505<< "graph: " << graph.DebugString();506// Check that all elements of matches are in the graph.507// Check that elements of first and second are unique.508std::vector<bool> seen_element(graph.LhsSize());509std::vector<bool> seen_matcher(graph.RhsSize());510SCOPED_TRACE(PrintToString(matches));511for (size_t i = 0; i < matches.size(); ++i) {512size_t ilhs = matches[i].first;513size_t irhs = matches[i].second;514EXPECT_TRUE(graph.HasEdge(ilhs, irhs));515EXPECT_FALSE(seen_element[ilhs]);516EXPECT_FALSE(seen_matcher[irhs]);517seen_element[ilhs] = true;518seen_matcher[irhs] = true;519}520} while (graph.NextGraph());521}522523INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest,524::testing::Range(size_t{0}, size_t{5}));525526// Parameterized by a pair interpreted as (LhsSize, RhsSize).527class BipartiteNonSquareTest528: public ::testing::TestWithParam<std::pair<size_t, size_t>> {};529530TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {531// .......532// 0:-----\ :533// 1:---\ | :534// 2:---\ | :535// 3:-\ | | :536// :.......:537// 0 1 2538MatchMatrix g(4, 3);539constexpr std::array<std::array<size_t, 2>, 4> kEdges = {540{{{0, 2}}, {{1, 1}}, {{2, 1}}, {{3, 0}}}};541for (size_t i = 0; i < kEdges.size(); ++i) {542g.SetEdge(kEdges[i][0], kEdges[i][1], true);543}544EXPECT_THAT(FindBacktrackingMaxBPM(g),545ElementsAre(Pair(3, 0), Pair(AnyOf(1, 2), 1), Pair(0, 2)))546<< g.DebugString();547}548549// Verify a few nonsquare matrices.550TEST_P(BipartiteNonSquareTest, Exhaustive) {551size_t nlhs = GetParam().first;552size_t nrhs = GetParam().second;553MatchMatrix graph(nlhs, nrhs);554do {555EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),556internal::FindMaxBipartiteMatching(graph).size())557<< "graph: " << graph.DebugString()558<< "\nbacktracking: " << PrintToString(FindBacktrackingMaxBPM(graph))559<< "\nmax flow: "560<< PrintToString(internal::FindMaxBipartiteMatching(graph));561} while (graph.NextGraph());562}563564INSTANTIATE_TEST_SUITE_P(565AllGraphs, BipartiteNonSquareTest,566testing::Values(std::make_pair(1, 2), std::make_pair(2, 1),567std::make_pair(3, 2), std::make_pair(2, 3),568std::make_pair(4, 1), std::make_pair(1, 4),569std::make_pair(4, 3), std::make_pair(3, 4)));570571class BipartiteRandomTest572: public ::testing::TestWithParam<std::pair<int, int>> {};573574// Verifies a large sample of larger graphs.575TEST_P(BipartiteRandomTest, LargerNets) {576int nodes = GetParam().first;577int iters = GetParam().second;578MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes));579580auto seed = static_cast<uint32_t>(GTEST_FLAG_GET(random_seed));581if (seed == 0) {582seed = static_cast<uint32_t>(time(nullptr));583}584585for (; iters > 0; --iters, ++seed) {586srand(static_cast<unsigned int>(seed));587graph.Randomize();588EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),589internal::FindMaxBipartiteMatching(graph).size())590<< " graph: " << graph.DebugString()591<< "\nTo reproduce the failure, rerun the test with the flag"592" --"593<< GTEST_FLAG_PREFIX_ << "random_seed=" << seed;594}595}596597// Test argument is a std::pair<int, int> representing (nodes, iters).598INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest,599testing::Values(std::make_pair(5, 10000),600std::make_pair(6, 5000),601std::make_pair(7, 2000),602std::make_pair(8, 500),603std::make_pair(9, 100)));604605// Tests IsReadableTypeName().606607TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {608EXPECT_TRUE(IsReadableTypeName("int"));609EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));610EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));611EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));612}613614TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {615EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));616EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));617EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));618}619620TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {621EXPECT_FALSE(622IsReadableTypeName("basic_string<char, std::char_traits<char> >"));623EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));624}625626TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {627EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));628}629630// Tests FormatMatcherDescription().631632TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {633EXPECT_EQ("is even",634FormatMatcherDescription(false, "IsEven", {}, Strings()));635EXPECT_EQ("not (is even)",636FormatMatcherDescription(true, "IsEven", {}, Strings()));637638EXPECT_EQ("equals (a: 5)",639FormatMatcherDescription(false, "Equals", {"a"}, {"5"}));640641EXPECT_EQ(642"is in range (a: 5, b: 8)",643FormatMatcherDescription(false, "IsInRange", {"a", "b"}, {"5", "8"}));644}645646INSTANTIATE_GTEST_MATCHER_TEST_P(MatcherTupleTest);647648TEST_P(MatcherTupleTestP, ExplainsMatchFailure) {649stringstream ss1;650ExplainMatchFailureTupleTo(651std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),652std::make_tuple('a', 10), &ss1);653EXPECT_EQ("", ss1.str()); // Successful match.654655stringstream ss2;656ExplainMatchFailureTupleTo(657std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),658std::make_tuple(2, 'b'), &ss2);659EXPECT_EQ(660" Expected arg #0: is > 5\n"661" Actual: 2, which is 3 less than 5\n"662" Expected arg #1: is equal to 'a' (97, 0x61)\n"663" Actual: 'b' (98, 0x62)\n",664ss2.str()); // Failed match where both arguments need explanation.665666stringstream ss3;667ExplainMatchFailureTupleTo(668std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),669std::make_tuple(2, 'a'), &ss3);670EXPECT_EQ(671" Expected arg #0: is > 5\n"672" Actual: 2, which is 3 less than 5\n",673ss3.str()); // Failed match where only one argument needs674// explanation.675}676677#if GTEST_HAS_TYPED_TEST678679// Sample optional type implementation with minimal requirements for use with680// Optional matcher.681template <typename T>682class SampleOptional {683public:684using value_type = T;685explicit SampleOptional(T value)686: value_(std::move(value)), has_value_(true) {}687SampleOptional() : value_(), has_value_(false) {}688operator bool() const { return has_value_; }689const T& operator*() const { return value_; }690691private:692T value_;693bool has_value_;694};695696// Sample optional type implementation with alternative minimal requirements for697// use with Optional matcher. In particular, while it doesn't have a bool698// conversion operator, it does have a has_value() method.699template <typename T>700class SampleOptionalWithoutBoolConversion {701public:702using value_type = T;703explicit SampleOptionalWithoutBoolConversion(T value)704: value_(std::move(value)), has_value_(true) {}705SampleOptionalWithoutBoolConversion() : value_(), has_value_(false) {}706bool has_value() const { return has_value_; }707const T& operator*() const { return value_; }708709private:710T value_;711bool has_value_;712};713714template <typename T>715class OptionalTest : public testing::Test {};716717using OptionalTestTypes =718testing::Types<SampleOptional<int>,719SampleOptionalWithoutBoolConversion<int>>;720721TYPED_TEST_SUITE(OptionalTest, OptionalTestTypes);722723TYPED_TEST(OptionalTest, DescribesSelf) {724const Matcher<TypeParam> m = Optional(Eq(1));725EXPECT_EQ("value is equal to 1", Describe(m));726}727728TYPED_TEST(OptionalTest, ExplainsSelf) {729const Matcher<TypeParam> m = Optional(Eq(1));730EXPECT_EQ("whose value 1 matches", Explain(m, TypeParam(1)));731EXPECT_EQ("whose value 2 doesn't match", Explain(m, TypeParam(2)));732}733734TYPED_TEST(OptionalTest, MatchesNonEmptyOptional) {735const Matcher<TypeParam> m1 = Optional(1);736const Matcher<TypeParam> m2 = Optional(Eq(2));737const Matcher<TypeParam> m3 = Optional(Lt(3));738TypeParam opt(1);739EXPECT_TRUE(m1.Matches(opt));740EXPECT_FALSE(m2.Matches(opt));741EXPECT_TRUE(m3.Matches(opt));742}743744TYPED_TEST(OptionalTest, DoesNotMatchNullopt) {745const Matcher<TypeParam> m = Optional(1);746TypeParam empty;747EXPECT_FALSE(m.Matches(empty));748}749750TYPED_TEST(OptionalTest, ComposesWithMonomorphicMatchersTakingReferences) {751const Matcher<const int&> eq1 = Eq(1);752const Matcher<const int&> eq2 = Eq(2);753TypeParam opt(1);754EXPECT_THAT(opt, Optional(eq1));755EXPECT_THAT(opt, Optional(Not(eq2)));756EXPECT_THAT(opt, Optional(AllOf(eq1, Not(eq2))));757}758759TYPED_TEST(OptionalTest, ComposesWithMonomorphicMatchersRequiringConversion) {760const Matcher<int64_t> eq1 = Eq(1);761const Matcher<int64_t> eq2 = Eq(2);762TypeParam opt(1);763EXPECT_THAT(opt, Optional(eq1));764EXPECT_THAT(opt, Optional(Not(eq2)));765EXPECT_THAT(opt, Optional(AllOf(eq1, Not(eq2))));766}767768template <typename T>769class MoveOnlyOptionalTest : public testing::Test {};770771using MoveOnlyOptionalTestTypes =772testing::Types<SampleOptional<std::unique_ptr<int>>,773SampleOptionalWithoutBoolConversion<std::unique_ptr<int>>>;774775TYPED_TEST_SUITE(MoveOnlyOptionalTest, MoveOnlyOptionalTestTypes);776777TYPED_TEST(MoveOnlyOptionalTest, WorksWithMoveOnly) {778Matcher<TypeParam> m = Optional(Eq(nullptr));779EXPECT_TRUE(m.Matches(TypeParam(nullptr)));780}781782#endif // GTEST_HAS_TYPED_TEST783784class SampleVariantIntString {785public:786SampleVariantIntString(int i) : i_(i), has_int_(true) {}787SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}788789template <typename T>790friend bool holds_alternative(const SampleVariantIntString& value) {791return value.has_int_ == std::is_same<T, int>::value;792}793794template <typename T>795friend const T& get(const SampleVariantIntString& value) {796return value.get_impl(static_cast<T*>(nullptr));797}798799private:800const int& get_impl(int*) const { return i_; }801const std::string& get_impl(std::string*) const { return s_; }802803int i_;804std::string s_;805bool has_int_;806};807808TEST(VariantTest, DescribesSelf) {809const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));810EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "811"'.*' and the value is equal to 1"));812}813814TEST(VariantTest, ExplainsSelf) {815const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));816EXPECT_THAT(Explain(m, SampleVariantIntString(1)),817ContainsRegex("whose value 1"));818EXPECT_THAT(Explain(m, SampleVariantIntString("A")),819HasSubstr("whose value is not of type '"));820EXPECT_THAT(Explain(m, SampleVariantIntString(2)),821"whose value 2 doesn't match");822}823824TEST(VariantTest, FullMatch) {825Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));826EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));827828m = VariantWith<std::string>(Eq("1"));829EXPECT_TRUE(m.Matches(SampleVariantIntString("1")));830}831832TEST(VariantTest, TypeDoesNotMatch) {833Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));834EXPECT_FALSE(m.Matches(SampleVariantIntString("1")));835836m = VariantWith<std::string>(Eq("1"));837EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));838}839840TEST(VariantTest, InnerDoesNotMatch) {841Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));842EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));843844m = VariantWith<std::string>(Eq("1"));845EXPECT_FALSE(m.Matches(SampleVariantIntString("2")));846}847848class SampleAnyType {849public:850explicit SampleAnyType(int i) : index_(0), i_(i) {}851explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}852853template <typename T>854friend const T* any_cast(const SampleAnyType* any) {855return any->get_impl(static_cast<T*>(nullptr));856}857858private:859int index_;860int i_;861std::string s_;862863const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; }864const std::string* get_impl(std::string*) const {865return index_ == 1 ? &s_ : nullptr;866}867};868869TEST(AnyWithTest, FullMatch) {870Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));871EXPECT_TRUE(m.Matches(SampleAnyType(1)));872}873874TEST(AnyWithTest, TestBadCastType) {875Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail"));876EXPECT_FALSE(m.Matches(SampleAnyType(1)));877}878879TEST(AnyWithTest, TestUseInContainers) {880std::vector<SampleAnyType> a;881a.emplace_back(1);882a.emplace_back(2);883a.emplace_back(3);884EXPECT_THAT(885a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)}));886887std::vector<SampleAnyType> b;888b.emplace_back("hello");889b.emplace_back("merhaba");890b.emplace_back("salut");891EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"),892AnyWith<std::string>("merhaba"),893AnyWith<std::string>("salut")}));894}895TEST(AnyWithTest, TestCompare) {896EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));897}898899TEST(AnyWithTest, DescribesSelf) {900const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));901EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type "902"'.*' and the value is equal to 1"));903}904905TEST(AnyWithTest, ExplainsSelf) {906const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));907908EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1"));909EXPECT_THAT(Explain(m, SampleAnyType("A")),910HasSubstr("whose value is not of type '"));911EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match");912}913914// Tests Args<k0, ..., kn>(m).915916TEST(ArgsTest, AcceptsZeroTemplateArg) {917const std::tuple<int, bool> t(5, true);918EXPECT_THAT(t, Args<>(Eq(std::tuple<>())));919EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>()))));920}921922TEST(ArgsTest, AcceptsOneTemplateArg) {923const std::tuple<int, bool> t(5, true);924EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5))));925EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true))));926EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false)))));927}928929TEST(ArgsTest, AcceptsTwoTemplateArgs) {930const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT931932EXPECT_THAT(t, (Args<0, 1>(Lt())));933EXPECT_THAT(t, (Args<1, 2>(Lt())));934EXPECT_THAT(t, Not(Args<0, 2>(Gt())));935}936937TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {938const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT939EXPECT_THAT(t, (Args<0, 0>(Eq())));940EXPECT_THAT(t, Not(Args<1, 1>(Ne())));941}942943TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {944const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT945EXPECT_THAT(t, (Args<2, 0>(Gt())));946EXPECT_THAT(t, Not(Args<2, 1>(Lt())));947}948949MATCHER(SumIsZero, "") {950return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0;951}952953TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {954EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));955EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));956}957958TEST(ArgsTest, CanBeNested) {959const std::tuple<short, int, long, int> t(short{4}, 5, 6L, 6); // NOLINT960EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));961EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));962}963964TEST(ArgsTest, CanMatchTupleByValue) {965typedef std::tuple<char, int, int> Tuple3;966const Matcher<Tuple3> m = Args<1, 2>(Lt());967EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));968EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));969}970971TEST(ArgsTest, CanMatchTupleByReference) {972typedef std::tuple<char, char, int> Tuple3;973const Matcher<const Tuple3&> m = Args<0, 1>(Lt());974EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));975EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));976}977978// Validates that arg is printed as str.979MATCHER_P(PrintsAs, str, "") { return testing::PrintToString(arg) == str; }980981TEST(ArgsTest, AcceptsTenTemplateArgs) {982EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),983(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(984PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));985EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),986Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(987PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));988}989990TEST(ArgsTest, DescirbesSelfCorrectly) {991const Matcher<std::tuple<int, bool, char>> m = Args<2, 0>(Lt());992EXPECT_EQ(993"are a tuple whose fields (#2, #0) are a pair where "994"the first < the second",995Describe(m));996}997998TEST(ArgsTest, DescirbesNestedArgsCorrectly) {999const Matcher<const std::tuple<int, bool, char, int>&> m =1000Args<0, 2, 3>(Args<2, 0>(Lt()));1001EXPECT_EQ(1002"are a tuple whose fields (#0, #2, #3) are a tuple "1003"whose fields (#2, #0) are a pair where the first < the second",1004Describe(m));1005}10061007TEST(ArgsTest, DescribesNegationCorrectly) {1008const Matcher<std::tuple<int, char>> m = Args<1, 0>(Gt());1009EXPECT_EQ(1010"are a tuple whose fields (#1, #0) aren't a pair "1011"where the first > the second",1012DescribeNegation(m));1013}10141015TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {1016const Matcher<std::tuple<bool, int, int>> m = Args<1, 2>(Eq());1017EXPECT_EQ("whose fields (#1, #2) are (42, 42)",1018Explain(m, std::make_tuple(false, 42, 42)));1019EXPECT_EQ("whose fields (#1, #2) are (42, 43)",1020Explain(m, std::make_tuple(false, 42, 43)));1021}10221023// For testing Args<>'s explanation.1024class LessThanMatcher : public MatcherInterface<std::tuple<char, int>> {1025public:1026void DescribeTo(::std::ostream* /*os*/) const override {}10271028bool MatchAndExplain(std::tuple<char, int> value,1029MatchResultListener* listener) const override {1030const int diff = std::get<0>(value) - std::get<1>(value);1031if (diff > 0) {1032*listener << "where the first value is " << diff1033<< " more than the second";1034}1035return diff < 0;1036}1037};10381039Matcher<std::tuple<char, int>> LessThan() {1040return MakeMatcher(new LessThanMatcher);1041}10421043TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {1044const Matcher<std::tuple<char, int, int>> m = Args<0, 2>(LessThan());1045EXPECT_EQ(1046"whose fields (#0, #2) are ('a' (97, 0x61), 42), "1047"where the first value is 55 more than the second",1048Explain(m, std::make_tuple('a', 42, 42)));1049EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",1050Explain(m, std::make_tuple('\0', 42, 43)));1051}10521053// Tests for the MATCHER*() macro family.10541055// Tests that a simple MATCHER() definition works.10561057MATCHER(IsEven, "") { return (arg % 2) == 0; }10581059TEST(MatcherMacroTest, Works) {1060const Matcher<int> m = IsEven();1061EXPECT_TRUE(m.Matches(6));1062EXPECT_FALSE(m.Matches(7));10631064EXPECT_EQ("is even", Describe(m));1065EXPECT_EQ("not (is even)", DescribeNegation(m));1066EXPECT_EQ("", Explain(m, 6));1067EXPECT_EQ("", Explain(m, 7));1068}10691070// This also tests that the description string can reference 'negation'.1071MATCHER(IsEven2, negation ? "is odd" : "is even") {1072if ((arg % 2) == 0) {1073// Verifies that we can stream to result_listener, a listener1074// supplied by the MATCHER macro implicitly.1075*result_listener << "OK";1076return true;1077} else {1078*result_listener << "% 2 == " << (arg % 2);1079return false;1080}1081}10821083// This also tests that the description string can reference matcher1084// parameters.1085MATCHER_P2(EqSumOf, x, y,1086std::string(negation ? "doesn't equal" : "equals") + " the sum of " +1087PrintToString(x) + " and " + PrintToString(y)) {1088if (arg == (x + y)) {1089*result_listener << "OK";1090return true;1091} else {1092// Verifies that we can stream to the underlying stream of1093// result_listener.1094if (result_listener->stream() != nullptr) {1095*result_listener->stream() << "diff == " << (x + y - arg);1096}1097return false;1098}1099}11001101// Tests that the matcher description can reference 'negation' and the1102// matcher parameters.1103TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {1104const Matcher<int> m1 = IsEven2();1105EXPECT_EQ("is even", Describe(m1));1106EXPECT_EQ("is odd", DescribeNegation(m1));11071108const Matcher<int> m2 = EqSumOf(5, 9);1109EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));1110EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));1111}11121113// Tests explaining match result in a MATCHER* macro.1114TEST(MatcherMacroTest, CanExplainMatchResult) {1115const Matcher<int> m1 = IsEven2();1116EXPECT_EQ("OK", Explain(m1, 4));1117EXPECT_EQ("% 2 == 1", Explain(m1, 5));11181119const Matcher<int> m2 = EqSumOf(1, 2);1120EXPECT_EQ("OK", Explain(m2, 3));1121EXPECT_EQ("diff == -1", Explain(m2, 4));1122}11231124// Tests that the body of MATCHER() can reference the type of the1125// value being matched.11261127MATCHER(IsEmptyString, "") {1128StaticAssertTypeEq<::std::string, arg_type>();1129return arg.empty();1130}11311132MATCHER(IsEmptyStringByRef, "") {1133StaticAssertTypeEq<const ::std::string&, arg_type>();1134return arg.empty();1135}11361137TEST(MatcherMacroTest, CanReferenceArgType) {1138const Matcher<::std::string> m1 = IsEmptyString();1139EXPECT_TRUE(m1.Matches(""));11401141const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();1142EXPECT_TRUE(m2.Matches(""));1143}11441145// Tests that MATCHER() can be used in a namespace.11461147namespace matcher_test {1148MATCHER(IsOdd, "") { return (arg % 2) != 0; }1149} // namespace matcher_test11501151TEST(MatcherMacroTest, WorksInNamespace) {1152Matcher<int> m = matcher_test::IsOdd();1153EXPECT_FALSE(m.Matches(4));1154EXPECT_TRUE(m.Matches(5));1155}11561157// Tests that Value() can be used to compose matchers.1158MATCHER(IsPositiveOdd, "") {1159return Value(arg, matcher_test::IsOdd()) && arg > 0;1160}11611162TEST(MatcherMacroTest, CanBeComposedUsingValue) {1163EXPECT_THAT(3, IsPositiveOdd());1164EXPECT_THAT(4, Not(IsPositiveOdd()));1165EXPECT_THAT(-1, Not(IsPositiveOdd()));1166}11671168// Tests that a simple MATCHER_P() definition works.11691170MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }11711172TEST(MatcherPMacroTest, Works) {1173const Matcher<int> m = IsGreaterThan32And(5);1174EXPECT_TRUE(m.Matches(36));1175EXPECT_FALSE(m.Matches(5));11761177EXPECT_EQ("is greater than 32 and (n: 5)", Describe(m));1178EXPECT_EQ("not (is greater than 32 and (n: 5))", DescribeNegation(m));1179EXPECT_EQ("", Explain(m, 36));1180EXPECT_EQ("", Explain(m, 5));1181}11821183// Tests that the description is calculated correctly from the matcher name.1184MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }11851186TEST(MatcherPMacroTest, GeneratesCorrectDescription) {1187const Matcher<int> m = _is_Greater_Than32and_(5);11881189EXPECT_EQ("is greater than 32 and (n: 5)", Describe(m));1190EXPECT_EQ("not (is greater than 32 and (n: 5))", DescribeNegation(m));1191EXPECT_EQ("", Explain(m, 36));1192EXPECT_EQ("", Explain(m, 5));1193}11941195// Tests that a MATCHER_P matcher can be explicitly instantiated with1196// a reference parameter type.11971198class UncopyableFoo {1199public:1200explicit UncopyableFoo(char value) : value_(value) { (void)value_; }12011202UncopyableFoo(const UncopyableFoo&) = delete;1203void operator=(const UncopyableFoo&) = delete;12041205private:1206char value_;1207};12081209MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }12101211TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {1212UncopyableFoo foo1('1'), foo2('2');1213const Matcher<const UncopyableFoo&> m =1214ReferencesUncopyable<const UncopyableFoo&>(foo1);12151216EXPECT_TRUE(m.Matches(foo1));1217EXPECT_FALSE(m.Matches(foo2));12181219// We don't want the address of the parameter printed, as most1220// likely it will just annoy the user. If the address is1221// interesting, the user should consider passing the parameter by1222// pointer instead.1223EXPECT_EQ("references uncopyable (variable: 1-byte object <31>)",1224Describe(m));1225}12261227// Tests that the body of MATCHER_Pn() can reference the parameter1228// types.12291230MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {1231StaticAssertTypeEq<int, foo_type>();1232StaticAssertTypeEq<long, bar_type>(); // NOLINT1233StaticAssertTypeEq<char, baz_type>();1234return arg == 0;1235}12361237TEST(MatcherPnMacroTest, CanReferenceParamTypes) {1238EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));1239}12401241// Tests that a MATCHER_Pn matcher can be explicitly instantiated with1242// reference parameter types.12431244MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {1245return &arg == &variable1 || &arg == &variable2;1246}12471248TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {1249UncopyableFoo foo1('1'), foo2('2'), foo3('3');1250const Matcher<const UncopyableFoo&> const_m =1251ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);12521253EXPECT_TRUE(const_m.Matches(foo1));1254EXPECT_TRUE(const_m.Matches(foo2));1255EXPECT_FALSE(const_m.Matches(foo3));12561257const Matcher<UncopyableFoo&> m =1258ReferencesAnyOf<UncopyableFoo&, UncopyableFoo&>(foo1, foo2);12591260EXPECT_TRUE(m.Matches(foo1));1261EXPECT_TRUE(m.Matches(foo2));1262EXPECT_FALSE(m.Matches(foo3));1263}12641265TEST(MatcherPnMacroTest,1266GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {1267UncopyableFoo foo1('1'), foo2('2');1268const Matcher<const UncopyableFoo&> m =1269ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);12701271// We don't want the addresses of the parameters printed, as most1272// likely they will just annoy the user. If the addresses are1273// interesting, the user should consider passing the parameters by1274// pointers instead.1275EXPECT_EQ(1276"references any of (variable1: 1-byte object <31>, variable2: 1-byte "1277"object <32>)",1278Describe(m));1279}12801281// Tests that a simple MATCHER_P2() definition works.12821283MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }12841285TEST(MatcherPnMacroTest, Works) {1286const Matcher<const long&> m = IsNotInClosedRange(10, 20); // NOLINT1287EXPECT_TRUE(m.Matches(36L));1288EXPECT_FALSE(m.Matches(15L));12891290EXPECT_EQ("is not in closed range (low: 10, hi: 20)", Describe(m));1291EXPECT_EQ("not (is not in closed range (low: 10, hi: 20))",1292DescribeNegation(m));1293EXPECT_EQ("", Explain(m, 36L));1294EXPECT_EQ("", Explain(m, 15L));1295}12961297// Tests that MATCHER*() definitions can be overloaded on the number1298// of parameters; also tests MATCHER_Pn() where n >= 3.12991300MATCHER(EqualsSumOf, "") { return arg == 0; }1301MATCHER_P(EqualsSumOf, a, "") { return arg == a; }1302MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }1303MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }1304MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }1305MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }1306MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {1307return arg == a + b + c + d + e + f;1308}1309MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {1310return arg == a + b + c + d + e + f + g;1311}1312MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {1313return arg == a + b + c + d + e + f + g + h;1314}1315MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {1316return arg == a + b + c + d + e + f + g + h + i;1317}1318MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {1319return arg == a + b + c + d + e + f + g + h + i + j;1320}13211322TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {1323EXPECT_THAT(0, EqualsSumOf());1324EXPECT_THAT(1, EqualsSumOf(1));1325EXPECT_THAT(12, EqualsSumOf(10, 2));1326EXPECT_THAT(123, EqualsSumOf(100, 20, 3));1327EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));1328EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));1329EXPECT_THAT("abcdef",1330EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));1331EXPECT_THAT("abcdefg",1332EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));1333EXPECT_THAT("abcdefgh", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",1334'f', 'g', "h"));1335EXPECT_THAT("abcdefghi", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",1336'f', 'g', "h", 'i'));1337EXPECT_THAT("abcdefghij",1338EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', "h",1339'i', ::std::string("j")));13401341EXPECT_THAT(1, Not(EqualsSumOf()));1342EXPECT_THAT(-1, Not(EqualsSumOf(1)));1343EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));1344EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));1345EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));1346EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));1347EXPECT_THAT("abcdef ",1348Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));1349EXPECT_THAT("abcdefg ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",1350"e", 'f', 'g')));1351EXPECT_THAT("abcdefgh ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",1352"e", 'f', 'g', "h")));1353EXPECT_THAT("abcdefghi ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",1354"e", 'f', 'g', "h", 'i')));1355EXPECT_THAT("abcdefghij ",1356Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',1357"h", 'i', ::std::string("j"))));1358}13591360// Tests that a MATCHER_Pn() definition can be instantiated with any1361// compatible parameter types.1362TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {1363EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));1364EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));13651366EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));1367EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));1368}13691370// Tests that the matcher body can promote the parameter types.13711372MATCHER_P2(EqConcat, prefix, suffix, "") {1373// The following lines promote the two parameters to desired types.1374std::string prefix_str(prefix);1375char suffix_char = static_cast<char>(suffix);1376return arg == prefix_str + suffix_char;1377}13781379TEST(MatcherPnMacroTest, SimpleTypePromotion) {1380Matcher<std::string> no_promo = EqConcat(std::string("foo"), 't');1381Matcher<const std::string&> promo = EqConcat("foo", static_cast<int>('t'));1382EXPECT_FALSE(no_promo.Matches("fool"));1383EXPECT_FALSE(promo.Matches("fool"));1384EXPECT_TRUE(no_promo.Matches("foot"));1385EXPECT_TRUE(promo.Matches("foot"));1386}13871388// Verifies the type of a MATCHER*.13891390TEST(MatcherPnMacroTest, TypesAreCorrect) {1391// EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.1392EqualsSumOfMatcher a0 = EqualsSumOf();13931394// EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.1395EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);13961397// EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk1398// variable, and so on.1399EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');1400EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');1401EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');1402EqualsSumOfMatcherP5<int, int, int, int, char> a5 =1403EqualsSumOf(1, 2, 3, 4, '5');1404EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =1405EqualsSumOf(1, 2, 3, 4, 5, '6');1406EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =1407EqualsSumOf(1, 2, 3, 4, 5, 6, '7');1408EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =1409EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');1410EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =1411EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');1412EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =1413EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');14141415// Avoid "unused variable" warnings.1416(void)a0;1417(void)a1;1418(void)a2;1419(void)a3;1420(void)a4;1421(void)a5;1422(void)a6;1423(void)a7;1424(void)a8;1425(void)a9;1426(void)a10;1427}14281429// Tests that matcher-typed parameters can be used in Value() inside a1430// MATCHER_Pn definition.14311432// Succeeds if arg matches exactly 2 of the 3 matchers.1433MATCHER_P3(TwoOf, m1, m2, m3, "") {1434const int count = static_cast<int>(Value(arg, m1)) +1435static_cast<int>(Value(arg, m2)) +1436static_cast<int>(Value(arg, m3));1437return count == 2;1438}14391440TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {1441EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));1442EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));1443}14441445// Tests Contains().Times().14461447INSTANTIATE_GTEST_MATCHER_TEST_P(ContainsTimes);14481449TEST(ContainsTimes, ListMatchesWhenElementQuantityMatches) {1450list<int> some_list;1451some_list.push_back(3);1452some_list.push_back(1);1453some_list.push_back(2);1454some_list.push_back(3);1455EXPECT_THAT(some_list, Contains(3).Times(2));1456EXPECT_THAT(some_list, Contains(2).Times(1));1457EXPECT_THAT(some_list, Contains(Ge(2)).Times(3));1458EXPECT_THAT(some_list, Contains(Ge(2)).Times(Gt(2)));1459EXPECT_THAT(some_list, Contains(4).Times(0));1460EXPECT_THAT(some_list, Contains(_).Times(4));1461EXPECT_THAT(some_list, Not(Contains(5).Times(1)));1462EXPECT_THAT(some_list, Contains(5).Times(_)); // Times(_) always matches1463EXPECT_THAT(some_list, Not(Contains(3).Times(1)));1464EXPECT_THAT(some_list, Contains(3).Times(Not(1)));1465EXPECT_THAT(list<int>{}, Not(Contains(_)));1466}14671468TEST_P(ContainsTimesP, ExplainsMatchResultCorrectly) {1469const int a[2] = {1, 2};1470Matcher<const int(&)[2]> m = Contains(2).Times(3);1471EXPECT_EQ(1472"whose element #1 matches but whose match quantity of 1 does not match",1473Explain(m, a));14741475m = Contains(3).Times(0);1476EXPECT_EQ("has no element that matches and whose match quantity of 0 matches",1477Explain(m, a));14781479m = Contains(3).Times(4);1480EXPECT_EQ(1481"has no element that matches and whose match quantity of 0 does not "1482"match",1483Explain(m, a));14841485m = Contains(2).Times(4);1486EXPECT_EQ(1487"whose element #1 matches but whose match quantity of 1 does not "1488"match",1489Explain(m, a));14901491m = Contains(GreaterThan(0)).Times(2);1492EXPECT_EQ("whose elements (0, 1) match and whose match quantity of 2 matches",1493Explain(m, a));14941495m = Contains(GreaterThan(10)).Times(Gt(1));1496EXPECT_EQ(1497"has no element that matches and whose match quantity of 0 does not "1498"match",1499Explain(m, a));15001501m = Contains(GreaterThan(0)).Times(GreaterThan<size_t>(5));1502EXPECT_EQ(1503"whose elements (0, 1) match but whose match quantity of 2 does not "1504"match, which is 3 less than 5",1505Explain(m, a));1506}15071508TEST(ContainsTimes, DescribesItselfCorrectly) {1509Matcher<vector<int>> m = Contains(1).Times(2);1510EXPECT_EQ("quantity of elements that match is equal to 1 is equal to 2",1511Describe(m));15121513Matcher<vector<int>> m2 = Not(m);1514EXPECT_EQ("quantity of elements that match is equal to 1 isn't equal to 2",1515Describe(m2));1516}15171518// Tests AllOfArray()15191520TEST(AllOfArrayTest, BasicForms) {1521// Iterator1522std::vector<int> v0{};1523std::vector<int> v1{1};1524std::vector<int> v2{2, 3};1525std::vector<int> v3{4, 4, 4};1526EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end()));1527EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end()));1528EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));1529EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));1530EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end()));1531// Pointer + size1532int ar[6] = {1, 2, 3, 4, 4, 4};1533EXPECT_THAT(0, AllOfArray(ar, 0));1534EXPECT_THAT(1, AllOfArray(ar, 1));1535EXPECT_THAT(2, Not(AllOfArray(ar, 1)));1536EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3)));1537EXPECT_THAT(4, AllOfArray(ar + 3, 3));1538// Array1539// int ar0[0]; Not usable1540int ar1[1] = {1};1541int ar2[2] = {2, 3};1542int ar3[3] = {4, 4, 4};1543// EXPECT_THAT(0, Not(AllOfArray(ar0))); // Cannot work1544EXPECT_THAT(1, AllOfArray(ar1));1545EXPECT_THAT(2, Not(AllOfArray(ar1)));1546EXPECT_THAT(3, Not(AllOfArray(ar2)));1547EXPECT_THAT(4, AllOfArray(ar3));1548// Container1549EXPECT_THAT(0, AllOfArray(v0));1550EXPECT_THAT(1, AllOfArray(v1));1551EXPECT_THAT(2, Not(AllOfArray(v1)));1552EXPECT_THAT(3, Not(AllOfArray(v2)));1553EXPECT_THAT(4, AllOfArray(v3));1554// Initializer1555EXPECT_THAT(0, AllOfArray<int>({})); // Requires template arg.1556EXPECT_THAT(1, AllOfArray({1}));1557EXPECT_THAT(2, Not(AllOfArray({1})));1558EXPECT_THAT(3, Not(AllOfArray({2, 3})));1559EXPECT_THAT(4, AllOfArray({4, 4, 4}));1560}15611562TEST(AllOfArrayTest, Matchers) {1563// vector1564std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};1565EXPECT_THAT(0, Not(AllOfArray(matchers)));1566EXPECT_THAT(1, AllOfArray(matchers));1567EXPECT_THAT(2, Not(AllOfArray(matchers)));1568// initializer_list1569EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)})));1570EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)}));1571}15721573INSTANTIATE_GTEST_MATCHER_TEST_P(AnyOfArrayTest);15741575TEST(AnyOfArrayTest, BasicForms) {1576// Iterator1577std::vector<int> v0{};1578std::vector<int> v1{1};1579std::vector<int> v2{2, 3};1580EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end())));1581EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end()));1582EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));1583EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end()));1584EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));1585// Pointer + size1586int ar[3] = {1, 2, 3};1587EXPECT_THAT(0, Not(AnyOfArray(ar, 0)));1588EXPECT_THAT(1, AnyOfArray(ar, 1));1589EXPECT_THAT(2, Not(AnyOfArray(ar, 1)));1590EXPECT_THAT(3, AnyOfArray(ar + 1, 2));1591EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2)));1592// Array1593// int ar0[0]; Not usable1594int ar1[1] = {1};1595int ar2[2] = {2, 3};1596// EXPECT_THAT(0, Not(AnyOfArray(ar0))); // Cannot work1597EXPECT_THAT(1, AnyOfArray(ar1));1598EXPECT_THAT(2, Not(AnyOfArray(ar1)));1599EXPECT_THAT(3, AnyOfArray(ar2));1600EXPECT_THAT(4, Not(AnyOfArray(ar2)));1601// Container1602EXPECT_THAT(0, Not(AnyOfArray(v0)));1603EXPECT_THAT(1, AnyOfArray(v1));1604EXPECT_THAT(2, Not(AnyOfArray(v1)));1605EXPECT_THAT(3, AnyOfArray(v2));1606EXPECT_THAT(4, Not(AnyOfArray(v2)));1607// Initializer1608EXPECT_THAT(0, Not(AnyOfArray<int>({}))); // Requires template arg.1609EXPECT_THAT(1, AnyOfArray({1}));1610EXPECT_THAT(2, Not(AnyOfArray({1})));1611EXPECT_THAT(3, AnyOfArray({2, 3}));1612EXPECT_THAT(4, Not(AnyOfArray({2, 3})));1613}16141615TEST(AnyOfArrayTest, Matchers) {1616// We negate test AllOfArrayTest.Matchers.1617// vector1618std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};1619EXPECT_THAT(0, AnyOfArray(matchers));1620EXPECT_THAT(1, Not(AnyOfArray(matchers)));1621EXPECT_THAT(2, AnyOfArray(matchers));1622// initializer_list1623EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)}));1624EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)})));1625}16261627TEST_P(AnyOfArrayTestP, ExplainsMatchResultCorrectly) {1628// AnyOfArray and AllOfArray use the same underlying template-template,1629// thus it is sufficient to test one here.1630const std::vector<int> v0{};1631const std::vector<int> v1{1};1632const std::vector<int> v2{2, 3};1633const Matcher<int> m0 = AnyOfArray(v0);1634const Matcher<int> m1 = AnyOfArray(v1);1635const Matcher<int> m2 = AnyOfArray(v2);1636EXPECT_EQ("", Explain(m0, 0));1637EXPECT_EQ("which matches (is equal to 1)", Explain(m1, 1));1638EXPECT_EQ("isn't equal to 1", Explain(m1, 2));1639EXPECT_EQ("which matches (is equal to 3)", Explain(m2, 3));1640EXPECT_EQ("isn't equal to 2, and isn't equal to 3", Explain(m2, 4));1641EXPECT_EQ("()", Describe(m0));1642EXPECT_EQ("(is equal to 1)", Describe(m1));1643EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));1644EXPECT_EQ("()", DescribeNegation(m0));1645EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1));1646EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2));1647// Explain with matchers1648const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});1649const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});1650// Explains the first positive match and all prior negative matches...1651EXPECT_EQ("which is 1 less than 1", Explain(g1, 0));1652EXPECT_EQ("which is the same as 1", Explain(g1, 1));1653EXPECT_EQ("which is 1 more than 1", Explain(g1, 2));1654EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2",1655Explain(g2, 0));1656EXPECT_EQ("which is the same as 1, and which is 1 less than 2",1657Explain(g2, 1));1658EXPECT_EQ("which is 1 more than 1", // Only the first1659Explain(g2, 2));1660}16611662MATCHER(IsNotNull, "") { return arg != nullptr; }16631664// Verifies that a matcher defined using MATCHER() can work on1665// move-only types.1666TEST(MatcherMacroTest, WorksOnMoveOnlyType) {1667std::unique_ptr<int> p(new int(3));1668EXPECT_THAT(p, IsNotNull());1669EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));1670}16711672MATCHER_P(UniquePointee, pointee, "") { return *arg == pointee; }16731674// Verifies that a matcher defined using MATCHER_P*() can work on1675// move-only types.1676TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {1677std::unique_ptr<int> p(new int(3));1678EXPECT_THAT(p, UniquePointee(3));1679EXPECT_THAT(p, Not(UniquePointee(2)));1680}16811682MATCHER(EnsureNoUnusedButMarkedUnusedWarning, "") { return (arg % 2) == 0; }16831684TEST(MockMethodMockFunctionTest, EnsureNoUnusedButMarkedUnusedWarning) {1685#ifdef __clang__1686#pragma clang diagnostic push1687#pragma clang diagnostic error "-Wused-but-marked-unused"1688#endif1689// https://github.com/google/googletest/issues/40551690EXPECT_THAT(0, EnsureNoUnusedButMarkedUnusedWarning());1691#ifdef __clang__1692#pragma clang diagnostic pop1693#endif1694}16951696#if GTEST_HAS_EXCEPTIONS16971698// std::function<void()> is used below for compatibility with older copies of1699// GCC. Normally, a raw lambda is all that is needed.17001701// Test that examples from documentation compile1702TEST(ThrowsTest, Examples) {1703EXPECT_THAT(1704std::function<void()>([]() { throw std::runtime_error("message"); }),1705Throws<std::runtime_error>());17061707EXPECT_THAT(1708std::function<void()>([]() { throw std::runtime_error("message"); }),1709ThrowsMessage<std::runtime_error>(HasSubstr("message")));1710}17111712TEST(ThrowsTest, PrintsExceptionWhat) {1713EXPECT_THAT(1714std::function<void()>([]() { throw std::runtime_error("ABC123XYZ"); }),1715ThrowsMessage<std::runtime_error>(HasSubstr("ABC123XYZ")));1716}17171718TEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) {1719EXPECT_THAT(std::function<void()>([]() { throw std::exception(); }),1720Throws<std::exception>());1721}17221723TEST(ThrowsTest, CallableExecutedExactlyOnce) {1724size_t a = 0;17251726EXPECT_THAT(std::function<void()>([&a]() {1727a++;1728throw 10;1729}),1730Throws<int>());1731EXPECT_EQ(a, 1u);17321733EXPECT_THAT(std::function<void()>([&a]() {1734a++;1735throw std::runtime_error("message");1736}),1737Throws<std::runtime_error>());1738EXPECT_EQ(a, 2u);17391740EXPECT_THAT(std::function<void()>([&a]() {1741a++;1742throw std::runtime_error("message");1743}),1744ThrowsMessage<std::runtime_error>(HasSubstr("message")));1745EXPECT_EQ(a, 3u);17461747EXPECT_THAT(std::function<void()>([&a]() {1748a++;1749throw std::runtime_error("message");1750}),1751Throws<std::runtime_error>(1752Property(&std::runtime_error::what, HasSubstr("message"))));1753EXPECT_EQ(a, 4u);1754}17551756TEST(ThrowsTest, Describe) {1757Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();1758std::stringstream ss;1759matcher.DescribeTo(&ss);1760auto explanation = ss.str();1761EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));1762}17631764TEST(ThrowsTest, Success) {1765Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();1766StringMatchResultListener listener;1767EXPECT_TRUE(matcher.MatchAndExplain(1768[]() { throw std::runtime_error("error message"); }, &listener));1769EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));1770}17711772TEST(ThrowsTest, FailWrongType) {1773Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();1774StringMatchResultListener listener;1775EXPECT_FALSE(matcher.MatchAndExplain(1776[]() { throw std::logic_error("error message"); }, &listener));1777EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));1778EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));1779}17801781TEST(ThrowsTest, FailWrongTypeNonStd) {1782Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();1783StringMatchResultListener listener;1784EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));1785EXPECT_THAT(listener.str(),1786HasSubstr("throws an exception of an unknown type"));1787}17881789TEST(ThrowsTest, FailNoThrow) {1790Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();1791StringMatchResultListener listener;1792EXPECT_FALSE(matcher.MatchAndExplain([]() { (void)0; }, &listener));1793EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));1794}17951796class ThrowsPredicateTest1797: public TestWithParam<Matcher<std::function<void()>>> {};17981799TEST_P(ThrowsPredicateTest, Describe) {1800Matcher<std::function<void()>> matcher = GetParam();1801std::stringstream ss;1802matcher.DescribeTo(&ss);1803auto explanation = ss.str();1804EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));1805EXPECT_THAT(explanation, HasSubstr("error message"));1806}18071808TEST_P(ThrowsPredicateTest, Success) {1809Matcher<std::function<void()>> matcher = GetParam();1810StringMatchResultListener listener;1811EXPECT_TRUE(matcher.MatchAndExplain(1812[]() { throw std::runtime_error("error message"); }, &listener));1813EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));1814}18151816TEST_P(ThrowsPredicateTest, FailWrongType) {1817Matcher<std::function<void()>> matcher = GetParam();1818StringMatchResultListener listener;1819EXPECT_FALSE(matcher.MatchAndExplain(1820[]() { throw std::logic_error("error message"); }, &listener));1821EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));1822EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));1823}18241825TEST_P(ThrowsPredicateTest, FailWrongTypeNonStd) {1826Matcher<std::function<void()>> matcher = GetParam();1827StringMatchResultListener listener;1828EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));1829EXPECT_THAT(listener.str(),1830HasSubstr("throws an exception of an unknown type"));1831}18321833TEST_P(ThrowsPredicateTest, FailNoThrow) {1834Matcher<std::function<void()>> matcher = GetParam();1835StringMatchResultListener listener;1836EXPECT_FALSE(matcher.MatchAndExplain([]() {}, &listener));1837EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));1838}18391840INSTANTIATE_TEST_SUITE_P(1841AllMessagePredicates, ThrowsPredicateTest,1842Values(Matcher<std::function<void()>>(1843ThrowsMessage<std::runtime_error>(HasSubstr("error message")))));18441845// Tests that Throws<E1>(Matcher<E2>{}) compiles even when E2 != const E1&.1846TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) {1847{1848Matcher<std::function<void()>> matcher =1849ThrowsMessage<std::runtime_error>(HasSubstr("error message"));1850EXPECT_TRUE(1851matcher.Matches([]() { throw std::runtime_error("error message"); }));1852EXPECT_FALSE(1853matcher.Matches([]() { throw std::runtime_error("wrong message"); }));1854}18551856{1857Matcher<uint64_t> inner = Eq(10);1858Matcher<std::function<void()>> matcher = Throws<uint32_t>(inner);1859EXPECT_TRUE(matcher.Matches([]() { throw (uint32_t)10; }));1860EXPECT_FALSE(matcher.Matches([]() { throw (uint32_t)11; }));1861}1862}18631864// Tests that ThrowsMessage("message") is equivalent1865// to ThrowsMessage(Eq<std::string>("message")).1866TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {1867Matcher<std::function<void()>> matcher =1868ThrowsMessage<std::runtime_error>("error message");1869EXPECT_TRUE(1870matcher.Matches([]() { throw std::runtime_error("error message"); }));1871EXPECT_FALSE(matcher.Matches(1872[]() { throw std::runtime_error("wrong error message"); }));1873}18741875#endif // GTEST_HAS_EXCEPTIONS18761877} // namespace1878} // namespace gmock_matchers_test1879} // namespace testing18801881GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100188218831884