gen_gtest_pred_impl.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 #
00003 # Copyright 2006, Google Inc.
00004 # All rights reserved.
00005 #
00006 # Redistribution and use in source and binary forms, with or without
00007 # modification, are permitted provided that the following conditions are
00008 # met:
00009 #
00010 #     * Redistributions of source code must retain the above copyright
00011 # notice, this list of conditions and the following disclaimer.
00012 #     * Redistributions in binary form must reproduce the above
00013 # copyright notice, this list of conditions and the following disclaimer
00014 # in the documentation and/or other materials provided with the
00015 # distribution.
00016 #     * Neither the name of Google Inc. nor the names of its
00017 # contributors may be used to endorse or promote products derived from
00018 # this software without specific prior written permission.
00019 #
00020 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00021 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00022 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00023 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00024 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00025 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00026 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00027 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00028 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00029 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00030 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00031 
00032 """gen_gtest_pred_impl.py v0.1
00033 
00034 Generates the implementation of Google Test predicate assertions and
00035 accompanying tests.
00036 
00037 Usage:
00038 
00039   gen_gtest_pred_impl.py MAX_ARITY
00040 
00041 where MAX_ARITY is a positive integer.
00042 
00043 The command generates the implementation of up-to MAX_ARITY-ary
00044 predicate assertions, and writes it to file gtest_pred_impl.h in the
00045 directory where the script is.  It also generates the accompanying
00046 unit test in file gtest_pred_impl_unittest.cc.
00047 """
00048 
00049 __author__ = 'wan@google.com (Zhanyong Wan)'
00050 
00051 import os
00052 import sys
00053 import time
00054 
00055 # Where this script is.
00056 SCRIPT_DIR = os.path.dirname(sys.argv[0])
00057 
00058 # Where to store the generated header.
00059 HEADER = os.path.join(SCRIPT_DIR, '../include/gtest/gtest_pred_impl.h')
00060 
00061 # Where to store the generated unit test.
00062 UNIT_TEST = os.path.join(SCRIPT_DIR, '../test/gtest_pred_impl_unittest.cc')
00063 
00064 
00065 def HeaderPreamble(n):
00066   """Returns the preamble for the header file.
00067 
00068   Args:
00069     n:  the maximum arity of the predicate macros to be generated.
00070   """
00071 
00072   # A map that defines the values used in the preamble template.
00073   DEFS = {
00074     'today' : time.strftime('%m/%d/%Y'),
00075     'year' : time.strftime('%Y'),
00076     'command' : '%s %s' % (os.path.basename(sys.argv[0]), n),
00077     'n' : n
00078     }
00079 
00080   return (
00081 """// Copyright 2006, Google Inc.
00082 // All rights reserved.
00083 //
00084 // Redistribution and use in source and binary forms, with or without
00085 // modification, are permitted provided that the following conditions are
00086 // met:
00087 //
00088 //     * Redistributions of source code must retain the above copyright
00089 // notice, this list of conditions and the following disclaimer.
00090 //     * Redistributions in binary form must reproduce the above
00091 // copyright notice, this list of conditions and the following disclaimer
00092 // in the documentation and/or other materials provided with the
00093 // distribution.
00094 //     * Neither the name of Google Inc. nor the names of its
00095 // contributors may be used to endorse or promote products derived from
00096 // this software without specific prior written permission.
00097 //
00098 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00099 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00100 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00101 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00102 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00103 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00104 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00105 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00106 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00107 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00108 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00109 
00110 // This file is AUTOMATICALLY GENERATED on %(today)s by command
00111 // '%(command)s'.  DO NOT EDIT BY HAND!
00112 //
00113 // Implements a family of generic predicate assertion macros.
00114 
00115 #ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
00116 #define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
00117 
00118 // Makes sure this header is not included before gtest.h.
00119 #ifndef GTEST_INCLUDE_GTEST_GTEST_H_
00120 # error Do not include gtest_pred_impl.h directly.  Include gtest.h instead.
00121 #endif  // GTEST_INCLUDE_GTEST_GTEST_H_
00122 
00123 // This header implements a family of generic predicate assertion
00124 // macros:
00125 //
00126 //   ASSERT_PRED_FORMAT1(pred_format, v1)
00127 //   ASSERT_PRED_FORMAT2(pred_format, v1, v2)
00128 //   ...
00129 //
00130 // where pred_format is a function or functor that takes n (in the
00131 // case of ASSERT_PRED_FORMATn) values and their source expression
00132 // text, and returns a testing::AssertionResult.  See the definition
00133 // of ASSERT_EQ in gtest.h for an example.
00134 //
00135 // If you don't care about formatting, you can use the more
00136 // restrictive version:
00137 //
00138 //   ASSERT_PRED1(pred, v1)
00139 //   ASSERT_PRED2(pred, v1, v2)
00140 //   ...
00141 //
00142 // where pred is an n-ary function or functor that returns bool,
00143 // and the values v1, v2, ..., must support the << operator for
00144 // streaming to std::ostream.
00145 //
00146 // We also define the EXPECT_* variations.
00147 //
00148 // For now we only support predicates whose arity is at most %(n)s.
00149 // Please email googletestframework@googlegroups.com if you need
00150 // support for higher arities.
00151 
00152 // GTEST_ASSERT_ is the basic statement to which all of the assertions
00153 // in this file reduce.  Don't use this in your code.
00154 
00155 #define GTEST_ASSERT_(expression, on_failure) \\
00156   GTEST_AMBIGUOUS_ELSE_BLOCKER_ \\
00157   if (const ::testing::AssertionResult gtest_ar = (expression)) \\
00158     ; \\
00159   else \\
00160     on_failure(gtest_ar.failure_message())
00161 """ % DEFS)
00162 
00163 
00164 def Arity(n):
00165   """Returns the English name of the given arity."""
00166 
00167   if n < 0:
00168     return None
00169   elif n <= 3:
00170     return ['nullary', 'unary', 'binary', 'ternary'][n]
00171   else:
00172     return '%s-ary' % n
00173 
00174 
00175 def Title(word):
00176   """Returns the given word in title case.  The difference between
00177   this and string's title() method is that Title('4-ary') is '4-ary'
00178   while '4-ary'.title() is '4-Ary'."""
00179 
00180   return word[0].upper() + word[1:]
00181 
00182 
00183 def OneTo(n):
00184   """Returns the list [1, 2, 3, ..., n]."""
00185 
00186   return range(1, n + 1)
00187 
00188 
00189 def Iter(n, format, sep=''):
00190   """Given a positive integer n, a format string that contains 0 or
00191   more '%s' format specs, and optionally a separator string, returns
00192   the join of n strings, each formatted with the format string on an
00193   iterator ranged from 1 to n.
00194 
00195   Example:
00196 
00197   Iter(3, 'v%s', sep=', ') returns 'v1, v2, v3'.
00198   """
00199 
00200   # How many '%s' specs are in format?
00201   spec_count = len(format.split('%s')) - 1
00202   return sep.join([format % (spec_count * (i,)) for i in OneTo(n)])
00203 
00204 
00205 def ImplementationForArity(n):
00206   """Returns the implementation of n-ary predicate assertions."""
00207 
00208   # A map the defines the values used in the implementation template.
00209   DEFS = {
00210     'n' : str(n),
00211     'vs' : Iter(n, 'v%s', sep=', '),
00212     'vts' : Iter(n, '#v%s', sep=', '),
00213     'arity' : Arity(n),
00214     'Arity' : Title(Arity(n))
00215     }
00216 
00217   impl = """
00218 
00219 // Helper function for implementing {EXPECT|ASSERT}_PRED%(n)s.  Don't use
00220 // this in your code.
00221 template <typename Pred""" % DEFS
00222 
00223   impl += Iter(n, """,
00224           typename T%s""")
00225 
00226   impl += """>
00227 AssertionResult AssertPred%(n)sHelper(const char* pred_text""" % DEFS
00228 
00229   impl += Iter(n, """,
00230                                   const char* e%s""")
00231 
00232   impl += """,
00233                                   Pred pred"""
00234 
00235   impl += Iter(n, """,
00236                                   const T%s& v%s""")
00237 
00238   impl += """) {
00239   if (pred(%(vs)s)) return AssertionSuccess();
00240 
00241 """ % DEFS
00242 
00243   impl += '  return AssertionFailure() << pred_text << "("'
00244 
00245   impl += Iter(n, """
00246                             << e%s""", sep=' << ", "')
00247 
00248   impl += ' << ") evaluates to false, where"'
00249 
00250   impl += Iter(n, """
00251                             << "\\n" << e%s << " evaluates to " << v%s""")
00252 
00253   impl += """;
00254 }
00255 
00256 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
00257 // Don't use this in your code.
00258 #define GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, on_failure)\\
00259   GTEST_ASSERT_(pred_format(%(vts)s, %(vs)s), \\
00260                 on_failure)
00261 
00262 // Internal macro for implementing {EXPECT|ASSERT}_PRED%(n)s.  Don't use
00263 // this in your code.
00264 #define GTEST_PRED%(n)s_(pred, %(vs)s, on_failure)\\
00265   GTEST_ASSERT_(::testing::AssertPred%(n)sHelper(#pred""" % DEFS
00266 
00267   impl += Iter(n, """, \\
00268                                              #v%s""")
00269 
00270   impl += """, \\
00271                                              pred"""
00272 
00273   impl += Iter(n, """, \\
00274                                              v%s""")
00275 
00276   impl += """), on_failure)
00277 
00278 // %(Arity)s predicate assertion macros.
00279 #define EXPECT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
00280   GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_NONFATAL_FAILURE_)
00281 #define EXPECT_PRED%(n)s(pred, %(vs)s) \\
00282   GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_NONFATAL_FAILURE_)
00283 #define ASSERT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
00284   GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_FATAL_FAILURE_)
00285 #define ASSERT_PRED%(n)s(pred, %(vs)s) \\
00286   GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_FATAL_FAILURE_)
00287 
00288 """ % DEFS
00289 
00290   return impl
00291 
00292 
00293 def HeaderPostamble():
00294   """Returns the postamble for the header file."""
00295 
00296   return """
00297 
00298 #endif  // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
00299 """
00300 
00301 
00302 def GenerateFile(path, content):
00303   """Given a file path and a content string, overwrites it with the
00304   given content."""
00305 
00306   print 'Updating file %s . . .' % path
00307 
00308   f = file(path, 'w+')
00309   print >>f, content,
00310   f.close()
00311 
00312   print 'File %s has been updated.' % path
00313 
00314 
00315 def GenerateHeader(n):
00316   """Given the maximum arity n, updates the header file that implements
00317   the predicate assertions."""
00318 
00319   GenerateFile(HEADER,
00320                HeaderPreamble(n)
00321                + ''.join([ImplementationForArity(i) for i in OneTo(n)])
00322                + HeaderPostamble())
00323 
00324 
00325 def UnitTestPreamble():
00326   """Returns the preamble for the unit test file."""
00327 
00328   # A map that defines the values used in the preamble template.
00329   DEFS = {
00330     'today' : time.strftime('%m/%d/%Y'),
00331     'year' : time.strftime('%Y'),
00332     'command' : '%s %s' % (os.path.basename(sys.argv[0]), sys.argv[1]),
00333     }
00334 
00335   return (
00336 """// Copyright 2006, Google Inc.
00337 // All rights reserved.
00338 //
00339 // Redistribution and use in source and binary forms, with or without
00340 // modification, are permitted provided that the following conditions are
00341 // met:
00342 //
00343 //     * Redistributions of source code must retain the above copyright
00344 // notice, this list of conditions and the following disclaimer.
00345 //     * Redistributions in binary form must reproduce the above
00346 // copyright notice, this list of conditions and the following disclaimer
00347 // in the documentation and/or other materials provided with the
00348 // distribution.
00349 //     * Neither the name of Google Inc. nor the names of its
00350 // contributors may be used to endorse or promote products derived from
00351 // this software without specific prior written permission.
00352 //
00353 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00354 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00355 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00356 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00357 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00358 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00359 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00360 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00361 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00362 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00363 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00364 
00365 // This file is AUTOMATICALLY GENERATED on %(today)s by command
00366 // '%(command)s'.  DO NOT EDIT BY HAND!
00367 
00368 // Regression test for gtest_pred_impl.h
00369 //
00370 // This file is generated by a script and quite long.  If you intend to
00371 // learn how Google Test works by reading its unit tests, read
00372 // gtest_unittest.cc instead.
00373 //
00374 // This is intended as a regression test for the Google Test predicate
00375 // assertions.  We compile it as part of the gtest_unittest target
00376 // only to keep the implementation tidy and compact, as it is quite
00377 // involved to set up the stage for testing Google Test using Google
00378 // Test itself.
00379 //
00380 // Currently, gtest_unittest takes ~11 seconds to run in the testing
00381 // daemon.  In the future, if it grows too large and needs much more
00382 // time to finish, we should consider separating this file into a
00383 // stand-alone regression test.
00384 
00385 #include <iostream>
00386 
00387 #include "gtest/gtest.h"
00388 #include "gtest/gtest-spi.h"
00389 
00390 // A user-defined data type.
00391 struct Bool {
00392   explicit Bool(int val) : value(val != 0) {}
00393 
00394   bool operator>(int n) const { return value > Bool(n).value; }
00395 
00396   Bool operator+(const Bool& rhs) const { return Bool(value + rhs.value); }
00397 
00398   bool operator==(const Bool& rhs) const { return value == rhs.value; }
00399 
00400   bool value;
00401 };
00402 
00403 // Enables Bool to be used in assertions.
00404 std::ostream& operator<<(std::ostream& os, const Bool& x) {
00405   return os << (x.value ? "true" : "false");
00406 }
00407 
00408 """ % DEFS)
00409 
00410 
00411 def TestsForArity(n):
00412   """Returns the tests for n-ary predicate assertions."""
00413 
00414   # A map that defines the values used in the template for the tests.
00415   DEFS = {
00416     'n' : n,
00417     'es' : Iter(n, 'e%s', sep=', '),
00418     'vs' : Iter(n, 'v%s', sep=', '),
00419     'vts' : Iter(n, '#v%s', sep=', '),
00420     'tvs' : Iter(n, 'T%s v%s', sep=', '),
00421     'int_vs' : Iter(n, 'int v%s', sep=', '),
00422     'Bool_vs' : Iter(n, 'Bool v%s', sep=', '),
00423     'types' : Iter(n, 'typename T%s', sep=', '),
00424     'v_sum' : Iter(n, 'v%s', sep=' + '),
00425     'arity' : Arity(n),
00426     'Arity' : Title(Arity(n)),
00427     }
00428 
00429   tests = (
00430 """// Sample functions/functors for testing %(arity)s predicate assertions.
00431 
00432 // A %(arity)s predicate function.
00433 template <%(types)s>
00434 bool PredFunction%(n)s(%(tvs)s) {
00435   return %(v_sum)s > 0;
00436 }
00437 
00438 // The following two functions are needed to circumvent a bug in
00439 // gcc 2.95.3, which sometimes has problem with the above template
00440 // function.
00441 bool PredFunction%(n)sInt(%(int_vs)s) {
00442   return %(v_sum)s > 0;
00443 }
00444 bool PredFunction%(n)sBool(%(Bool_vs)s) {
00445   return %(v_sum)s > 0;
00446 }
00447 """ % DEFS)
00448 
00449   tests += """
00450 // A %(arity)s predicate functor.
00451 struct PredFunctor%(n)s {
00452   template <%(types)s>
00453   bool operator()(""" % DEFS
00454 
00455   tests += Iter(n, 'const T%s& v%s', sep=""",
00456                   """)
00457 
00458   tests += """) {
00459     return %(v_sum)s > 0;
00460   }
00461 };
00462 """ % DEFS
00463 
00464   tests += """
00465 // A %(arity)s predicate-formatter function.
00466 template <%(types)s>
00467 testing::AssertionResult PredFormatFunction%(n)s(""" % DEFS
00468 
00469   tests += Iter(n, 'const char* e%s', sep=""",
00470                                              """)
00471 
00472   tests += Iter(n, """,
00473                                              const T%s& v%s""")
00474 
00475   tests += """) {
00476   if (PredFunction%(n)s(%(vs)s))
00477     return testing::AssertionSuccess();
00478 
00479   return testing::AssertionFailure()
00480       << """ % DEFS
00481 
00482   tests += Iter(n, 'e%s', sep=' << " + " << ')
00483 
00484   tests += """
00485       << " is expected to be positive, but evaluates to "
00486       << %(v_sum)s << ".";
00487 }
00488 """ % DEFS
00489 
00490   tests += """
00491 // A %(arity)s predicate-formatter functor.
00492 struct PredFormatFunctor%(n)s {
00493   template <%(types)s>
00494   testing::AssertionResult operator()(""" % DEFS
00495 
00496   tests += Iter(n, 'const char* e%s', sep=""",
00497                                       """)
00498 
00499   tests += Iter(n, """,
00500                                       const T%s& v%s""")
00501 
00502   tests += """) const {
00503     return PredFormatFunction%(n)s(%(es)s, %(vs)s);
00504   }
00505 };
00506 """ % DEFS
00507 
00508   tests += """
00509 // Tests for {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
00510 
00511 class Predicate%(n)sTest : public testing::Test {
00512  protected:
00513   virtual void SetUp() {
00514     expected_to_finish_ = true;
00515     finished_ = false;""" % DEFS
00516 
00517   tests += """
00518     """ + Iter(n, 'n%s_ = ') + """0;
00519   }
00520 """
00521 
00522   tests += """
00523   virtual void TearDown() {
00524     // Verifies that each of the predicate's arguments was evaluated
00525     // exactly once."""
00526 
00527   tests += ''.join(["""
00528     EXPECT_EQ(1, n%s_) <<
00529         "The predicate assertion didn't evaluate argument %s "
00530         "exactly once.";""" % (i, i + 1) for i in OneTo(n)])
00531 
00532   tests += """
00533 
00534     // Verifies that the control flow in the test function is expected.
00535     if (expected_to_finish_ && !finished_) {
00536       FAIL() << "The predicate assertion unexpactedly aborted the test.";
00537     } else if (!expected_to_finish_ && finished_) {
00538       FAIL() << "The failed predicate assertion didn't abort the test "
00539                 "as expected.";
00540     }
00541   }
00542 
00543   // true iff the test function is expected to run to finish.
00544   static bool expected_to_finish_;
00545 
00546   // true iff the test function did run to finish.
00547   static bool finished_;
00548 """ % DEFS
00549 
00550   tests += Iter(n, """
00551   static int n%s_;""")
00552 
00553   tests += """
00554 };
00555 
00556 bool Predicate%(n)sTest::expected_to_finish_;
00557 bool Predicate%(n)sTest::finished_;
00558 """ % DEFS
00559 
00560   tests += Iter(n, """int Predicate%%(n)sTest::n%s_;
00561 """) % DEFS
00562 
00563   tests += """
00564 typedef Predicate%(n)sTest EXPECT_PRED_FORMAT%(n)sTest;
00565 typedef Predicate%(n)sTest ASSERT_PRED_FORMAT%(n)sTest;
00566 typedef Predicate%(n)sTest EXPECT_PRED%(n)sTest;
00567 typedef Predicate%(n)sTest ASSERT_PRED%(n)sTest;
00568 """ % DEFS
00569 
00570   def GenTest(use_format, use_assert, expect_failure,
00571               use_functor, use_user_type):
00572     """Returns the test for a predicate assertion macro.
00573 
00574     Args:
00575       use_format:     true iff the assertion is a *_PRED_FORMAT*.
00576       use_assert:     true iff the assertion is a ASSERT_*.
00577       expect_failure: true iff the assertion is expected to fail.
00578       use_functor:    true iff the first argument of the assertion is
00579                       a functor (as opposed to a function)
00580       use_user_type:  true iff the predicate functor/function takes
00581                       argument(s) of a user-defined type.
00582 
00583     Example:
00584 
00585       GenTest(1, 0, 0, 1, 0) returns a test that tests the behavior
00586       of a successful EXPECT_PRED_FORMATn() that takes a functor
00587       whose arguments have built-in types."""
00588 
00589     if use_assert:
00590       assrt = 'ASSERT'  # 'assert' is reserved, so we cannot use
00591                         # that identifier here.
00592     else:
00593       assrt = 'EXPECT'
00594 
00595     assertion = assrt + '_PRED'
00596 
00597     if use_format:
00598       pred_format = 'PredFormat'
00599       assertion += '_FORMAT'
00600     else:
00601       pred_format = 'Pred'
00602 
00603     assertion += '%(n)s' % DEFS
00604 
00605     if use_functor:
00606       pred_format_type = 'functor'
00607       pred_format += 'Functor%(n)s()'
00608     else:
00609       pred_format_type = 'function'
00610       pred_format += 'Function%(n)s'
00611       if not use_format:
00612         if use_user_type:
00613           pred_format += 'Bool'
00614         else:
00615           pred_format += 'Int'
00616 
00617     test_name = pred_format_type.title()
00618 
00619     if use_user_type:
00620       arg_type = 'user-defined type (Bool)'
00621       test_name += 'OnUserType'
00622       if expect_failure:
00623         arg = 'Bool(n%s_++)'
00624       else:
00625         arg = 'Bool(++n%s_)'
00626     else:
00627       arg_type = 'built-in type (int)'
00628       test_name += 'OnBuiltInType'
00629       if expect_failure:
00630         arg = 'n%s_++'
00631       else:
00632         arg = '++n%s_'
00633 
00634     if expect_failure:
00635       successful_or_failed = 'failed'
00636       expected_or_not = 'expected.'
00637       test_name +=  'Failure'
00638     else:
00639       successful_or_failed = 'successful'
00640       expected_or_not = 'UNEXPECTED!'
00641       test_name +=  'Success'
00642 
00643     # A map that defines the values used in the test template.
00644     defs = DEFS.copy()
00645     defs.update({
00646       'assert' : assrt,
00647       'assertion' : assertion,
00648       'test_name' : test_name,
00649       'pf_type' : pred_format_type,
00650       'pf' : pred_format,
00651       'arg_type' : arg_type,
00652       'arg' : arg,
00653       'successful' : successful_or_failed,
00654       'expected' : expected_or_not,
00655       })
00656 
00657     test = """
00658 // Tests a %(successful)s %(assertion)s where the
00659 // predicate-formatter is a %(pf_type)s on a %(arg_type)s.
00660 TEST_F(%(assertion)sTest, %(test_name)s) {""" % defs
00661 
00662     indent = (len(assertion) + 3)*' '
00663     extra_indent = ''
00664 
00665     if expect_failure:
00666       extra_indent = '  '
00667       if use_assert:
00668         test += """
00669   expected_to_finish_ = false;
00670   EXPECT_FATAL_FAILURE({  // NOLINT"""
00671       else:
00672         test += """
00673   EXPECT_NONFATAL_FAILURE({  // NOLINT"""
00674 
00675     test += '\n' + extra_indent + """  %(assertion)s(%(pf)s""" % defs
00676 
00677     test = test % defs
00678     test += Iter(n, ',\n' + indent + extra_indent + '%(arg)s' % defs)
00679     test += ');\n' + extra_indent + '  finished_ = true;\n'
00680 
00681     if expect_failure:
00682       test += '  }, "");\n'
00683 
00684     test += '}\n'
00685     return test
00686 
00687   # Generates tests for all 2**6 = 64 combinations.
00688   tests += ''.join([GenTest(use_format, use_assert, expect_failure,
00689                             use_functor, use_user_type)
00690                     for use_format in [0, 1]
00691                     for use_assert in [0, 1]
00692                     for expect_failure in [0, 1]
00693                     for use_functor in [0, 1]
00694                     for use_user_type in [0, 1]
00695                     ])
00696 
00697   return tests
00698 
00699 
00700 def UnitTestPostamble():
00701   """Returns the postamble for the tests."""
00702 
00703   return ''
00704 
00705 
00706 def GenerateUnitTest(n):
00707   """Returns the tests for up-to n-ary predicate assertions."""
00708 
00709   GenerateFile(UNIT_TEST,
00710                UnitTestPreamble()
00711                + ''.join([TestsForArity(i) for i in OneTo(n)])
00712                + UnitTestPostamble())
00713 
00714 
00715 def _Main():
00716   """The entry point of the script.  Generates the header file and its
00717   unit test."""
00718 
00719   if len(sys.argv) != 2:
00720     print __doc__
00721     print 'Author: ' + __author__
00722     sys.exit(1)
00723 
00724   n = int(sys.argv[1])
00725   GenerateHeader(n)
00726   GenerateUnitTest(n)
00727 
00728 
00729 if __name__ == '__main__':
00730   _Main()


rc_visard_driver
Author(s): Heiko Hirschmueller , Christian Emmerich , Felix Ruess
autogenerated on Thu Jun 6 2019 20:43:02