gmock-matchers.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. // Copyright 2007, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. // Google Mock - a framework for writing C++ mock classes.
  30. //
  31. // This file implements Matcher<const string&>, Matcher<string>, and
  32. // utilities for defining matchers.
  33. #include "gmock/gmock-matchers.h"
  34. #include "gmock/gmock-generated-matchers.h"
  35. #include <string.h>
  36. #include <iostream>
  37. #include <sstream>
  38. #include <string>
  39. namespace testing {
  40. namespace internal {
  41. // Returns the description for a matcher defined using the MATCHER*()
  42. // macro where the user-supplied description string is "", if
  43. // 'negation' is false; otherwise returns the description of the
  44. // negation of the matcher. 'param_values' contains a list of strings
  45. // that are the print-out of the matcher's parameters.
  46. GTEST_API_ std::string FormatMatcherDescription(bool negation,
  47. const char* matcher_name,
  48. const Strings& param_values) {
  49. std::string result = ConvertIdentifierNameToWords(matcher_name);
  50. if (param_values.size() >= 1) result += " " + JoinAsTuple(param_values);
  51. return negation ? "not (" + result + ")" : result;
  52. }
  53. // FindMaxBipartiteMatching and its helper class.
  54. //
  55. // Uses the well-known Ford-Fulkerson max flow method to find a maximum
  56. // bipartite matching. Flow is considered to be from left to right.
  57. // There is an implicit source node that is connected to all of the left
  58. // nodes, and an implicit sink node that is connected to all of the
  59. // right nodes. All edges have unit capacity.
  60. //
  61. // Neither the flow graph nor the residual flow graph are represented
  62. // explicitly. Instead, they are implied by the information in 'graph' and
  63. // a vector<int> called 'left_' whose elements are initialized to the
  64. // value kUnused. This represents the initial state of the algorithm,
  65. // where the flow graph is empty, and the residual flow graph has the
  66. // following edges:
  67. // - An edge from source to each left_ node
  68. // - An edge from each right_ node to sink
  69. // - An edge from each left_ node to each right_ node, if the
  70. // corresponding edge exists in 'graph'.
  71. //
  72. // When the TryAugment() method adds a flow, it sets left_[l] = r for some
  73. // nodes l and r. This induces the following changes:
  74. // - The edges (source, l), (l, r), and (r, sink) are added to the
  75. // flow graph.
  76. // - The same three edges are removed from the residual flow graph.
  77. // - The reverse edges (l, source), (r, l), and (sink, r) are added
  78. // to the residual flow graph, which is a directional graph
  79. // representing unused flow capacity.
  80. //
  81. // When the method augments a flow (moving left_[l] from some r1 to some
  82. // other r2), this can be thought of as "undoing" the above steps with
  83. // respect to r1 and "redoing" them with respect to r2.
  84. //
  85. // It bears repeating that the flow graph and residual flow graph are
  86. // never represented explicitly, but can be derived by looking at the
  87. // information in 'graph' and in left_.
  88. //
  89. // As an optimization, there is a second vector<int> called right_ which
  90. // does not provide any new information. Instead, it enables more
  91. // efficient queries about edges entering or leaving the right-side nodes
  92. // of the flow or residual flow graphs. The following invariants are
  93. // maintained:
  94. //
  95. // left[l] == kUnused or right[left[l]] == l
  96. // right[r] == kUnused or left[right[r]] == r
  97. //
  98. // . [ source ] .
  99. // . ||| .
  100. // . ||| .
  101. // . ||\--> left[0]=1 ---\ right[0]=-1 ----\ .
  102. // . || | | .
  103. // . |\---> left[1]=-1 \--> right[1]=0 ---\| .
  104. // . | || .
  105. // . \----> left[2]=2 ------> right[2]=2 --\|| .
  106. // . ||| .
  107. // . elements matchers vvv .
  108. // . [ sink ] .
  109. //
  110. // See Also:
  111. // [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method".
  112. // "Introduction to Algorithms (Second ed.)", pp. 651-664.
  113. // [2] "Ford-Fulkerson algorithm", Wikipedia,
  114. // 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
  115. class MaxBipartiteMatchState {
  116. public:
  117. explicit MaxBipartiteMatchState(const MatchMatrix& graph)
  118. : graph_(&graph),
  119. left_(graph_->LhsSize(), kUnused),
  120. right_(graph_->RhsSize(), kUnused) {}
  121. // Returns the edges of a maximal match, each in the form {left, right}.
  122. ElementMatcherPairs Compute() {
  123. // 'seen' is used for path finding { 0: unseen, 1: seen }.
  124. ::std::vector<char> seen;
  125. // Searches the residual flow graph for a path from each left node to
  126. // the sink in the residual flow graph, and if one is found, add flow
  127. // to the graph. It's okay to search through the left nodes once. The
  128. // edge from the implicit source node to each previously-visited left
  129. // node will have flow if that left node has any path to the sink
  130. // whatsoever. Subsequent augmentations can only add flow to the
  131. // network, and cannot take away that previous flow unit from the source.
  132. // Since the source-to-left edge can only carry one flow unit (or,
  133. // each element can be matched to only one matcher), there is no need
  134. // to visit the left nodes more than once looking for augmented paths.
  135. // The flow is known to be possible or impossible by looking at the
  136. // node once.
  137. for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
  138. // Reset the path-marking vector and try to find a path from
  139. // source to sink starting at the left_[ilhs] node.
  140. GTEST_CHECK_(left_[ilhs] == kUnused)
  141. << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
  142. // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
  143. seen.assign(graph_->RhsSize(), 0);
  144. TryAugment(ilhs, &seen);
  145. }
  146. ElementMatcherPairs result;
  147. for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
  148. size_t irhs = left_[ilhs];
  149. if (irhs == kUnused) continue;
  150. result.push_back(ElementMatcherPair(ilhs, irhs));
  151. }
  152. return result;
  153. }
  154. private:
  155. static const size_t kUnused = static_cast<size_t>(-1);
  156. // Perform a depth-first search from left node ilhs to the sink. If a
  157. // path is found, flow is added to the network by linking the left and
  158. // right vector elements corresponding each segment of the path.
  159. // Returns true if a path to sink was found, which means that a unit of
  160. // flow was added to the network. The 'seen' vector elements correspond
  161. // to right nodes and are marked to eliminate cycles from the search.
  162. //
  163. // Left nodes will only be explored at most once because they
  164. // are accessible from at most one right node in the residual flow
  165. // graph.
  166. //
  167. // Note that left_[ilhs] is the only element of left_ that TryAugment will
  168. // potentially transition from kUnused to another value. Any other
  169. // left_ element holding kUnused before TryAugment will be holding it
  170. // when TryAugment returns.
  171. //
  172. bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
  173. for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
  174. if ((*seen)[irhs]) continue;
  175. if (!graph_->HasEdge(ilhs, irhs)) continue;
  176. // There's an available edge from ilhs to irhs.
  177. (*seen)[irhs] = 1;
  178. // Next a search is performed to determine whether
  179. // this edge is a dead end or leads to the sink.
  180. //
  181. // right_[irhs] == kUnused means that there is residual flow from
  182. // right node irhs to the sink, so we can use that to finish this
  183. // flow path and return success.
  184. //
  185. // Otherwise there is residual flow to some ilhs. We push flow
  186. // along that path and call ourselves recursively to see if this
  187. // ultimately leads to sink.
  188. if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
  189. // Add flow from left_[ilhs] to right_[irhs].
  190. left_[ilhs] = irhs;
  191. right_[irhs] = ilhs;
  192. return true;
  193. }
  194. }
  195. return false;
  196. }
  197. const MatchMatrix* graph_; // not owned
  198. // Each element of the left_ vector represents a left hand side node
  199. // (i.e. an element) and each element of right_ is a right hand side
  200. // node (i.e. a matcher). The values in the left_ vector indicate
  201. // outflow from that node to a node on the right_ side. The values
  202. // in the right_ indicate inflow, and specify which left_ node is
  203. // feeding that right_ node, if any. For example, left_[3] == 1 means
  204. // there's a flow from element #3 to matcher #1. Such a flow would also
  205. // be redundantly represented in the right_ vector as right_[1] == 3.
  206. // Elements of left_ and right_ are either kUnused or mutually
  207. // referent. Mutually referent means that left_[right_[i]] = i and
  208. // right_[left_[i]] = i.
  209. ::std::vector<size_t> left_;
  210. ::std::vector<size_t> right_;
  211. GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState);
  212. };
  213. const size_t MaxBipartiteMatchState::kUnused;
  214. GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g) {
  215. return MaxBipartiteMatchState(g).Compute();
  216. }
  217. static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
  218. ::std::ostream* stream) {
  219. typedef ElementMatcherPairs::const_iterator Iter;
  220. ::std::ostream& os = *stream;
  221. os << "{";
  222. const char* sep = "";
  223. for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
  224. os << sep << "\n ("
  225. << "element #" << it->first << ", "
  226. << "matcher #" << it->second << ")";
  227. sep = ",";
  228. }
  229. os << "\n}";
  230. }
  231. bool MatchMatrix::NextGraph() {
  232. for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
  233. for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
  234. char& b = matched_[SpaceIndex(ilhs, irhs)];
  235. if (!b) {
  236. b = 1;
  237. return true;
  238. }
  239. b = 0;
  240. }
  241. }
  242. return false;
  243. }
  244. void MatchMatrix::Randomize() {
  245. for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
  246. for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
  247. char& b = matched_[SpaceIndex(ilhs, irhs)];
  248. b = static_cast<char>(rand() & 1); // NOLINT
  249. }
  250. }
  251. }
  252. std::string MatchMatrix::DebugString() const {
  253. ::std::stringstream ss;
  254. const char* sep = "";
  255. for (size_t i = 0; i < LhsSize(); ++i) {
  256. ss << sep;
  257. for (size_t j = 0; j < RhsSize(); ++j) {
  258. ss << HasEdge(i, j);
  259. }
  260. sep = ";";
  261. }
  262. return ss.str();
  263. }
  264. void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
  265. ::std::ostream* os) const {
  266. switch (match_flags()) {
  267. case UnorderedMatcherRequire::ExactMatch:
  268. if (matcher_describers_.empty()) {
  269. *os << "is empty";
  270. return;
  271. }
  272. if (matcher_describers_.size() == 1) {
  273. *os << "has " << Elements(1) << " and that element ";
  274. matcher_describers_[0]->DescribeTo(os);
  275. return;
  276. }
  277. *os << "has " << Elements(matcher_describers_.size())
  278. << " and there exists some permutation of elements such that:\n";
  279. break;
  280. case UnorderedMatcherRequire::Superset:
  281. *os << "a surjection from elements to requirements exists such that:\n";
  282. break;
  283. case UnorderedMatcherRequire::Subset:
  284. *os << "an injection from elements to requirements exists such that:\n";
  285. break;
  286. }
  287. const char* sep = "";
  288. for (size_t i = 0; i != matcher_describers_.size(); ++i) {
  289. *os << sep;
  290. if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
  291. *os << " - element #" << i << " ";
  292. } else {
  293. *os << " - an element ";
  294. }
  295. matcher_describers_[i]->DescribeTo(os);
  296. if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
  297. sep = ", and\n";
  298. } else {
  299. sep = "\n";
  300. }
  301. }
  302. }
  303. void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
  304. ::std::ostream* os) const {
  305. switch (match_flags()) {
  306. case UnorderedMatcherRequire::ExactMatch:
  307. if (matcher_describers_.empty()) {
  308. *os << "isn't empty";
  309. return;
  310. }
  311. if (matcher_describers_.size() == 1) {
  312. *os << "doesn't have " << Elements(1) << ", or has " << Elements(1)
  313. << " that ";
  314. matcher_describers_[0]->DescribeNegationTo(os);
  315. return;
  316. }
  317. *os << "doesn't have " << Elements(matcher_describers_.size())
  318. << ", or there exists no permutation of elements such that:\n";
  319. break;
  320. case UnorderedMatcherRequire::Superset:
  321. *os << "no surjection from elements to requirements exists such that:\n";
  322. break;
  323. case UnorderedMatcherRequire::Subset:
  324. *os << "no injection from elements to requirements exists such that:\n";
  325. break;
  326. }
  327. const char* sep = "";
  328. for (size_t i = 0; i != matcher_describers_.size(); ++i) {
  329. *os << sep;
  330. if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
  331. *os << " - element #" << i << " ";
  332. } else {
  333. *os << " - an element ";
  334. }
  335. matcher_describers_[i]->DescribeTo(os);
  336. if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
  337. sep = ", and\n";
  338. } else {
  339. sep = "\n";
  340. }
  341. }
  342. }
  343. // Checks that all matchers match at least one element, and that all
  344. // elements match at least one matcher. This enables faster matching
  345. // and better error reporting.
  346. // Returns false, writing an explanation to 'listener', if and only
  347. // if the success criteria are not met.
  348. bool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix(
  349. const ::std::vector<std::string>& element_printouts,
  350. const MatchMatrix& matrix, MatchResultListener* listener) const {
  351. bool result = true;
  352. ::std::vector<char> element_matched(matrix.LhsSize(), 0);
  353. ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
  354. for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
  355. for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
  356. char matched = matrix.HasEdge(ilhs, irhs);
  357. element_matched[ilhs] |= matched;
  358. matcher_matched[irhs] |= matched;
  359. }
  360. }
  361. if (match_flags() & UnorderedMatcherRequire::Superset) {
  362. const char* sep =
  363. "where the following matchers don't match any elements:\n";
  364. for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
  365. if (matcher_matched[mi]) continue;
  366. result = false;
  367. if (listener->IsInterested()) {
  368. *listener << sep << "matcher #" << mi << ": ";
  369. matcher_describers_[mi]->DescribeTo(listener->stream());
  370. sep = ",\n";
  371. }
  372. }
  373. }
  374. if (match_flags() & UnorderedMatcherRequire::Subset) {
  375. const char* sep =
  376. "where the following elements don't match any matchers:\n";
  377. const char* outer_sep = "";
  378. if (!result) {
  379. outer_sep = "\nand ";
  380. }
  381. for (size_t ei = 0; ei < element_matched.size(); ++ei) {
  382. if (element_matched[ei]) continue;
  383. result = false;
  384. if (listener->IsInterested()) {
  385. *listener << outer_sep << sep << "element #" << ei << ": "
  386. << element_printouts[ei];
  387. sep = ",\n";
  388. outer_sep = "";
  389. }
  390. }
  391. }
  392. return result;
  393. }
  394. bool UnorderedElementsAreMatcherImplBase::FindPairing(
  395. const MatchMatrix& matrix, MatchResultListener* listener) const {
  396. ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);
  397. size_t max_flow = matches.size();
  398. if ((match_flags() & UnorderedMatcherRequire::Superset) &&
  399. max_flow < matrix.RhsSize()) {
  400. if (listener->IsInterested()) {
  401. *listener << "where no permutation of the elements can satisfy all "
  402. "matchers, and the closest match is "
  403. << max_flow << " of " << matrix.RhsSize()
  404. << " matchers with the pairings:\n";
  405. LogElementMatcherPairVec(matches, listener->stream());
  406. }
  407. return false;
  408. }
  409. if ((match_flags() & UnorderedMatcherRequire::Subset) &&
  410. max_flow < matrix.LhsSize()) {
  411. if (listener->IsInterested()) {
  412. *listener
  413. << "where not all elements can be matched, and the closest match is "
  414. << max_flow << " of " << matrix.RhsSize()
  415. << " matchers with the pairings:\n";
  416. LogElementMatcherPairVec(matches, listener->stream());
  417. }
  418. return false;
  419. }
  420. if (matches.size() > 1) {
  421. if (listener->IsInterested()) {
  422. const char* sep = "where:\n";
  423. for (size_t mi = 0; mi < matches.size(); ++mi) {
  424. *listener << sep << " - element #" << matches[mi].first
  425. << " is matched by matcher #" << matches[mi].second;
  426. sep = ",\n";
  427. }
  428. }
  429. }
  430. return true;
  431. }
  432. } // namespace internal
  433. } // namespace testing