gmock-matchers.cc 18 KB

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