Path: blob/main/contrib/googletest/googlemock/test/gmock-matchers-misc_test.cc
48255 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 <memory>35#include <ostream>36#include <string>37#include <tuple>38#include <utility>39#include <vector>4041#include "gtest/gtest.h"4243// Silence warning C4244: 'initializing': conversion from 'int' to 'short',44// possible loss of data and C4100, unreferenced local parameter45GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)4647#include "test/gmock-matchers_test.h"4849namespace testing {50namespace gmock_matchers_test {51namespace {5253TEST(AddressTest, NonConst) {54int n = 1;55const Matcher<int> m = Address(Eq(&n));5657EXPECT_TRUE(m.Matches(n));5859int other = 5;6061EXPECT_FALSE(m.Matches(other));6263int& n_ref = n;6465EXPECT_TRUE(m.Matches(n_ref));66}6768TEST(AddressTest, Const) {69const int n = 1;70const Matcher<int> m = Address(Eq(&n));7172EXPECT_TRUE(m.Matches(n));7374int other = 5;7576EXPECT_FALSE(m.Matches(other));77}7879TEST(AddressTest, MatcherDoesntCopy) {80std::unique_ptr<int> n(new int(1));81const Matcher<std::unique_ptr<int>> m = Address(Eq(&n));8283EXPECT_TRUE(m.Matches(n));84}8586TEST(AddressTest, Describe) {87Matcher<int> matcher = Address(_);88EXPECT_EQ("has address that is anything", Describe(matcher));89EXPECT_EQ("does not have address that is anything",90DescribeNegation(matcher));91}9293// The following two tests verify that values without a public copy94// ctor can be used as arguments to matchers like Eq(), Ge(), and etc95// with the help of ByRef().9697class NotCopyable {98public:99explicit NotCopyable(int a_value) : value_(a_value) {}100101int value() const { return value_; }102103bool operator==(const NotCopyable& rhs) const {104return value() == rhs.value();105}106107bool operator>=(const NotCopyable& rhs) const {108return value() >= rhs.value();109}110111private:112int value_;113114NotCopyable(const NotCopyable&) = delete;115NotCopyable& operator=(const NotCopyable&) = delete;116};117118TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {119const NotCopyable const_value1(1);120const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));121122const NotCopyable n1(1), n2(2);123EXPECT_TRUE(m.Matches(n1));124EXPECT_FALSE(m.Matches(n2));125}126127TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {128NotCopyable value2(2);129const Matcher<NotCopyable&> m = Ge(ByRef(value2));130131NotCopyable n1(1), n2(2);132EXPECT_FALSE(m.Matches(n1));133EXPECT_TRUE(m.Matches(n2));134}135136TEST(IsEmptyTest, ImplementsIsEmpty) {137vector<int> container;138EXPECT_THAT(container, IsEmpty());139container.push_back(0);140EXPECT_THAT(container, Not(IsEmpty()));141container.push_back(1);142EXPECT_THAT(container, Not(IsEmpty()));143}144145TEST(IsEmptyTest, WorksWithString) {146std::string text;147EXPECT_THAT(text, IsEmpty());148text = "foo";149EXPECT_THAT(text, Not(IsEmpty()));150text = std::string("\0", 1);151EXPECT_THAT(text, Not(IsEmpty()));152}153154TEST(IsEmptyTest, CanDescribeSelf) {155Matcher<vector<int>> m = IsEmpty();156EXPECT_EQ("is empty", Describe(m));157EXPECT_EQ("isn't empty", DescribeNegation(m));158}159160TEST(IsEmptyTest, ExplainsResult) {161Matcher<vector<int>> m = IsEmpty();162vector<int> container;163EXPECT_EQ("", Explain(m, container));164container.push_back(0);165EXPECT_EQ("whose size is 1", Explain(m, container));166}167168TEST(IsEmptyTest, WorksWithMoveOnly) {169ContainerHelper helper;170EXPECT_CALL(helper, Call(IsEmpty()));171helper.Call({});172}173174TEST(IsTrueTest, IsTrueIsFalse) {175EXPECT_THAT(true, IsTrue());176EXPECT_THAT(false, IsFalse());177EXPECT_THAT(true, Not(IsFalse()));178EXPECT_THAT(false, Not(IsTrue()));179EXPECT_THAT(0, Not(IsTrue()));180EXPECT_THAT(0, IsFalse());181EXPECT_THAT(nullptr, Not(IsTrue()));182EXPECT_THAT(nullptr, IsFalse());183EXPECT_THAT(-1, IsTrue());184EXPECT_THAT(-1, Not(IsFalse()));185EXPECT_THAT(1, IsTrue());186EXPECT_THAT(1, Not(IsFalse()));187EXPECT_THAT(2, IsTrue());188EXPECT_THAT(2, Not(IsFalse()));189int a = 42;190EXPECT_THAT(a, IsTrue());191EXPECT_THAT(a, Not(IsFalse()));192EXPECT_THAT(&a, IsTrue());193EXPECT_THAT(&a, Not(IsFalse()));194EXPECT_THAT(false, Not(IsTrue()));195EXPECT_THAT(true, Not(IsFalse()));196EXPECT_THAT(std::true_type(), IsTrue());197EXPECT_THAT(std::true_type(), Not(IsFalse()));198EXPECT_THAT(std::false_type(), IsFalse());199EXPECT_THAT(std::false_type(), Not(IsTrue()));200EXPECT_THAT(nullptr, Not(IsTrue()));201EXPECT_THAT(nullptr, IsFalse());202std::unique_ptr<int> null_unique;203std::unique_ptr<int> nonnull_unique(new int(0));204EXPECT_THAT(null_unique, Not(IsTrue()));205EXPECT_THAT(null_unique, IsFalse());206EXPECT_THAT(nonnull_unique, IsTrue());207EXPECT_THAT(nonnull_unique, Not(IsFalse()));208}209210#ifdef GTEST_HAS_TYPED_TEST211// Tests ContainerEq with different container types, and212// different element types.213214template <typename T>215class ContainerEqTest : public testing::Test {};216217typedef testing::Types<set<int>, vector<size_t>, multiset<size_t>, list<int>>218ContainerEqTestTypes;219220TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes);221222// Tests that the filled container is equal to itself.223TYPED_TEST(ContainerEqTest, EqualsSelf) {224static const int vals[] = {1, 1, 2, 3, 5, 8};225TypeParam my_set(vals, vals + 6);226const Matcher<TypeParam> m = ContainerEq(my_set);227EXPECT_TRUE(m.Matches(my_set));228EXPECT_EQ("", Explain(m, my_set));229}230231// Tests that missing values are reported.232TYPED_TEST(ContainerEqTest, ValueMissing) {233static const int vals[] = {1, 1, 2, 3, 5, 8};234static const int test_vals[] = {2, 1, 8, 5};235TypeParam my_set(vals, vals + 6);236TypeParam test_set(test_vals, test_vals + 4);237const Matcher<TypeParam> m = ContainerEq(my_set);238EXPECT_FALSE(m.Matches(test_set));239EXPECT_EQ("which doesn't have these expected elements: 3",240Explain(m, test_set));241}242243// Tests that added values are reported.244TYPED_TEST(ContainerEqTest, ValueAdded) {245static const int vals[] = {1, 1, 2, 3, 5, 8};246static const int test_vals[] = {1, 2, 3, 5, 8, 46};247TypeParam my_set(vals, vals + 6);248TypeParam test_set(test_vals, test_vals + 6);249const Matcher<const TypeParam&> m = ContainerEq(my_set);250EXPECT_FALSE(m.Matches(test_set));251EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));252}253254// Tests that added and missing values are reported together.255TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {256static const int vals[] = {1, 1, 2, 3, 5, 8};257static const int test_vals[] = {1, 2, 3, 8, 46};258TypeParam my_set(vals, vals + 6);259TypeParam test_set(test_vals, test_vals + 5);260const Matcher<TypeParam> m = ContainerEq(my_set);261EXPECT_FALSE(m.Matches(test_set));262EXPECT_EQ(263"which has these unexpected elements: 46,\n"264"and doesn't have these expected elements: 5",265Explain(m, test_set));266}267268// Tests duplicated value -- expect no explanation.269TYPED_TEST(ContainerEqTest, DuplicateDifference) {270static const int vals[] = {1, 1, 2, 3, 5, 8};271static const int test_vals[] = {1, 2, 3, 5, 8};272TypeParam my_set(vals, vals + 6);273TypeParam test_set(test_vals, test_vals + 5);274const Matcher<const TypeParam&> m = ContainerEq(my_set);275// Depending on the container, match may be true or false276// But in any case there should be no explanation.277EXPECT_EQ("", Explain(m, test_set));278}279#endif // GTEST_HAS_TYPED_TEST280281// Tests that multiple missing values are reported.282// Using just vector here, so order is predictable.283TEST(ContainerEqExtraTest, MultipleValuesMissing) {284static const int vals[] = {1, 1, 2, 3, 5, 8};285static const int test_vals[] = {2, 1, 5};286vector<int> my_set(vals, vals + 6);287vector<int> test_set(test_vals, test_vals + 3);288const Matcher<vector<int>> m = ContainerEq(my_set);289EXPECT_FALSE(m.Matches(test_set));290EXPECT_EQ("which doesn't have these expected elements: 3, 8",291Explain(m, test_set));292}293294// Tests that added values are reported.295// Using just vector here, so order is predictable.296TEST(ContainerEqExtraTest, MultipleValuesAdded) {297static const int vals[] = {1, 1, 2, 3, 5, 8};298static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};299list<size_t> my_set(vals, vals + 6);300list<size_t> test_set(test_vals, test_vals + 7);301const Matcher<const list<size_t>&> m = ContainerEq(my_set);302EXPECT_FALSE(m.Matches(test_set));303EXPECT_EQ("which has these unexpected elements: 92, 46",304Explain(m, test_set));305}306307// Tests that added and missing values are reported together.308TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {309static const int vals[] = {1, 1, 2, 3, 5, 8};310static const int test_vals[] = {1, 2, 3, 92, 46};311list<size_t> my_set(vals, vals + 6);312list<size_t> test_set(test_vals, test_vals + 5);313const Matcher<const list<size_t>> m = ContainerEq(my_set);314EXPECT_FALSE(m.Matches(test_set));315EXPECT_EQ(316"which has these unexpected elements: 92, 46,\n"317"and doesn't have these expected elements: 5, 8",318Explain(m, test_set));319}320321// Tests to see that duplicate elements are detected,322// but (as above) not reported in the explanation.323TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {324static const int vals[] = {1, 1, 2, 3, 5, 8};325static const int test_vals[] = {1, 2, 3, 5, 8};326vector<int> my_set(vals, vals + 6);327vector<int> test_set(test_vals, test_vals + 5);328const Matcher<vector<int>> m = ContainerEq(my_set);329EXPECT_TRUE(m.Matches(my_set));330EXPECT_FALSE(m.Matches(test_set));331// There is nothing to report when both sets contain all the same values.332EXPECT_EQ("", Explain(m, test_set));333}334335// Tests that ContainerEq works for non-trivial associative containers,336// like maps.337TEST(ContainerEqExtraTest, WorksForMaps) {338map<int, std::string> my_map;339my_map[0] = "a";340my_map[1] = "b";341342map<int, std::string> test_map;343test_map[0] = "aa";344test_map[1] = "b";345346const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);347EXPECT_TRUE(m.Matches(my_map));348EXPECT_FALSE(m.Matches(test_map));349350EXPECT_EQ(351"which has these unexpected elements: (0, \"aa\"),\n"352"and doesn't have these expected elements: (0, \"a\")",353Explain(m, test_map));354}355356TEST(ContainerEqExtraTest, WorksForNativeArray) {357int a1[] = {1, 2, 3};358int a2[] = {1, 2, 3};359int b[] = {1, 2, 4};360361EXPECT_THAT(a1, ContainerEq(a2));362EXPECT_THAT(a1, Not(ContainerEq(b)));363}364365TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {366const char a1[][3] = {"hi", "lo"};367const char a2[][3] = {"hi", "lo"};368const char b[][3] = {"lo", "hi"};369370// Tests using ContainerEq() in the first dimension.371EXPECT_THAT(a1, ContainerEq(a2));372EXPECT_THAT(a1, Not(ContainerEq(b)));373374// Tests using ContainerEq() in the second dimension.375EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));376EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));377}378379TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {380const int a1[] = {1, 2, 3};381const int a2[] = {1, 2, 3};382const int b[] = {1, 2, 3, 4};383384const int* const p1 = a1;385EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2));386EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b)));387388const int c[] = {1, 3, 2};389EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c)));390}391392TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {393std::string a1[][3] = {{"hi", "hello", "ciao"}, {"bye", "see you", "ciao"}};394395std::string a2[][3] = {{"hi", "hello", "ciao"}, {"bye", "see you", "ciao"}};396397const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);398EXPECT_THAT(a1, m);399400a2[0][0] = "ha";401EXPECT_THAT(a1, m);402}403404namespace {405406// Used as a check on the more complex max flow method used in the407// real testing::internal::FindMaxBipartiteMatching. This method is408// compatible but runs in worst-case factorial time, so we only409// use it in testing for small problem sizes.410template <typename Graph>411class BacktrackingMaxBPMState {412public:413// Does not take ownership of 'g'.414explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) {}415416ElementMatcherPairs Compute() {417if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {418return best_so_far_;419}420lhs_used_.assign(graph_->LhsSize(), kUnused);421rhs_used_.assign(graph_->RhsSize(), kUnused);422for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {423matches_.clear();424RecurseInto(irhs);425if (best_so_far_.size() == graph_->RhsSize()) break;426}427return best_so_far_;428}429430private:431static const size_t kUnused = static_cast<size_t>(-1);432433void PushMatch(size_t lhs, size_t rhs) {434matches_.push_back(ElementMatcherPair(lhs, rhs));435lhs_used_[lhs] = rhs;436rhs_used_[rhs] = lhs;437if (matches_.size() > best_so_far_.size()) {438best_so_far_ = matches_;439}440}441442void PopMatch() {443const ElementMatcherPair& back = matches_.back();444lhs_used_[back.first] = kUnused;445rhs_used_[back.second] = kUnused;446matches_.pop_back();447}448449bool RecurseInto(size_t irhs) {450if (rhs_used_[irhs] != kUnused) {451return true;452}453for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {454if (lhs_used_[ilhs] != kUnused) {455continue;456}457if (!graph_->HasEdge(ilhs, irhs)) {458continue;459}460PushMatch(ilhs, irhs);461if (best_so_far_.size() == graph_->RhsSize()) {462return false;463}464for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {465if (!RecurseInto(mi)) return false;466}467PopMatch();468}469return true;470}471472const Graph* graph_; // not owned473std::vector<size_t> lhs_used_;474std::vector<size_t> rhs_used_;475ElementMatcherPairs matches_;476ElementMatcherPairs best_so_far_;477};478479template <typename Graph>480const size_t BacktrackingMaxBPMState<Graph>::kUnused;481482} // namespace483484// Implement a simple backtracking algorithm to determine if it is possible485// to find one element per matcher, without reusing elements.486template <typename Graph>487ElementMatcherPairs FindBacktrackingMaxBPM(const Graph& g) {488return BacktrackingMaxBPMState<Graph>(&g).Compute();489}490491class BacktrackingBPMTest : public ::testing::Test {};492493// Tests the MaxBipartiteMatching algorithm with square matrices.494// The single int param is the # of nodes on each of the left and right sides.495class BipartiteTest : public ::testing::TestWithParam<size_t> {};496497// Verify all match graphs up to some moderate number of edges.498TEST_P(BipartiteTest, Exhaustive) {499size_t nodes = GetParam();500MatchMatrix graph(nodes, nodes);501do {502ElementMatcherPairs matches = internal::FindMaxBipartiteMatching(graph);503EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())504<< "graph: " << graph.DebugString();505// Check that all elements of matches are in the graph.506// Check that elements of first and second are unique.507std::vector<bool> seen_element(graph.LhsSize());508std::vector<bool> seen_matcher(graph.RhsSize());509SCOPED_TRACE(PrintToString(matches));510for (size_t i = 0; i < matches.size(); ++i) {511size_t ilhs = matches[i].first;512size_t irhs = matches[i].second;513EXPECT_TRUE(graph.HasEdge(ilhs, irhs));514EXPECT_FALSE(seen_element[ilhs]);515EXPECT_FALSE(seen_matcher[irhs]);516seen_element[ilhs] = true;517seen_matcher[irhs] = true;518}519} while (graph.NextGraph());520}521522INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest,523::testing::Range(size_t{0}, size_t{5}));524525// Parameterized by a pair interpreted as (LhsSize, RhsSize).526class BipartiteNonSquareTest527: public ::testing::TestWithParam<std::pair<size_t, size_t>> {};528529TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {530// .......531// 0:-----\ :532// 1:---\ | :533// 2:---\ | :534// 3:-\ | | :535// :.......:536// 0 1 2537MatchMatrix g(4, 3);538constexpr std::array<std::array<size_t, 2>, 4> kEdges = {539{{{0, 2}}, {{1, 1}}, {{2, 1}}, {{3, 0}}}};540for (size_t i = 0; i < kEdges.size(); ++i) {541g.SetEdge(kEdges[i][0], kEdges[i][1], true);542}543EXPECT_THAT(FindBacktrackingMaxBPM(g),544ElementsAre(Pair(3, 0), Pair(AnyOf(1, 2), 1), Pair(0, 2)))545<< g.DebugString();546}547548// Verify a few nonsquare matrices.549TEST_P(BipartiteNonSquareTest, Exhaustive) {550size_t nlhs = GetParam().first;551size_t nrhs = GetParam().second;552MatchMatrix graph(nlhs, nrhs);553do {554EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),555internal::FindMaxBipartiteMatching(graph).size())556<< "graph: " << graph.DebugString()557<< "\nbacktracking: " << PrintToString(FindBacktrackingMaxBPM(graph))558<< "\nmax flow: "559<< PrintToString(internal::FindMaxBipartiteMatching(graph));560} while (graph.NextGraph());561}562563INSTANTIATE_TEST_SUITE_P(564AllGraphs, BipartiteNonSquareTest,565testing::Values(std::make_pair(1, 2), std::make_pair(2, 1),566std::make_pair(3, 2), std::make_pair(2, 3),567std::make_pair(4, 1), std::make_pair(1, 4),568std::make_pair(4, 3), std::make_pair(3, 4)));569570class BipartiteRandomTest571: public ::testing::TestWithParam<std::pair<int, int>> {};572573// Verifies a large sample of larger graphs.574TEST_P(BipartiteRandomTest, LargerNets) {575int nodes = GetParam().first;576int iters = GetParam().second;577MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes));578579auto seed = static_cast<uint32_t>(GTEST_FLAG_GET(random_seed));580if (seed == 0) {581seed = static_cast<uint32_t>(time(nullptr));582}583584for (; iters > 0; --iters, ++seed) {585srand(static_cast<unsigned int>(seed));586graph.Randomize();587EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),588internal::FindMaxBipartiteMatching(graph).size())589<< " graph: " << graph.DebugString()590<< "\nTo reproduce the failure, rerun the test with the flag"591" --"592<< GTEST_FLAG_PREFIX_ << "random_seed=" << seed;593}594}595596// Test argument is a std::pair<int, int> representing (nodes, iters).597INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest,598testing::Values(std::make_pair(5, 10000),599std::make_pair(6, 5000),600std::make_pair(7, 2000),601std::make_pair(8, 500),602std::make_pair(9, 100)));603604// Tests IsReadableTypeName().605606TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {607EXPECT_TRUE(IsReadableTypeName("int"));608EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));609EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));610EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));611}612613TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {614EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));615EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));616EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));617}618619TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {620EXPECT_FALSE(621IsReadableTypeName("basic_string<char, std::char_traits<char> >"));622EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));623}624625TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {626EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));627}628629// Tests FormatMatcherDescription().630631TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {632EXPECT_EQ("is even",633FormatMatcherDescription(false, "IsEven", {}, Strings()));634EXPECT_EQ("not (is even)",635FormatMatcherDescription(true, "IsEven", {}, Strings()));636637EXPECT_EQ("equals (a: 5)",638FormatMatcherDescription(false, "Equals", {"a"}, {"5"}));639640EXPECT_EQ(641"is in range (a: 5, b: 8)",642FormatMatcherDescription(false, "IsInRange", {"a", "b"}, {"5", "8"}));643}644645INSTANTIATE_GTEST_MATCHER_TEST_P(MatcherTupleTest);646647TEST_P(MatcherTupleTestP, ExplainsMatchFailure) {648stringstream ss1;649ExplainMatchFailureTupleTo(650std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),651std::make_tuple('a', 10), &ss1);652EXPECT_EQ("", ss1.str()); // Successful match.653654stringstream ss2;655ExplainMatchFailureTupleTo(656std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),657std::make_tuple(2, 'b'), &ss2);658EXPECT_EQ(659" Expected arg #0: is > 5\n"660" Actual: 2, which is 3 less than 5\n"661" Expected arg #1: is equal to 'a' (97, 0x61)\n"662" Actual: 'b' (98, 0x62)\n",663ss2.str()); // Failed match where both arguments need explanation.664665stringstream ss3;666ExplainMatchFailureTupleTo(667std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),668std::make_tuple(2, 'a'), &ss3);669EXPECT_EQ(670" Expected arg #0: is > 5\n"671" Actual: 2, which is 3 less than 5\n",672ss3.str()); // Failed match where only one argument needs673// explanation.674}675676// Sample optional type implementation with minimal requirements for use with677// Optional matcher.678template <typename T>679class SampleOptional {680public:681using value_type = T;682explicit SampleOptional(T value)683: value_(std::move(value)), has_value_(true) {}684SampleOptional() : value_(), has_value_(false) {}685operator bool() const { return has_value_; }686const T& operator*() const { return value_; }687688private:689T value_;690bool has_value_;691};692693TEST(OptionalTest, DescribesSelf) {694const Matcher<SampleOptional<int>> m = Optional(Eq(1));695EXPECT_EQ("value is equal to 1", Describe(m));696}697698TEST(OptionalTest, ExplainsSelf) {699const Matcher<SampleOptional<int>> m = Optional(Eq(1));700EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional<int>(1)));701EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional<int>(2)));702}703704TEST(OptionalTest, MatchesNonEmptyOptional) {705const Matcher<SampleOptional<int>> m1 = Optional(1);706const Matcher<SampleOptional<int>> m2 = Optional(Eq(2));707const Matcher<SampleOptional<int>> m3 = Optional(Lt(3));708SampleOptional<int> opt(1);709EXPECT_TRUE(m1.Matches(opt));710EXPECT_FALSE(m2.Matches(opt));711EXPECT_TRUE(m3.Matches(opt));712}713714TEST(OptionalTest, DoesNotMatchNullopt) {715const Matcher<SampleOptional<int>> m = Optional(1);716SampleOptional<int> empty;717EXPECT_FALSE(m.Matches(empty));718}719720TEST(OptionalTest, WorksWithMoveOnly) {721Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr));722EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr)));723}724725class SampleVariantIntString {726public:727SampleVariantIntString(int i) : i_(i), has_int_(true) {}728SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}729730template <typename T>731friend bool holds_alternative(const SampleVariantIntString& value) {732return value.has_int_ == std::is_same<T, int>::value;733}734735template <typename T>736friend const T& get(const SampleVariantIntString& value) {737return value.get_impl(static_cast<T*>(nullptr));738}739740private:741const int& get_impl(int*) const { return i_; }742const std::string& get_impl(std::string*) const { return s_; }743744int i_;745std::string s_;746bool has_int_;747};748749TEST(VariantTest, DescribesSelf) {750const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));751EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "752"'.*' and the value is equal to 1"));753}754755TEST(VariantTest, ExplainsSelf) {756const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));757EXPECT_THAT(Explain(m, SampleVariantIntString(1)),758ContainsRegex("whose value 1"));759EXPECT_THAT(Explain(m, SampleVariantIntString("A")),760HasSubstr("whose value is not of type '"));761EXPECT_THAT(Explain(m, SampleVariantIntString(2)),762"whose value 2 doesn't match");763}764765TEST(VariantTest, FullMatch) {766Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));767EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));768769m = VariantWith<std::string>(Eq("1"));770EXPECT_TRUE(m.Matches(SampleVariantIntString("1")));771}772773TEST(VariantTest, TypeDoesNotMatch) {774Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));775EXPECT_FALSE(m.Matches(SampleVariantIntString("1")));776777m = VariantWith<std::string>(Eq("1"));778EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));779}780781TEST(VariantTest, InnerDoesNotMatch) {782Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));783EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));784785m = VariantWith<std::string>(Eq("1"));786EXPECT_FALSE(m.Matches(SampleVariantIntString("2")));787}788789class SampleAnyType {790public:791explicit SampleAnyType(int i) : index_(0), i_(i) {}792explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}793794template <typename T>795friend const T* any_cast(const SampleAnyType* any) {796return any->get_impl(static_cast<T*>(nullptr));797}798799private:800int index_;801int i_;802std::string s_;803804const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; }805const std::string* get_impl(std::string*) const {806return index_ == 1 ? &s_ : nullptr;807}808};809810TEST(AnyWithTest, FullMatch) {811Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));812EXPECT_TRUE(m.Matches(SampleAnyType(1)));813}814815TEST(AnyWithTest, TestBadCastType) {816Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail"));817EXPECT_FALSE(m.Matches(SampleAnyType(1)));818}819820TEST(AnyWithTest, TestUseInContainers) {821std::vector<SampleAnyType> a;822a.emplace_back(1);823a.emplace_back(2);824a.emplace_back(3);825EXPECT_THAT(826a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)}));827828std::vector<SampleAnyType> b;829b.emplace_back("hello");830b.emplace_back("merhaba");831b.emplace_back("salut");832EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"),833AnyWith<std::string>("merhaba"),834AnyWith<std::string>("salut")}));835}836TEST(AnyWithTest, TestCompare) {837EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));838}839840TEST(AnyWithTest, DescribesSelf) {841const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));842EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type "843"'.*' and the value is equal to 1"));844}845846TEST(AnyWithTest, ExplainsSelf) {847const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));848849EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1"));850EXPECT_THAT(Explain(m, SampleAnyType("A")),851HasSubstr("whose value is not of type '"));852EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match");853}854855// Tests Args<k0, ..., kn>(m).856857TEST(ArgsTest, AcceptsZeroTemplateArg) {858const std::tuple<int, bool> t(5, true);859EXPECT_THAT(t, Args<>(Eq(std::tuple<>())));860EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>()))));861}862863TEST(ArgsTest, AcceptsOneTemplateArg) {864const std::tuple<int, bool> t(5, true);865EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5))));866EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true))));867EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false)))));868}869870TEST(ArgsTest, AcceptsTwoTemplateArgs) {871const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT872873EXPECT_THAT(t, (Args<0, 1>(Lt())));874EXPECT_THAT(t, (Args<1, 2>(Lt())));875EXPECT_THAT(t, Not(Args<0, 2>(Gt())));876}877878TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {879const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT880EXPECT_THAT(t, (Args<0, 0>(Eq())));881EXPECT_THAT(t, Not(Args<1, 1>(Ne())));882}883884TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {885const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT886EXPECT_THAT(t, (Args<2, 0>(Gt())));887EXPECT_THAT(t, Not(Args<2, 1>(Lt())));888}889890MATCHER(SumIsZero, "") {891return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0;892}893894TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {895EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));896EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));897}898899TEST(ArgsTest, CanBeNested) {900const std::tuple<short, int, long, int> t(short{4}, 5, 6L, 6); // NOLINT901EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));902EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));903}904905TEST(ArgsTest, CanMatchTupleByValue) {906typedef std::tuple<char, int, int> Tuple3;907const Matcher<Tuple3> m = Args<1, 2>(Lt());908EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));909EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));910}911912TEST(ArgsTest, CanMatchTupleByReference) {913typedef std::tuple<char, char, int> Tuple3;914const Matcher<const Tuple3&> m = Args<0, 1>(Lt());915EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));916EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));917}918919// Validates that arg is printed as str.920MATCHER_P(PrintsAs, str, "") { return testing::PrintToString(arg) == str; }921922TEST(ArgsTest, AcceptsTenTemplateArgs) {923EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),924(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(925PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));926EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),927Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(928PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));929}930931TEST(ArgsTest, DescirbesSelfCorrectly) {932const Matcher<std::tuple<int, bool, char>> m = Args<2, 0>(Lt());933EXPECT_EQ(934"are a tuple whose fields (#2, #0) are a pair where "935"the first < the second",936Describe(m));937}938939TEST(ArgsTest, DescirbesNestedArgsCorrectly) {940const Matcher<const std::tuple<int, bool, char, int>&> m =941Args<0, 2, 3>(Args<2, 0>(Lt()));942EXPECT_EQ(943"are a tuple whose fields (#0, #2, #3) are a tuple "944"whose fields (#2, #0) are a pair where the first < the second",945Describe(m));946}947948TEST(ArgsTest, DescribesNegationCorrectly) {949const Matcher<std::tuple<int, char>> m = Args<1, 0>(Gt());950EXPECT_EQ(951"are a tuple whose fields (#1, #0) aren't a pair "952"where the first > the second",953DescribeNegation(m));954}955956TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {957const Matcher<std::tuple<bool, int, int>> m = Args<1, 2>(Eq());958EXPECT_EQ("whose fields (#1, #2) are (42, 42)",959Explain(m, std::make_tuple(false, 42, 42)));960EXPECT_EQ("whose fields (#1, #2) are (42, 43)",961Explain(m, std::make_tuple(false, 42, 43)));962}963964// For testing Args<>'s explanation.965class LessThanMatcher : public MatcherInterface<std::tuple<char, int>> {966public:967void DescribeTo(::std::ostream* /*os*/) const override {}968969bool MatchAndExplain(std::tuple<char, int> value,970MatchResultListener* listener) const override {971const int diff = std::get<0>(value) - std::get<1>(value);972if (diff > 0) {973*listener << "where the first value is " << diff974<< " more than the second";975}976return diff < 0;977}978};979980Matcher<std::tuple<char, int>> LessThan() {981return MakeMatcher(new LessThanMatcher);982}983984TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {985const Matcher<std::tuple<char, int, int>> m = Args<0, 2>(LessThan());986EXPECT_EQ(987"whose fields (#0, #2) are ('a' (97, 0x61), 42), "988"where the first value is 55 more than the second",989Explain(m, std::make_tuple('a', 42, 42)));990EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",991Explain(m, std::make_tuple('\0', 42, 43)));992}993994// Tests for the MATCHER*() macro family.995996// Tests that a simple MATCHER() definition works.997998MATCHER(IsEven, "") { return (arg % 2) == 0; }9991000TEST(MatcherMacroTest, Works) {1001const Matcher<int> m = IsEven();1002EXPECT_TRUE(m.Matches(6));1003EXPECT_FALSE(m.Matches(7));10041005EXPECT_EQ("is even", Describe(m));1006EXPECT_EQ("not (is even)", DescribeNegation(m));1007EXPECT_EQ("", Explain(m, 6));1008EXPECT_EQ("", Explain(m, 7));1009}10101011// This also tests that the description string can reference 'negation'.1012MATCHER(IsEven2, negation ? "is odd" : "is even") {1013if ((arg % 2) == 0) {1014// Verifies that we can stream to result_listener, a listener1015// supplied by the MATCHER macro implicitly.1016*result_listener << "OK";1017return true;1018} else {1019*result_listener << "% 2 == " << (arg % 2);1020return false;1021}1022}10231024// This also tests that the description string can reference matcher1025// parameters.1026MATCHER_P2(EqSumOf, x, y,1027std::string(negation ? "doesn't equal" : "equals") + " the sum of " +1028PrintToString(x) + " and " + PrintToString(y)) {1029if (arg == (x + y)) {1030*result_listener << "OK";1031return true;1032} else {1033// Verifies that we can stream to the underlying stream of1034// result_listener.1035if (result_listener->stream() != nullptr) {1036*result_listener->stream() << "diff == " << (x + y - arg);1037}1038return false;1039}1040}10411042// Tests that the matcher description can reference 'negation' and the1043// matcher parameters.1044TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {1045const Matcher<int> m1 = IsEven2();1046EXPECT_EQ("is even", Describe(m1));1047EXPECT_EQ("is odd", DescribeNegation(m1));10481049const Matcher<int> m2 = EqSumOf(5, 9);1050EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));1051EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));1052}10531054// Tests explaining match result in a MATCHER* macro.1055TEST(MatcherMacroTest, CanExplainMatchResult) {1056const Matcher<int> m1 = IsEven2();1057EXPECT_EQ("OK", Explain(m1, 4));1058EXPECT_EQ("% 2 == 1", Explain(m1, 5));10591060const Matcher<int> m2 = EqSumOf(1, 2);1061EXPECT_EQ("OK", Explain(m2, 3));1062EXPECT_EQ("diff == -1", Explain(m2, 4));1063}10641065// Tests that the body of MATCHER() can reference the type of the1066// value being matched.10671068MATCHER(IsEmptyString, "") {1069StaticAssertTypeEq<::std::string, arg_type>();1070return arg.empty();1071}10721073MATCHER(IsEmptyStringByRef, "") {1074StaticAssertTypeEq<const ::std::string&, arg_type>();1075return arg.empty();1076}10771078TEST(MatcherMacroTest, CanReferenceArgType) {1079const Matcher<::std::string> m1 = IsEmptyString();1080EXPECT_TRUE(m1.Matches(""));10811082const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();1083EXPECT_TRUE(m2.Matches(""));1084}10851086// Tests that MATCHER() can be used in a namespace.10871088namespace matcher_test {1089MATCHER(IsOdd, "") { return (arg % 2) != 0; }1090} // namespace matcher_test10911092TEST(MatcherMacroTest, WorksInNamespace) {1093Matcher<int> m = matcher_test::IsOdd();1094EXPECT_FALSE(m.Matches(4));1095EXPECT_TRUE(m.Matches(5));1096}10971098// Tests that Value() can be used to compose matchers.1099MATCHER(IsPositiveOdd, "") {1100return Value(arg, matcher_test::IsOdd()) && arg > 0;1101}11021103TEST(MatcherMacroTest, CanBeComposedUsingValue) {1104EXPECT_THAT(3, IsPositiveOdd());1105EXPECT_THAT(4, Not(IsPositiveOdd()));1106EXPECT_THAT(-1, Not(IsPositiveOdd()));1107}11081109// Tests that a simple MATCHER_P() definition works.11101111MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }11121113TEST(MatcherPMacroTest, Works) {1114const Matcher<int> m = IsGreaterThan32And(5);1115EXPECT_TRUE(m.Matches(36));1116EXPECT_FALSE(m.Matches(5));11171118EXPECT_EQ("is greater than 32 and (n: 5)", Describe(m));1119EXPECT_EQ("not (is greater than 32 and (n: 5))", DescribeNegation(m));1120EXPECT_EQ("", Explain(m, 36));1121EXPECT_EQ("", Explain(m, 5));1122}11231124// Tests that the description is calculated correctly from the matcher name.1125MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }11261127TEST(MatcherPMacroTest, GeneratesCorrectDescription) {1128const Matcher<int> m = _is_Greater_Than32and_(5);11291130EXPECT_EQ("is greater than 32 and (n: 5)", Describe(m));1131EXPECT_EQ("not (is greater than 32 and (n: 5))", DescribeNegation(m));1132EXPECT_EQ("", Explain(m, 36));1133EXPECT_EQ("", Explain(m, 5));1134}11351136// Tests that a MATCHER_P matcher can be explicitly instantiated with1137// a reference parameter type.11381139class UncopyableFoo {1140public:1141explicit UncopyableFoo(char value) : value_(value) { (void)value_; }11421143UncopyableFoo(const UncopyableFoo&) = delete;1144void operator=(const UncopyableFoo&) = delete;11451146private:1147char value_;1148};11491150MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }11511152TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {1153UncopyableFoo foo1('1'), foo2('2');1154const Matcher<const UncopyableFoo&> m =1155ReferencesUncopyable<const UncopyableFoo&>(foo1);11561157EXPECT_TRUE(m.Matches(foo1));1158EXPECT_FALSE(m.Matches(foo2));11591160// We don't want the address of the parameter printed, as most1161// likely it will just annoy the user. If the address is1162// interesting, the user should consider passing the parameter by1163// pointer instead.1164EXPECT_EQ("references uncopyable (variable: 1-byte object <31>)",1165Describe(m));1166}11671168// Tests that the body of MATCHER_Pn() can reference the parameter1169// types.11701171MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {1172StaticAssertTypeEq<int, foo_type>();1173StaticAssertTypeEq<long, bar_type>(); // NOLINT1174StaticAssertTypeEq<char, baz_type>();1175return arg == 0;1176}11771178TEST(MatcherPnMacroTest, CanReferenceParamTypes) {1179EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));1180}11811182// Tests that a MATCHER_Pn matcher can be explicitly instantiated with1183// reference parameter types.11841185MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {1186return &arg == &variable1 || &arg == &variable2;1187}11881189TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {1190UncopyableFoo foo1('1'), foo2('2'), foo3('3');1191const Matcher<const UncopyableFoo&> const_m =1192ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);11931194EXPECT_TRUE(const_m.Matches(foo1));1195EXPECT_TRUE(const_m.Matches(foo2));1196EXPECT_FALSE(const_m.Matches(foo3));11971198const Matcher<UncopyableFoo&> m =1199ReferencesAnyOf<UncopyableFoo&, UncopyableFoo&>(foo1, foo2);12001201EXPECT_TRUE(m.Matches(foo1));1202EXPECT_TRUE(m.Matches(foo2));1203EXPECT_FALSE(m.Matches(foo3));1204}12051206TEST(MatcherPnMacroTest,1207GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {1208UncopyableFoo foo1('1'), foo2('2');1209const Matcher<const UncopyableFoo&> m =1210ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);12111212// We don't want the addresses of the parameters printed, as most1213// likely they will just annoy the user. If the addresses are1214// interesting, the user should consider passing the parameters by1215// pointers instead.1216EXPECT_EQ(1217"references any of (variable1: 1-byte object <31>, variable2: 1-byte "1218"object <32>)",1219Describe(m));1220}12211222// Tests that a simple MATCHER_P2() definition works.12231224MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }12251226TEST(MatcherPnMacroTest, Works) {1227const Matcher<const long&> m = IsNotInClosedRange(10, 20); // NOLINT1228EXPECT_TRUE(m.Matches(36L));1229EXPECT_FALSE(m.Matches(15L));12301231EXPECT_EQ("is not in closed range (low: 10, hi: 20)", Describe(m));1232EXPECT_EQ("not (is not in closed range (low: 10, hi: 20))",1233DescribeNegation(m));1234EXPECT_EQ("", Explain(m, 36L));1235EXPECT_EQ("", Explain(m, 15L));1236}12371238// Tests that MATCHER*() definitions can be overloaded on the number1239// of parameters; also tests MATCHER_Pn() where n >= 3.12401241MATCHER(EqualsSumOf, "") { return arg == 0; }1242MATCHER_P(EqualsSumOf, a, "") { return arg == a; }1243MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }1244MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }1245MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }1246MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }1247MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {1248return arg == a + b + c + d + e + f;1249}1250MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {1251return arg == a + b + c + d + e + f + g;1252}1253MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {1254return arg == a + b + c + d + e + f + g + h;1255}1256MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {1257return arg == a + b + c + d + e + f + g + h + i;1258}1259MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {1260return arg == a + b + c + d + e + f + g + h + i + j;1261}12621263TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {1264EXPECT_THAT(0, EqualsSumOf());1265EXPECT_THAT(1, EqualsSumOf(1));1266EXPECT_THAT(12, EqualsSumOf(10, 2));1267EXPECT_THAT(123, EqualsSumOf(100, 20, 3));1268EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));1269EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));1270EXPECT_THAT("abcdef",1271EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));1272EXPECT_THAT("abcdefg",1273EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));1274EXPECT_THAT("abcdefgh", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",1275'f', 'g', "h"));1276EXPECT_THAT("abcdefghi", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",1277'f', 'g', "h", 'i'));1278EXPECT_THAT("abcdefghij",1279EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', "h",1280'i', ::std::string("j")));12811282EXPECT_THAT(1, Not(EqualsSumOf()));1283EXPECT_THAT(-1, Not(EqualsSumOf(1)));1284EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));1285EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));1286EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));1287EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));1288EXPECT_THAT("abcdef ",1289Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));1290EXPECT_THAT("abcdefg ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",1291"e", 'f', 'g')));1292EXPECT_THAT("abcdefgh ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",1293"e", 'f', 'g', "h")));1294EXPECT_THAT("abcdefghi ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",1295"e", 'f', 'g', "h", 'i')));1296EXPECT_THAT("abcdefghij ",1297Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',1298"h", 'i', ::std::string("j"))));1299}13001301// Tests that a MATCHER_Pn() definition can be instantiated with any1302// compatible parameter types.1303TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {1304EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));1305EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));13061307EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));1308EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));1309}13101311// Tests that the matcher body can promote the parameter types.13121313MATCHER_P2(EqConcat, prefix, suffix, "") {1314// The following lines promote the two parameters to desired types.1315std::string prefix_str(prefix);1316char suffix_char = static_cast<char>(suffix);1317return arg == prefix_str + suffix_char;1318}13191320TEST(MatcherPnMacroTest, SimpleTypePromotion) {1321Matcher<std::string> no_promo = EqConcat(std::string("foo"), 't');1322Matcher<const std::string&> promo = EqConcat("foo", static_cast<int>('t'));1323EXPECT_FALSE(no_promo.Matches("fool"));1324EXPECT_FALSE(promo.Matches("fool"));1325EXPECT_TRUE(no_promo.Matches("foot"));1326EXPECT_TRUE(promo.Matches("foot"));1327}13281329// Verifies the type of a MATCHER*.13301331TEST(MatcherPnMacroTest, TypesAreCorrect) {1332// EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.1333EqualsSumOfMatcher a0 = EqualsSumOf();13341335// EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.1336EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);13371338// EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk1339// variable, and so on.1340EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');1341EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');1342EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');1343EqualsSumOfMatcherP5<int, int, int, int, char> a5 =1344EqualsSumOf(1, 2, 3, 4, '5');1345EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =1346EqualsSumOf(1, 2, 3, 4, 5, '6');1347EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =1348EqualsSumOf(1, 2, 3, 4, 5, 6, '7');1349EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =1350EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');1351EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =1352EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');1353EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =1354EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');13551356// Avoid "unused variable" warnings.1357(void)a0;1358(void)a1;1359(void)a2;1360(void)a3;1361(void)a4;1362(void)a5;1363(void)a6;1364(void)a7;1365(void)a8;1366(void)a9;1367(void)a10;1368}13691370// Tests that matcher-typed parameters can be used in Value() inside a1371// MATCHER_Pn definition.13721373// Succeeds if arg matches exactly 2 of the 3 matchers.1374MATCHER_P3(TwoOf, m1, m2, m3, "") {1375const int count = static_cast<int>(Value(arg, m1)) +1376static_cast<int>(Value(arg, m2)) +1377static_cast<int>(Value(arg, m3));1378return count == 2;1379}13801381TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {1382EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));1383EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));1384}13851386// Tests Contains().Times().13871388INSTANTIATE_GTEST_MATCHER_TEST_P(ContainsTimes);13891390TEST(ContainsTimes, ListMatchesWhenElementQuantityMatches) {1391list<int> some_list;1392some_list.push_back(3);1393some_list.push_back(1);1394some_list.push_back(2);1395some_list.push_back(3);1396EXPECT_THAT(some_list, Contains(3).Times(2));1397EXPECT_THAT(some_list, Contains(2).Times(1));1398EXPECT_THAT(some_list, Contains(Ge(2)).Times(3));1399EXPECT_THAT(some_list, Contains(Ge(2)).Times(Gt(2)));1400EXPECT_THAT(some_list, Contains(4).Times(0));1401EXPECT_THAT(some_list, Contains(_).Times(4));1402EXPECT_THAT(some_list, Not(Contains(5).Times(1)));1403EXPECT_THAT(some_list, Contains(5).Times(_)); // Times(_) always matches1404EXPECT_THAT(some_list, Not(Contains(3).Times(1)));1405EXPECT_THAT(some_list, Contains(3).Times(Not(1)));1406EXPECT_THAT(list<int>{}, Not(Contains(_)));1407}14081409TEST_P(ContainsTimesP, ExplainsMatchResultCorrectly) {1410const int a[2] = {1, 2};1411Matcher<const int(&)[2]> m = Contains(2).Times(3);1412EXPECT_EQ(1413"whose element #1 matches but whose match quantity of 1 does not match",1414Explain(m, a));14151416m = Contains(3).Times(0);1417EXPECT_EQ("has no element that matches and whose match quantity of 0 matches",1418Explain(m, a));14191420m = Contains(3).Times(4);1421EXPECT_EQ(1422"has no element that matches and whose match quantity of 0 does not "1423"match",1424Explain(m, a));14251426m = Contains(2).Times(4);1427EXPECT_EQ(1428"whose element #1 matches but whose match quantity of 1 does not "1429"match",1430Explain(m, a));14311432m = Contains(GreaterThan(0)).Times(2);1433EXPECT_EQ("whose elements (0, 1) match and whose match quantity of 2 matches",1434Explain(m, a));14351436m = Contains(GreaterThan(10)).Times(Gt(1));1437EXPECT_EQ(1438"has no element that matches and whose match quantity of 0 does not "1439"match",1440Explain(m, a));14411442m = Contains(GreaterThan(0)).Times(GreaterThan<size_t>(5));1443EXPECT_EQ(1444"whose elements (0, 1) match but whose match quantity of 2 does not "1445"match, which is 3 less than 5",1446Explain(m, a));1447}14481449TEST(ContainsTimes, DescribesItselfCorrectly) {1450Matcher<vector<int>> m = Contains(1).Times(2);1451EXPECT_EQ("quantity of elements that match is equal to 1 is equal to 2",1452Describe(m));14531454Matcher<vector<int>> m2 = Not(m);1455EXPECT_EQ("quantity of elements that match is equal to 1 isn't equal to 2",1456Describe(m2));1457}14581459// Tests AllOfArray()14601461TEST(AllOfArrayTest, BasicForms) {1462// Iterator1463std::vector<int> v0{};1464std::vector<int> v1{1};1465std::vector<int> v2{2, 3};1466std::vector<int> v3{4, 4, 4};1467EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end()));1468EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end()));1469EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));1470EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));1471EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end()));1472// Pointer + size1473int ar[6] = {1, 2, 3, 4, 4, 4};1474EXPECT_THAT(0, AllOfArray(ar, 0));1475EXPECT_THAT(1, AllOfArray(ar, 1));1476EXPECT_THAT(2, Not(AllOfArray(ar, 1)));1477EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3)));1478EXPECT_THAT(4, AllOfArray(ar + 3, 3));1479// Array1480// int ar0[0]; Not usable1481int ar1[1] = {1};1482int ar2[2] = {2, 3};1483int ar3[3] = {4, 4, 4};1484// EXPECT_THAT(0, Not(AllOfArray(ar0))); // Cannot work1485EXPECT_THAT(1, AllOfArray(ar1));1486EXPECT_THAT(2, Not(AllOfArray(ar1)));1487EXPECT_THAT(3, Not(AllOfArray(ar2)));1488EXPECT_THAT(4, AllOfArray(ar3));1489// Container1490EXPECT_THAT(0, AllOfArray(v0));1491EXPECT_THAT(1, AllOfArray(v1));1492EXPECT_THAT(2, Not(AllOfArray(v1)));1493EXPECT_THAT(3, Not(AllOfArray(v2)));1494EXPECT_THAT(4, AllOfArray(v3));1495// Initializer1496EXPECT_THAT(0, AllOfArray<int>({})); // Requires template arg.1497EXPECT_THAT(1, AllOfArray({1}));1498EXPECT_THAT(2, Not(AllOfArray({1})));1499EXPECT_THAT(3, Not(AllOfArray({2, 3})));1500EXPECT_THAT(4, AllOfArray({4, 4, 4}));1501}15021503TEST(AllOfArrayTest, Matchers) {1504// vector1505std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};1506EXPECT_THAT(0, Not(AllOfArray(matchers)));1507EXPECT_THAT(1, AllOfArray(matchers));1508EXPECT_THAT(2, Not(AllOfArray(matchers)));1509// initializer_list1510EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)})));1511EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)}));1512}15131514INSTANTIATE_GTEST_MATCHER_TEST_P(AnyOfArrayTest);15151516TEST(AnyOfArrayTest, BasicForms) {1517// Iterator1518std::vector<int> v0{};1519std::vector<int> v1{1};1520std::vector<int> v2{2, 3};1521EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end())));1522EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end()));1523EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));1524EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end()));1525EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));1526// Pointer + size1527int ar[3] = {1, 2, 3};1528EXPECT_THAT(0, Not(AnyOfArray(ar, 0)));1529EXPECT_THAT(1, AnyOfArray(ar, 1));1530EXPECT_THAT(2, Not(AnyOfArray(ar, 1)));1531EXPECT_THAT(3, AnyOfArray(ar + 1, 2));1532EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2)));1533// Array1534// int ar0[0]; Not usable1535int ar1[1] = {1};1536int ar2[2] = {2, 3};1537// EXPECT_THAT(0, Not(AnyOfArray(ar0))); // Cannot work1538EXPECT_THAT(1, AnyOfArray(ar1));1539EXPECT_THAT(2, Not(AnyOfArray(ar1)));1540EXPECT_THAT(3, AnyOfArray(ar2));1541EXPECT_THAT(4, Not(AnyOfArray(ar2)));1542// Container1543EXPECT_THAT(0, Not(AnyOfArray(v0)));1544EXPECT_THAT(1, AnyOfArray(v1));1545EXPECT_THAT(2, Not(AnyOfArray(v1)));1546EXPECT_THAT(3, AnyOfArray(v2));1547EXPECT_THAT(4, Not(AnyOfArray(v2)));1548// Initializer1549EXPECT_THAT(0, Not(AnyOfArray<int>({}))); // Requires template arg.1550EXPECT_THAT(1, AnyOfArray({1}));1551EXPECT_THAT(2, Not(AnyOfArray({1})));1552EXPECT_THAT(3, AnyOfArray({2, 3}));1553EXPECT_THAT(4, Not(AnyOfArray({2, 3})));1554}15551556TEST(AnyOfArrayTest, Matchers) {1557// We negate test AllOfArrayTest.Matchers.1558// vector1559std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};1560EXPECT_THAT(0, AnyOfArray(matchers));1561EXPECT_THAT(1, Not(AnyOfArray(matchers)));1562EXPECT_THAT(2, AnyOfArray(matchers));1563// initializer_list1564EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)}));1565EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)})));1566}15671568TEST_P(AnyOfArrayTestP, ExplainsMatchResultCorrectly) {1569// AnyOfArray and AllOfArray use the same underlying template-template,1570// thus it is sufficient to test one here.1571const std::vector<int> v0{};1572const std::vector<int> v1{1};1573const std::vector<int> v2{2, 3};1574const Matcher<int> m0 = AnyOfArray(v0);1575const Matcher<int> m1 = AnyOfArray(v1);1576const Matcher<int> m2 = AnyOfArray(v2);1577EXPECT_EQ("", Explain(m0, 0));1578EXPECT_EQ("", Explain(m1, 1));1579EXPECT_EQ("", Explain(m1, 2));1580EXPECT_EQ("", Explain(m2, 3));1581EXPECT_EQ("", Explain(m2, 4));1582EXPECT_EQ("()", Describe(m0));1583EXPECT_EQ("(is equal to 1)", Describe(m1));1584EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));1585EXPECT_EQ("()", DescribeNegation(m0));1586EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1));1587EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2));1588// Explain with matchers1589const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});1590const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});1591// Explains the first positive match and all prior negative matches...1592EXPECT_EQ("which is 1 less than 1", Explain(g1, 0));1593EXPECT_EQ("which is the same as 1", Explain(g1, 1));1594EXPECT_EQ("which is 1 more than 1", Explain(g1, 2));1595EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2",1596Explain(g2, 0));1597EXPECT_EQ("which is the same as 1, and which is 1 less than 2",1598Explain(g2, 1));1599EXPECT_EQ("which is 1 more than 1", // Only the first1600Explain(g2, 2));1601}16021603MATCHER(IsNotNull, "") { return arg != nullptr; }16041605// Verifies that a matcher defined using MATCHER() can work on1606// move-only types.1607TEST(MatcherMacroTest, WorksOnMoveOnlyType) {1608std::unique_ptr<int> p(new int(3));1609EXPECT_THAT(p, IsNotNull());1610EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));1611}16121613MATCHER_P(UniquePointee, pointee, "") { return *arg == pointee; }16141615// Verifies that a matcher defined using MATCHER_P*() can work on1616// move-only types.1617TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {1618std::unique_ptr<int> p(new int(3));1619EXPECT_THAT(p, UniquePointee(3));1620EXPECT_THAT(p, Not(UniquePointee(2)));1621}16221623MATCHER(EnsureNoUnusedButMarkedUnusedWarning, "") { return (arg % 2) == 0; }16241625TEST(MockMethodMockFunctionTest, EnsureNoUnusedButMarkedUnusedWarning) {1626#ifdef __clang__1627#pragma clang diagnostic push1628#pragma clang diagnostic error "-Wused-but-marked-unused"1629#endif1630// https://github.com/google/googletest/issues/40551631EXPECT_THAT(0, EnsureNoUnusedButMarkedUnusedWarning());1632#ifdef __clang__1633#pragma clang diagnostic pop1634#endif1635}16361637#if GTEST_HAS_EXCEPTIONS16381639// std::function<void()> is used below for compatibility with older copies of1640// GCC. Normally, a raw lambda is all that is needed.16411642// Test that examples from documentation compile1643TEST(ThrowsTest, Examples) {1644EXPECT_THAT(1645std::function<void()>([]() { throw std::runtime_error("message"); }),1646Throws<std::runtime_error>());16471648EXPECT_THAT(1649std::function<void()>([]() { throw std::runtime_error("message"); }),1650ThrowsMessage<std::runtime_error>(HasSubstr("message")));1651}16521653TEST(ThrowsTest, PrintsExceptionWhat) {1654EXPECT_THAT(1655std::function<void()>([]() { throw std::runtime_error("ABC123XYZ"); }),1656ThrowsMessage<std::runtime_error>(HasSubstr("ABC123XYZ")));1657}16581659TEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) {1660EXPECT_THAT(std::function<void()>([]() { throw std::exception(); }),1661Throws<std::exception>());1662}16631664TEST(ThrowsTest, CallableExecutedExactlyOnce) {1665size_t a = 0;16661667EXPECT_THAT(std::function<void()>([&a]() {1668a++;1669throw 10;1670}),1671Throws<int>());1672EXPECT_EQ(a, 1u);16731674EXPECT_THAT(std::function<void()>([&a]() {1675a++;1676throw std::runtime_error("message");1677}),1678Throws<std::runtime_error>());1679EXPECT_EQ(a, 2u);16801681EXPECT_THAT(std::function<void()>([&a]() {1682a++;1683throw std::runtime_error("message");1684}),1685ThrowsMessage<std::runtime_error>(HasSubstr("message")));1686EXPECT_EQ(a, 3u);16871688EXPECT_THAT(std::function<void()>([&a]() {1689a++;1690throw std::runtime_error("message");1691}),1692Throws<std::runtime_error>(1693Property(&std::runtime_error::what, HasSubstr("message"))));1694EXPECT_EQ(a, 4u);1695}16961697TEST(ThrowsTest, Describe) {1698Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();1699std::stringstream ss;1700matcher.DescribeTo(&ss);1701auto explanation = ss.str();1702EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));1703}17041705TEST(ThrowsTest, Success) {1706Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();1707StringMatchResultListener listener;1708EXPECT_TRUE(matcher.MatchAndExplain(1709[]() { throw std::runtime_error("error message"); }, &listener));1710EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));1711}17121713TEST(ThrowsTest, FailWrongType) {1714Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();1715StringMatchResultListener listener;1716EXPECT_FALSE(matcher.MatchAndExplain(1717[]() { throw std::logic_error("error message"); }, &listener));1718EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));1719EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));1720}17211722TEST(ThrowsTest, FailWrongTypeNonStd) {1723Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();1724StringMatchResultListener listener;1725EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));1726EXPECT_THAT(listener.str(),1727HasSubstr("throws an exception of an unknown type"));1728}17291730TEST(ThrowsTest, FailNoThrow) {1731Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();1732StringMatchResultListener listener;1733EXPECT_FALSE(matcher.MatchAndExplain([]() { (void)0; }, &listener));1734EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));1735}17361737class ThrowsPredicateTest1738: public TestWithParam<Matcher<std::function<void()>>> {};17391740TEST_P(ThrowsPredicateTest, Describe) {1741Matcher<std::function<void()>> matcher = GetParam();1742std::stringstream ss;1743matcher.DescribeTo(&ss);1744auto explanation = ss.str();1745EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));1746EXPECT_THAT(explanation, HasSubstr("error message"));1747}17481749TEST_P(ThrowsPredicateTest, Success) {1750Matcher<std::function<void()>> matcher = GetParam();1751StringMatchResultListener listener;1752EXPECT_TRUE(matcher.MatchAndExplain(1753[]() { throw std::runtime_error("error message"); }, &listener));1754EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));1755}17561757TEST_P(ThrowsPredicateTest, FailWrongType) {1758Matcher<std::function<void()>> matcher = GetParam();1759StringMatchResultListener listener;1760EXPECT_FALSE(matcher.MatchAndExplain(1761[]() { throw std::logic_error("error message"); }, &listener));1762EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));1763EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));1764}17651766TEST_P(ThrowsPredicateTest, FailWrongTypeNonStd) {1767Matcher<std::function<void()>> matcher = GetParam();1768StringMatchResultListener listener;1769EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));1770EXPECT_THAT(listener.str(),1771HasSubstr("throws an exception of an unknown type"));1772}17731774TEST_P(ThrowsPredicateTest, FailNoThrow) {1775Matcher<std::function<void()>> matcher = GetParam();1776StringMatchResultListener listener;1777EXPECT_FALSE(matcher.MatchAndExplain([]() {}, &listener));1778EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));1779}17801781INSTANTIATE_TEST_SUITE_P(1782AllMessagePredicates, ThrowsPredicateTest,1783Values(Matcher<std::function<void()>>(1784ThrowsMessage<std::runtime_error>(HasSubstr("error message")))));17851786// Tests that Throws<E1>(Matcher<E2>{}) compiles even when E2 != const E1&.1787TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) {1788{1789Matcher<std::function<void()>> matcher =1790ThrowsMessage<std::runtime_error>(HasSubstr("error message"));1791EXPECT_TRUE(1792matcher.Matches([]() { throw std::runtime_error("error message"); }));1793EXPECT_FALSE(1794matcher.Matches([]() { throw std::runtime_error("wrong message"); }));1795}17961797{1798Matcher<uint64_t> inner = Eq(10);1799Matcher<std::function<void()>> matcher = Throws<uint32_t>(inner);1800EXPECT_TRUE(matcher.Matches([]() { throw (uint32_t)10; }));1801EXPECT_FALSE(matcher.Matches([]() { throw (uint32_t)11; }));1802}1803}18041805// Tests that ThrowsMessage("message") is equivalent1806// to ThrowsMessage(Eq<std::string>("message")).1807TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {1808Matcher<std::function<void()>> matcher =1809ThrowsMessage<std::runtime_error>("error message");1810EXPECT_TRUE(1811matcher.Matches([]() { throw std::runtime_error("error message"); }));1812EXPECT_FALSE(matcher.Matches(1813[]() { throw std::runtime_error("wrong error message"); }));1814}18151816#endif // GTEST_HAS_EXCEPTIONS18171818} // namespace1819} // namespace gmock_matchers_test1820} // namespace testing18211822GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100182318241825