gmock-matchers.cc
Go to the documentation of this file.
00001 // Copyright 2007, Google Inc.
00002 // All rights reserved.
00003 //
00004 // Redistribution and use in source and binary forms, with or without
00005 // modification, are permitted provided that the following conditions are
00006 // met:
00007 //
00008 //     * Redistributions of source code must retain the above copyright
00009 // notice, this list of conditions and the following disclaimer.
00010 //     * Redistributions in binary form must reproduce the above
00011 // copyright notice, this list of conditions and the following disclaimer
00012 // in the documentation and/or other materials provided with the
00013 // distribution.
00014 //     * Neither the name of Google Inc. nor the names of its
00015 // contributors may be used to endorse or promote products derived from
00016 // this software without specific prior written permission.
00017 //
00018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00029 //
00030 // Author: wan@google.com (Zhanyong Wan)
00031 
00032 // Google Mock - a framework for writing C++ mock classes.
00033 //
00034 // This file implements Matcher<const string&>, Matcher<string>, and
00035 // utilities for defining matchers.
00036 
00037 #include "gmock/gmock-matchers.h"
00038 #include "gmock/gmock-generated-matchers.h"
00039 
00040 #include <string.h>
00041 #include <sstream>
00042 #include <string>
00043 
00044 namespace testing {
00045 
00046 // Constructs a matcher that matches a const string& whose value is
00047 // equal to s.
00048 Matcher<const internal::string&>::Matcher(const internal::string& s) {
00049   *this = Eq(s);
00050 }
00051 
00052 // Constructs a matcher that matches a const string& whose value is
00053 // equal to s.
00054 Matcher<const internal::string&>::Matcher(const char* s) {
00055   *this = Eq(internal::string(s));
00056 }
00057 
00058 // Constructs a matcher that matches a string whose value is equal to s.
00059 Matcher<internal::string>::Matcher(const internal::string& s) { *this = Eq(s); }
00060 
00061 // Constructs a matcher that matches a string whose value is equal to s.
00062 Matcher<internal::string>::Matcher(const char* s) {
00063   *this = Eq(internal::string(s));
00064 }
00065 
00066 #if GTEST_HAS_STRING_PIECE_
00067 // Constructs a matcher that matches a const StringPiece& whose value is
00068 // equal to s.
00069 Matcher<const StringPiece&>::Matcher(const internal::string& s) {
00070   *this = Eq(s);
00071 }
00072 
00073 // Constructs a matcher that matches a const StringPiece& whose value is
00074 // equal to s.
00075 Matcher<const StringPiece&>::Matcher(const char* s) {
00076   *this = Eq(internal::string(s));
00077 }
00078 
00079 // Constructs a matcher that matches a const StringPiece& whose value is
00080 // equal to s.
00081 Matcher<const StringPiece&>::Matcher(StringPiece s) {
00082   *this = Eq(s.ToString());
00083 }
00084 
00085 // Constructs a matcher that matches a StringPiece whose value is equal to s.
00086 Matcher<StringPiece>::Matcher(const internal::string& s) {
00087   *this = Eq(s);
00088 }
00089 
00090 // Constructs a matcher that matches a StringPiece whose value is equal to s.
00091 Matcher<StringPiece>::Matcher(const char* s) {
00092   *this = Eq(internal::string(s));
00093 }
00094 
00095 // Constructs a matcher that matches a StringPiece whose value is equal to s.
00096 Matcher<StringPiece>::Matcher(StringPiece s) {
00097   *this = Eq(s.ToString());
00098 }
00099 #endif  // GTEST_HAS_STRING_PIECE_
00100 
00101 namespace internal {
00102 
00103 // Joins a vector of strings as if they are fields of a tuple; returns
00104 // the joined string.
00105 GTEST_API_ string JoinAsTuple(const Strings& fields) {
00106   switch (fields.size()) {
00107     case 0:
00108       return "";
00109     case 1:
00110       return fields[0];
00111     default:
00112       string result = "(" + fields[0];
00113       for (size_t i = 1; i < fields.size(); i++) {
00114         result += ", ";
00115         result += fields[i];
00116       }
00117       result += ")";
00118       return result;
00119   }
00120 }
00121 
00122 // Returns the description for a matcher defined using the MATCHER*()
00123 // macro where the user-supplied description string is "", if
00124 // 'negation' is false; otherwise returns the description of the
00125 // negation of the matcher.  'param_values' contains a list of strings
00126 // that are the print-out of the matcher's parameters.
00127 GTEST_API_ string FormatMatcherDescription(bool negation,
00128                                            const char* matcher_name,
00129                                            const Strings& param_values) {
00130   string result = ConvertIdentifierNameToWords(matcher_name);
00131   if (param_values.size() >= 1)
00132     result += " " + JoinAsTuple(param_values);
00133   return negation ? "not (" + result + ")" : result;
00134 }
00135 
00136 // FindMaxBipartiteMatching and its helper class.
00137 //
00138 // Uses the well-known Ford-Fulkerson max flow method to find a maximum
00139 // bipartite matching. Flow is considered to be from left to right.
00140 // There is an implicit source node that is connected to all of the left
00141 // nodes, and an implicit sink node that is connected to all of the
00142 // right nodes. All edges have unit capacity.
00143 //
00144 // Neither the flow graph nor the residual flow graph are represented
00145 // explicitly. Instead, they are implied by the information in 'graph' and
00146 // a vector<int> called 'left_' whose elements are initialized to the
00147 // value kUnused. This represents the initial state of the algorithm,
00148 // where the flow graph is empty, and the residual flow graph has the
00149 // following edges:
00150 //   - An edge from source to each left_ node
00151 //   - An edge from each right_ node to sink
00152 //   - An edge from each left_ node to each right_ node, if the
00153 //     corresponding edge exists in 'graph'.
00154 //
00155 // When the TryAugment() method adds a flow, it sets left_[l] = r for some
00156 // nodes l and r. This induces the following changes:
00157 //   - The edges (source, l), (l, r), and (r, sink) are added to the
00158 //     flow graph.
00159 //   - The same three edges are removed from the residual flow graph.
00160 //   - The reverse edges (l, source), (r, l), and (sink, r) are added
00161 //     to the residual flow graph, which is a directional graph
00162 //     representing unused flow capacity.
00163 //
00164 // When the method augments a flow (moving left_[l] from some r1 to some
00165 // other r2), this can be thought of as "undoing" the above steps with
00166 // respect to r1 and "redoing" them with respect to r2.
00167 //
00168 // It bears repeating that the flow graph and residual flow graph are
00169 // never represented explicitly, but can be derived by looking at the
00170 // information in 'graph' and in left_.
00171 //
00172 // As an optimization, there is a second vector<int> called right_ which
00173 // does not provide any new information. Instead, it enables more
00174 // efficient queries about edges entering or leaving the right-side nodes
00175 // of the flow or residual flow graphs. The following invariants are
00176 // maintained:
00177 //
00178 // left[l] == kUnused or right[left[l]] == l
00179 // right[r] == kUnused or left[right[r]] == r
00180 //
00181 // . [ source ]                                        .
00182 // .   |||                                             .
00183 // .   |||                                             .
00184 // .   ||\--> left[0]=1  ---\    right[0]=-1 ----\     .
00185 // .   ||                   |                    |     .
00186 // .   |\---> left[1]=-1    \--> right[1]=0  ---\|     .
00187 // .   |                                        ||     .
00188 // .   \----> left[2]=2  ------> right[2]=2  --\||     .
00189 // .                                           |||     .
00190 // .         elements           matchers       vvv     .
00191 // .                                         [ sink ]  .
00192 //
00193 // See Also:
00194 //   [1] Cormen, et al (2001). "Section 26.2: The Ford–Fulkerson method".
00195 //       "Introduction to Algorithms (Second ed.)", pp. 651–664.
00196 //   [2] "Ford–Fulkerson algorithm", Wikipedia,
00197 //       'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
00198 class MaxBipartiteMatchState {
00199  public:
00200   explicit MaxBipartiteMatchState(const MatchMatrix& graph)
00201       : graph_(&graph),
00202         left_(graph_->LhsSize(), kUnused),
00203         right_(graph_->RhsSize(), kUnused) {
00204   }
00205 
00206   // Returns the edges of a maximal match, each in the form {left, right}.
00207   ElementMatcherPairs Compute() {
00208     // 'seen' is used for path finding { 0: unseen, 1: seen }.
00209     ::std::vector<char> seen;
00210     // Searches the residual flow graph for a path from each left node to
00211     // the sink in the residual flow graph, and if one is found, add flow
00212     // to the graph. It's okay to search through the left nodes once. The
00213     // edge from the implicit source node to each previously-visited left
00214     // node will have flow if that left node has any path to the sink
00215     // whatsoever. Subsequent augmentations can only add flow to the
00216     // network, and cannot take away that previous flow unit from the source.
00217     // Since the source-to-left edge can only carry one flow unit (or,
00218     // each element can be matched to only one matcher), there is no need
00219     // to visit the left nodes more than once looking for augmented paths.
00220     // The flow is known to be possible or impossible by looking at the
00221     // node once.
00222     for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
00223       // Reset the path-marking vector and try to find a path from
00224       // source to sink starting at the left_[ilhs] node.
00225       GTEST_CHECK_(left_[ilhs] == kUnused)
00226           << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
00227       // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
00228       seen.assign(graph_->RhsSize(), 0);
00229       TryAugment(ilhs, &seen);
00230     }
00231     ElementMatcherPairs result;
00232     for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
00233       size_t irhs = left_[ilhs];
00234       if (irhs == kUnused) continue;
00235       result.push_back(ElementMatcherPair(ilhs, irhs));
00236     }
00237     return result;
00238   }
00239 
00240  private:
00241   static const size_t kUnused = static_cast<size_t>(-1);
00242 
00243   // Perform a depth-first search from left node ilhs to the sink.  If a
00244   // path is found, flow is added to the network by linking the left and
00245   // right vector elements corresponding each segment of the path.
00246   // Returns true if a path to sink was found, which means that a unit of
00247   // flow was added to the network. The 'seen' vector elements correspond
00248   // to right nodes and are marked to eliminate cycles from the search.
00249   //
00250   // Left nodes will only be explored at most once because they
00251   // are accessible from at most one right node in the residual flow
00252   // graph.
00253   //
00254   // Note that left_[ilhs] is the only element of left_ that TryAugment will
00255   // potentially transition from kUnused to another value. Any other
00256   // left_ element holding kUnused before TryAugment will be holding it
00257   // when TryAugment returns.
00258   //
00259   bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
00260     for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
00261       if ((*seen)[irhs])
00262         continue;
00263       if (!graph_->HasEdge(ilhs, irhs))
00264         continue;
00265       // There's an available edge from ilhs to irhs.
00266       (*seen)[irhs] = 1;
00267       // Next a search is performed to determine whether
00268       // this edge is a dead end or leads to the sink.
00269       //
00270       // right_[irhs] == kUnused means that there is residual flow from
00271       // right node irhs to the sink, so we can use that to finish this
00272       // flow path and return success.
00273       //
00274       // Otherwise there is residual flow to some ilhs. We push flow
00275       // along that path and call ourselves recursively to see if this
00276       // ultimately leads to sink.
00277       if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
00278         // Add flow from left_[ilhs] to right_[irhs].
00279         left_[ilhs] = irhs;
00280         right_[irhs] = ilhs;
00281         return true;
00282       }
00283     }
00284     return false;
00285   }
00286 
00287   const MatchMatrix* graph_;  // not owned
00288   // Each element of the left_ vector represents a left hand side node
00289   // (i.e. an element) and each element of right_ is a right hand side
00290   // node (i.e. a matcher). The values in the left_ vector indicate
00291   // outflow from that node to a node on the the right_ side. The values
00292   // in the right_ indicate inflow, and specify which left_ node is
00293   // feeding that right_ node, if any. For example, left_[3] == 1 means
00294   // there's a flow from element #3 to matcher #1. Such a flow would also
00295   // be redundantly represented in the right_ vector as right_[1] == 3.
00296   // Elements of left_ and right_ are either kUnused or mutually
00297   // referent. Mutually referent means that left_[right_[i]] = i and
00298   // right_[left_[i]] = i.
00299   ::std::vector<size_t> left_;
00300   ::std::vector<size_t> right_;
00301 
00302   GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState);
00303 };
00304 
00305 const size_t MaxBipartiteMatchState::kUnused;
00306 
00307 GTEST_API_ ElementMatcherPairs
00308 FindMaxBipartiteMatching(const MatchMatrix& g) {
00309   return MaxBipartiteMatchState(g).Compute();
00310 }
00311 
00312 static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
00313                                      ::std::ostream* stream) {
00314   typedef ElementMatcherPairs::const_iterator Iter;
00315   ::std::ostream& os = *stream;
00316   os << "{";
00317   const char *sep = "";
00318   for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
00319     os << sep << "\n  ("
00320        << "element #" << it->first << ", "
00321        << "matcher #" << it->second << ")";
00322     sep = ",";
00323   }
00324   os << "\n}";
00325 }
00326 
00327 // Tries to find a pairing, and explains the result.
00328 GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
00329                             MatchResultListener* listener) {
00330   ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);
00331 
00332   size_t max_flow = matches.size();
00333   bool result = (max_flow == matrix.RhsSize());
00334 
00335   if (!result) {
00336     if (listener->IsInterested()) {
00337       *listener << "where no permutation of the elements can "
00338                    "satisfy all matchers, and the closest match is "
00339                 << max_flow << " of " << matrix.RhsSize()
00340                 << " matchers with the pairings:\n";
00341       LogElementMatcherPairVec(matches, listener->stream());
00342     }
00343     return false;
00344   }
00345 
00346   if (matches.size() > 1) {
00347     if (listener->IsInterested()) {
00348       const char *sep = "where:\n";
00349       for (size_t mi = 0; mi < matches.size(); ++mi) {
00350         *listener << sep << " - element #" << matches[mi].first
00351                   << " is matched by matcher #" << matches[mi].second;
00352         sep = ",\n";
00353       }
00354     }
00355   }
00356   return true;
00357 }
00358 
00359 bool MatchMatrix::NextGraph() {
00360   for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
00361     for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
00362       char& b = matched_[SpaceIndex(ilhs, irhs)];
00363       if (!b) {
00364         b = 1;
00365         return true;
00366       }
00367       b = 0;
00368     }
00369   }
00370   return false;
00371 }
00372 
00373 void MatchMatrix::Randomize() {
00374   for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
00375     for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
00376       char& b = matched_[SpaceIndex(ilhs, irhs)];
00377       b = static_cast<char>(rand() & 1);  // NOLINT
00378     }
00379   }
00380 }
00381 
00382 string MatchMatrix::DebugString() const {
00383   ::std::stringstream ss;
00384   const char *sep = "";
00385   for (size_t i = 0; i < LhsSize(); ++i) {
00386     ss << sep;
00387     for (size_t j = 0; j < RhsSize(); ++j) {
00388       ss << HasEdge(i, j);
00389     }
00390     sep = ";";
00391   }
00392   return ss.str();
00393 }
00394 
00395 void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
00396     ::std::ostream* os) const {
00397   if (matcher_describers_.empty()) {
00398     *os << "is empty";
00399     return;
00400   }
00401   if (matcher_describers_.size() == 1) {
00402     *os << "has " << Elements(1) << " and that element ";
00403     matcher_describers_[0]->DescribeTo(os);
00404     return;
00405   }
00406   *os << "has " << Elements(matcher_describers_.size())
00407       << " and there exists some permutation of elements such that:\n";
00408   const char* sep = "";
00409   for (size_t i = 0; i != matcher_describers_.size(); ++i) {
00410     *os << sep << " - element #" << i << " ";
00411     matcher_describers_[i]->DescribeTo(os);
00412     sep = ", and\n";
00413   }
00414 }
00415 
00416 void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
00417     ::std::ostream* os) const {
00418   if (matcher_describers_.empty()) {
00419     *os << "isn't empty";
00420     return;
00421   }
00422   if (matcher_describers_.size() == 1) {
00423     *os << "doesn't have " << Elements(1)
00424         << ", or has " << Elements(1) << " that ";
00425     matcher_describers_[0]->DescribeNegationTo(os);
00426     return;
00427   }
00428   *os << "doesn't have " << Elements(matcher_describers_.size())
00429       << ", or there exists no permutation of elements such that:\n";
00430   const char* sep = "";
00431   for (size_t i = 0; i != matcher_describers_.size(); ++i) {
00432     *os << sep << " - element #" << i << " ";
00433     matcher_describers_[i]->DescribeTo(os);
00434     sep = ", and\n";
00435   }
00436 }
00437 
00438 // Checks that all matchers match at least one element, and that all
00439 // elements match at least one matcher. This enables faster matching
00440 // and better error reporting.
00441 // Returns false, writing an explanation to 'listener', if and only
00442 // if the success criteria are not met.
00443 bool UnorderedElementsAreMatcherImplBase::
00444 VerifyAllElementsAndMatchersAreMatched(
00445     const ::std::vector<string>& element_printouts,
00446     const MatchMatrix& matrix,
00447     MatchResultListener* listener) const {
00448   bool result = true;
00449   ::std::vector<char> element_matched(matrix.LhsSize(), 0);
00450   ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
00451 
00452   for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
00453     for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
00454       char matched = matrix.HasEdge(ilhs, irhs);
00455       element_matched[ilhs] |= matched;
00456       matcher_matched[irhs] |= matched;
00457     }
00458   }
00459 
00460   {
00461     const char* sep =
00462         "where the following matchers don't match any elements:\n";
00463     for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
00464       if (matcher_matched[mi])
00465         continue;
00466       result = false;
00467       if (listener->IsInterested()) {
00468         *listener << sep << "matcher #" << mi << ": ";
00469         matcher_describers_[mi]->DescribeTo(listener->stream());
00470         sep = ",\n";
00471       }
00472     }
00473   }
00474 
00475   {
00476     const char* sep =
00477         "where the following elements don't match any matchers:\n";
00478     const char* outer_sep = "";
00479     if (!result) {
00480       outer_sep = "\nand ";
00481     }
00482     for (size_t ei = 0; ei < element_matched.size(); ++ei) {
00483       if (element_matched[ei])
00484         continue;
00485       result = false;
00486       if (listener->IsInterested()) {
00487         *listener << outer_sep << sep << "element #" << ei << ": "
00488                   << element_printouts[ei];
00489         sep = ",\n";
00490         outer_sep = "";
00491       }
00492     }
00493   }
00494   return result;
00495 }
00496 
00497 }  // namespace internal
00498 }  // namespace testing


ros_opcua_impl_freeopcua
Author(s): Denis Štogl
autogenerated on Sat Jun 8 2019 18:24:41