media/webrtc/trunk/testing/gtest/scripts/gen_gtest_pred_impl.py

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/media/webrtc/trunk/testing/gtest/scripts/gen_gtest_pred_impl.py	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,730 @@
     1.4 +#!/usr/bin/env python
     1.5 +#
     1.6 +# Copyright 2006, Google Inc.
     1.7 +# All rights reserved.
     1.8 +#
     1.9 +# Redistribution and use in source and binary forms, with or without
    1.10 +# modification, are permitted provided that the following conditions are
    1.11 +# met:
    1.12 +#
    1.13 +#     * Redistributions of source code must retain the above copyright
    1.14 +# notice, this list of conditions and the following disclaimer.
    1.15 +#     * Redistributions in binary form must reproduce the above
    1.16 +# copyright notice, this list of conditions and the following disclaimer
    1.17 +# in the documentation and/or other materials provided with the
    1.18 +# distribution.
    1.19 +#     * Neither the name of Google Inc. nor the names of its
    1.20 +# contributors may be used to endorse or promote products derived from
    1.21 +# this software without specific prior written permission.
    1.22 +#
    1.23 +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    1.24 +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    1.25 +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    1.26 +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    1.27 +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    1.28 +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    1.29 +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    1.30 +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    1.31 +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    1.32 +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    1.33 +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    1.34 +
    1.35 +"""gen_gtest_pred_impl.py v0.1
    1.36 +
    1.37 +Generates the implementation of Google Test predicate assertions and
    1.38 +accompanying tests.
    1.39 +
    1.40 +Usage:
    1.41 +
    1.42 +  gen_gtest_pred_impl.py MAX_ARITY
    1.43 +
    1.44 +where MAX_ARITY is a positive integer.
    1.45 +
    1.46 +The command generates the implementation of up-to MAX_ARITY-ary
    1.47 +predicate assertions, and writes it to file gtest_pred_impl.h in the
    1.48 +directory where the script is.  It also generates the accompanying
    1.49 +unit test in file gtest_pred_impl_unittest.cc.
    1.50 +"""
    1.51 +
    1.52 +__author__ = 'wan@google.com (Zhanyong Wan)'
    1.53 +
    1.54 +import os
    1.55 +import sys
    1.56 +import time
    1.57 +
    1.58 +# Where this script is.
    1.59 +SCRIPT_DIR = os.path.dirname(sys.argv[0])
    1.60 +
    1.61 +# Where to store the generated header.
    1.62 +HEADER = os.path.join(SCRIPT_DIR, '../include/gtest/gtest_pred_impl.h')
    1.63 +
    1.64 +# Where to store the generated unit test.
    1.65 +UNIT_TEST = os.path.join(SCRIPT_DIR, '../test/gtest_pred_impl_unittest.cc')
    1.66 +
    1.67 +
    1.68 +def HeaderPreamble(n):
    1.69 +  """Returns the preamble for the header file.
    1.70 +
    1.71 +  Args:
    1.72 +    n:  the maximum arity of the predicate macros to be generated.
    1.73 +  """
    1.74 +
    1.75 +  # A map that defines the values used in the preamble template.
    1.76 +  DEFS = {
    1.77 +    'today' : time.strftime('%m/%d/%Y'),
    1.78 +    'year' : time.strftime('%Y'),
    1.79 +    'command' : '%s %s' % (os.path.basename(sys.argv[0]), n),
    1.80 +    'n' : n
    1.81 +    }
    1.82 +
    1.83 +  return (
    1.84 +"""// Copyright 2006, Google Inc.
    1.85 +// All rights reserved.
    1.86 +//
    1.87 +// Redistribution and use in source and binary forms, with or without
    1.88 +// modification, are permitted provided that the following conditions are
    1.89 +// met:
    1.90 +//
    1.91 +//     * Redistributions of source code must retain the above copyright
    1.92 +// notice, this list of conditions and the following disclaimer.
    1.93 +//     * Redistributions in binary form must reproduce the above
    1.94 +// copyright notice, this list of conditions and the following disclaimer
    1.95 +// in the documentation and/or other materials provided with the
    1.96 +// distribution.
    1.97 +//     * Neither the name of Google Inc. nor the names of its
    1.98 +// contributors may be used to endorse or promote products derived from
    1.99 +// this software without specific prior written permission.
   1.100 +//
   1.101 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   1.102 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   1.103 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   1.104 +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
   1.105 +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   1.106 +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   1.107 +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
   1.108 +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
   1.109 +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   1.110 +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
   1.111 +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   1.112 +
   1.113 +// This file is AUTOMATICALLY GENERATED on %(today)s by command
   1.114 +// '%(command)s'.  DO NOT EDIT BY HAND!
   1.115 +//
   1.116 +// Implements a family of generic predicate assertion macros.
   1.117 +
   1.118 +#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
   1.119 +#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
   1.120 +
   1.121 +// Makes sure this header is not included before gtest.h.
   1.122 +#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
   1.123 +# error Do not include gtest_pred_impl.h directly.  Include gtest.h instead.
   1.124 +#endif  // GTEST_INCLUDE_GTEST_GTEST_H_
   1.125 +
   1.126 +// This header implements a family of generic predicate assertion
   1.127 +// macros:
   1.128 +//
   1.129 +//   ASSERT_PRED_FORMAT1(pred_format, v1)
   1.130 +//   ASSERT_PRED_FORMAT2(pred_format, v1, v2)
   1.131 +//   ...
   1.132 +//
   1.133 +// where pred_format is a function or functor that takes n (in the
   1.134 +// case of ASSERT_PRED_FORMATn) values and their source expression
   1.135 +// text, and returns a testing::AssertionResult.  See the definition
   1.136 +// of ASSERT_EQ in gtest.h for an example.
   1.137 +//
   1.138 +// If you don't care about formatting, you can use the more
   1.139 +// restrictive version:
   1.140 +//
   1.141 +//   ASSERT_PRED1(pred, v1)
   1.142 +//   ASSERT_PRED2(pred, v1, v2)
   1.143 +//   ...
   1.144 +//
   1.145 +// where pred is an n-ary function or functor that returns bool,
   1.146 +// and the values v1, v2, ..., must support the << operator for
   1.147 +// streaming to std::ostream.
   1.148 +//
   1.149 +// We also define the EXPECT_* variations.
   1.150 +//
   1.151 +// For now we only support predicates whose arity is at most %(n)s.
   1.152 +// Please email googletestframework@googlegroups.com if you need
   1.153 +// support for higher arities.
   1.154 +
   1.155 +// GTEST_ASSERT_ is the basic statement to which all of the assertions
   1.156 +// in this file reduce.  Don't use this in your code.
   1.157 +
   1.158 +#define GTEST_ASSERT_(expression, on_failure) \\
   1.159 +  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \\
   1.160 +  if (const ::testing::AssertionResult gtest_ar = (expression)) \\
   1.161 +    ; \\
   1.162 +  else \\
   1.163 +    on_failure(gtest_ar.failure_message())
   1.164 +""" % DEFS)
   1.165 +
   1.166 +
   1.167 +def Arity(n):
   1.168 +  """Returns the English name of the given arity."""
   1.169 +
   1.170 +  if n < 0:
   1.171 +    return None
   1.172 +  elif n <= 3:
   1.173 +    return ['nullary', 'unary', 'binary', 'ternary'][n]
   1.174 +  else:
   1.175 +    return '%s-ary' % n
   1.176 +
   1.177 +
   1.178 +def Title(word):
   1.179 +  """Returns the given word in title case.  The difference between
   1.180 +  this and string's title() method is that Title('4-ary') is '4-ary'
   1.181 +  while '4-ary'.title() is '4-Ary'."""
   1.182 +
   1.183 +  return word[0].upper() + word[1:]
   1.184 +
   1.185 +
   1.186 +def OneTo(n):
   1.187 +  """Returns the list [1, 2, 3, ..., n]."""
   1.188 +
   1.189 +  return range(1, n + 1)
   1.190 +
   1.191 +
   1.192 +def Iter(n, format, sep=''):
   1.193 +  """Given a positive integer n, a format string that contains 0 or
   1.194 +  more '%s' format specs, and optionally a separator string, returns
   1.195 +  the join of n strings, each formatted with the format string on an
   1.196 +  iterator ranged from 1 to n.
   1.197 +
   1.198 +  Example:
   1.199 +
   1.200 +  Iter(3, 'v%s', sep=', ') returns 'v1, v2, v3'.
   1.201 +  """
   1.202 +
   1.203 +  # How many '%s' specs are in format?
   1.204 +  spec_count = len(format.split('%s')) - 1
   1.205 +  return sep.join([format % (spec_count * (i,)) for i in OneTo(n)])
   1.206 +
   1.207 +
   1.208 +def ImplementationForArity(n):
   1.209 +  """Returns the implementation of n-ary predicate assertions."""
   1.210 +
   1.211 +  # A map the defines the values used in the implementation template.
   1.212 +  DEFS = {
   1.213 +    'n' : str(n),
   1.214 +    'vs' : Iter(n, 'v%s', sep=', '),
   1.215 +    'vts' : Iter(n, '#v%s', sep=', '),
   1.216 +    'arity' : Arity(n),
   1.217 +    'Arity' : Title(Arity(n))
   1.218 +    }
   1.219 +
   1.220 +  impl = """
   1.221 +
   1.222 +// Helper function for implementing {EXPECT|ASSERT}_PRED%(n)s.  Don't use
   1.223 +// this in your code.
   1.224 +template <typename Pred""" % DEFS
   1.225 +
   1.226 +  impl += Iter(n, """,
   1.227 +          typename T%s""")
   1.228 +
   1.229 +  impl += """>
   1.230 +AssertionResult AssertPred%(n)sHelper(const char* pred_text""" % DEFS
   1.231 +
   1.232 +  impl += Iter(n, """,
   1.233 +                                  const char* e%s""")
   1.234 +
   1.235 +  impl += """,
   1.236 +                                  Pred pred"""
   1.237 +
   1.238 +  impl += Iter(n, """,
   1.239 +                                  const T%s& v%s""")
   1.240 +
   1.241 +  impl += """) {
   1.242 +  if (pred(%(vs)s)) return AssertionSuccess();
   1.243 +
   1.244 +""" % DEFS
   1.245 +
   1.246 +  impl += '  return AssertionFailure() << pred_text << "("'
   1.247 +
   1.248 +  impl += Iter(n, """
   1.249 +                            << e%s""", sep=' << ", "')
   1.250 +
   1.251 +  impl += ' << ") evaluates to false, where"'
   1.252 +
   1.253 +  impl += Iter(n, """
   1.254 +                            << "\\n" << e%s << " evaluates to " << v%s""")
   1.255 +
   1.256 +  impl += """;
   1.257 +}
   1.258 +
   1.259 +// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
   1.260 +// Don't use this in your code.
   1.261 +#define GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, on_failure)\\
   1.262 +  GTEST_ASSERT_(pred_format(%(vts)s, %(vs)s), \\
   1.263 +                on_failure)
   1.264 +
   1.265 +// Internal macro for implementing {EXPECT|ASSERT}_PRED%(n)s.  Don't use
   1.266 +// this in your code.
   1.267 +#define GTEST_PRED%(n)s_(pred, %(vs)s, on_failure)\\
   1.268 +  GTEST_ASSERT_(::testing::AssertPred%(n)sHelper(#pred""" % DEFS
   1.269 +
   1.270 +  impl += Iter(n, """, \\
   1.271 +                                             #v%s""")
   1.272 +
   1.273 +  impl += """, \\
   1.274 +                                             pred"""
   1.275 +
   1.276 +  impl += Iter(n, """, \\
   1.277 +                                             v%s""")
   1.278 +
   1.279 +  impl += """), on_failure)
   1.280 +
   1.281 +// %(Arity)s predicate assertion macros.
   1.282 +#define EXPECT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
   1.283 +  GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_NONFATAL_FAILURE_)
   1.284 +#define EXPECT_PRED%(n)s(pred, %(vs)s) \\
   1.285 +  GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_NONFATAL_FAILURE_)
   1.286 +#define ASSERT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
   1.287 +  GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_FATAL_FAILURE_)
   1.288 +#define ASSERT_PRED%(n)s(pred, %(vs)s) \\
   1.289 +  GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_FATAL_FAILURE_)
   1.290 +
   1.291 +""" % DEFS
   1.292 +
   1.293 +  return impl
   1.294 +
   1.295 +
   1.296 +def HeaderPostamble():
   1.297 +  """Returns the postamble for the header file."""
   1.298 +
   1.299 +  return """
   1.300 +
   1.301 +#endif  // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
   1.302 +"""
   1.303 +
   1.304 +
   1.305 +def GenerateFile(path, content):
   1.306 +  """Given a file path and a content string, overwrites it with the
   1.307 +  given content."""
   1.308 +
   1.309 +  print 'Updating file %s . . .' % path
   1.310 +
   1.311 +  f = file(path, 'w+')
   1.312 +  print >>f, content,
   1.313 +  f.close()
   1.314 +
   1.315 +  print 'File %s has been updated.' % path
   1.316 +
   1.317 +
   1.318 +def GenerateHeader(n):
   1.319 +  """Given the maximum arity n, updates the header file that implements
   1.320 +  the predicate assertions."""
   1.321 +
   1.322 +  GenerateFile(HEADER,
   1.323 +               HeaderPreamble(n)
   1.324 +               + ''.join([ImplementationForArity(i) for i in OneTo(n)])
   1.325 +               + HeaderPostamble())
   1.326 +
   1.327 +
   1.328 +def UnitTestPreamble():
   1.329 +  """Returns the preamble for the unit test file."""
   1.330 +
   1.331 +  # A map that defines the values used in the preamble template.
   1.332 +  DEFS = {
   1.333 +    'today' : time.strftime('%m/%d/%Y'),
   1.334 +    'year' : time.strftime('%Y'),
   1.335 +    'command' : '%s %s' % (os.path.basename(sys.argv[0]), sys.argv[1]),
   1.336 +    }
   1.337 +
   1.338 +  return (
   1.339 +"""// Copyright 2006, Google Inc.
   1.340 +// All rights reserved.
   1.341 +//
   1.342 +// Redistribution and use in source and binary forms, with or without
   1.343 +// modification, are permitted provided that the following conditions are
   1.344 +// met:
   1.345 +//
   1.346 +//     * Redistributions of source code must retain the above copyright
   1.347 +// notice, this list of conditions and the following disclaimer.
   1.348 +//     * Redistributions in binary form must reproduce the above
   1.349 +// copyright notice, this list of conditions and the following disclaimer
   1.350 +// in the documentation and/or other materials provided with the
   1.351 +// distribution.
   1.352 +//     * Neither the name of Google Inc. nor the names of its
   1.353 +// contributors may be used to endorse or promote products derived from
   1.354 +// this software without specific prior written permission.
   1.355 +//
   1.356 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   1.357 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   1.358 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   1.359 +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
   1.360 +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   1.361 +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   1.362 +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
   1.363 +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
   1.364 +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   1.365 +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
   1.366 +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   1.367 +
   1.368 +// This file is AUTOMATICALLY GENERATED on %(today)s by command
   1.369 +// '%(command)s'.  DO NOT EDIT BY HAND!
   1.370 +
   1.371 +// Regression test for gtest_pred_impl.h
   1.372 +//
   1.373 +// This file is generated by a script and quite long.  If you intend to
   1.374 +// learn how Google Test works by reading its unit tests, read
   1.375 +// gtest_unittest.cc instead.
   1.376 +//
   1.377 +// This is intended as a regression test for the Google Test predicate
   1.378 +// assertions.  We compile it as part of the gtest_unittest target
   1.379 +// only to keep the implementation tidy and compact, as it is quite
   1.380 +// involved to set up the stage for testing Google Test using Google
   1.381 +// Test itself.
   1.382 +//
   1.383 +// Currently, gtest_unittest takes ~11 seconds to run in the testing
   1.384 +// daemon.  In the future, if it grows too large and needs much more
   1.385 +// time to finish, we should consider separating this file into a
   1.386 +// stand-alone regression test.
   1.387 +
   1.388 +#include <iostream>
   1.389 +
   1.390 +#include "gtest/gtest.h"
   1.391 +#include "gtest/gtest-spi.h"
   1.392 +
   1.393 +// A user-defined data type.
   1.394 +struct Bool {
   1.395 +  explicit Bool(int val) : value(val != 0) {}
   1.396 +
   1.397 +  bool operator>(int n) const { return value > Bool(n).value; }
   1.398 +
   1.399 +  Bool operator+(const Bool& rhs) const { return Bool(value + rhs.value); }
   1.400 +
   1.401 +  bool operator==(const Bool& rhs) const { return value == rhs.value; }
   1.402 +
   1.403 +  bool value;
   1.404 +};
   1.405 +
   1.406 +// Enables Bool to be used in assertions.
   1.407 +std::ostream& operator<<(std::ostream& os, const Bool& x) {
   1.408 +  return os << (x.value ? "true" : "false");
   1.409 +}
   1.410 +
   1.411 +""" % DEFS)
   1.412 +
   1.413 +
   1.414 +def TestsForArity(n):
   1.415 +  """Returns the tests for n-ary predicate assertions."""
   1.416 +
   1.417 +  # A map that defines the values used in the template for the tests.
   1.418 +  DEFS = {
   1.419 +    'n' : n,
   1.420 +    'es' : Iter(n, 'e%s', sep=', '),
   1.421 +    'vs' : Iter(n, 'v%s', sep=', '),
   1.422 +    'vts' : Iter(n, '#v%s', sep=', '),
   1.423 +    'tvs' : Iter(n, 'T%s v%s', sep=', '),
   1.424 +    'int_vs' : Iter(n, 'int v%s', sep=', '),
   1.425 +    'Bool_vs' : Iter(n, 'Bool v%s', sep=', '),
   1.426 +    'types' : Iter(n, 'typename T%s', sep=', '),
   1.427 +    'v_sum' : Iter(n, 'v%s', sep=' + '),
   1.428 +    'arity' : Arity(n),
   1.429 +    'Arity' : Title(Arity(n)),
   1.430 +    }
   1.431 +
   1.432 +  tests = (
   1.433 +"""// Sample functions/functors for testing %(arity)s predicate assertions.
   1.434 +
   1.435 +// A %(arity)s predicate function.
   1.436 +template <%(types)s>
   1.437 +bool PredFunction%(n)s(%(tvs)s) {
   1.438 +  return %(v_sum)s > 0;
   1.439 +}
   1.440 +
   1.441 +// The following two functions are needed to circumvent a bug in
   1.442 +// gcc 2.95.3, which sometimes has problem with the above template
   1.443 +// function.
   1.444 +bool PredFunction%(n)sInt(%(int_vs)s) {
   1.445 +  return %(v_sum)s > 0;
   1.446 +}
   1.447 +bool PredFunction%(n)sBool(%(Bool_vs)s) {
   1.448 +  return %(v_sum)s > 0;
   1.449 +}
   1.450 +""" % DEFS)
   1.451 +
   1.452 +  tests += """
   1.453 +// A %(arity)s predicate functor.
   1.454 +struct PredFunctor%(n)s {
   1.455 +  template <%(types)s>
   1.456 +  bool operator()(""" % DEFS
   1.457 +
   1.458 +  tests += Iter(n, 'const T%s& v%s', sep=""",
   1.459 +                  """)
   1.460 +
   1.461 +  tests += """) {
   1.462 +    return %(v_sum)s > 0;
   1.463 +  }
   1.464 +};
   1.465 +""" % DEFS
   1.466 +
   1.467 +  tests += """
   1.468 +// A %(arity)s predicate-formatter function.
   1.469 +template <%(types)s>
   1.470 +testing::AssertionResult PredFormatFunction%(n)s(""" % DEFS
   1.471 +
   1.472 +  tests += Iter(n, 'const char* e%s', sep=""",
   1.473 +                                             """)
   1.474 +
   1.475 +  tests += Iter(n, """,
   1.476 +                                             const T%s& v%s""")
   1.477 +
   1.478 +  tests += """) {
   1.479 +  if (PredFunction%(n)s(%(vs)s))
   1.480 +    return testing::AssertionSuccess();
   1.481 +
   1.482 +  return testing::AssertionFailure()
   1.483 +      << """ % DEFS
   1.484 +
   1.485 +  tests += Iter(n, 'e%s', sep=' << " + " << ')
   1.486 +
   1.487 +  tests += """
   1.488 +      << " is expected to be positive, but evaluates to "
   1.489 +      << %(v_sum)s << ".";
   1.490 +}
   1.491 +""" % DEFS
   1.492 +
   1.493 +  tests += """
   1.494 +// A %(arity)s predicate-formatter functor.
   1.495 +struct PredFormatFunctor%(n)s {
   1.496 +  template <%(types)s>
   1.497 +  testing::AssertionResult operator()(""" % DEFS
   1.498 +
   1.499 +  tests += Iter(n, 'const char* e%s', sep=""",
   1.500 +                                      """)
   1.501 +
   1.502 +  tests += Iter(n, """,
   1.503 +                                      const T%s& v%s""")
   1.504 +
   1.505 +  tests += """) const {
   1.506 +    return PredFormatFunction%(n)s(%(es)s, %(vs)s);
   1.507 +  }
   1.508 +};
   1.509 +""" % DEFS
   1.510 +
   1.511 +  tests += """
   1.512 +// Tests for {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
   1.513 +
   1.514 +class Predicate%(n)sTest : public testing::Test {
   1.515 + protected:
   1.516 +  virtual void SetUp() {
   1.517 +    expected_to_finish_ = true;
   1.518 +    finished_ = false;""" % DEFS
   1.519 +
   1.520 +  tests += """
   1.521 +    """ + Iter(n, 'n%s_ = ') + """0;
   1.522 +  }
   1.523 +"""
   1.524 +
   1.525 +  tests += """
   1.526 +  virtual void TearDown() {
   1.527 +    // Verifies that each of the predicate's arguments was evaluated
   1.528 +    // exactly once."""
   1.529 +
   1.530 +  tests += ''.join(["""
   1.531 +    EXPECT_EQ(1, n%s_) <<
   1.532 +        "The predicate assertion didn't evaluate argument %s "
   1.533 +        "exactly once.";""" % (i, i + 1) for i in OneTo(n)])
   1.534 +
   1.535 +  tests += """
   1.536 +
   1.537 +    // Verifies that the control flow in the test function is expected.
   1.538 +    if (expected_to_finish_ && !finished_) {
   1.539 +      FAIL() << "The predicate assertion unexpactedly aborted the test.";
   1.540 +    } else if (!expected_to_finish_ && finished_) {
   1.541 +      FAIL() << "The failed predicate assertion didn't abort the test "
   1.542 +                "as expected.";
   1.543 +    }
   1.544 +  }
   1.545 +
   1.546 +  // true iff the test function is expected to run to finish.
   1.547 +  static bool expected_to_finish_;
   1.548 +
   1.549 +  // true iff the test function did run to finish.
   1.550 +  static bool finished_;
   1.551 +""" % DEFS
   1.552 +
   1.553 +  tests += Iter(n, """
   1.554 +  static int n%s_;""")
   1.555 +
   1.556 +  tests += """
   1.557 +};
   1.558 +
   1.559 +bool Predicate%(n)sTest::expected_to_finish_;
   1.560 +bool Predicate%(n)sTest::finished_;
   1.561 +""" % DEFS
   1.562 +
   1.563 +  tests += Iter(n, """int Predicate%%(n)sTest::n%s_;
   1.564 +""") % DEFS
   1.565 +
   1.566 +  tests += """
   1.567 +typedef Predicate%(n)sTest EXPECT_PRED_FORMAT%(n)sTest;
   1.568 +typedef Predicate%(n)sTest ASSERT_PRED_FORMAT%(n)sTest;
   1.569 +typedef Predicate%(n)sTest EXPECT_PRED%(n)sTest;
   1.570 +typedef Predicate%(n)sTest ASSERT_PRED%(n)sTest;
   1.571 +""" % DEFS
   1.572 +
   1.573 +  def GenTest(use_format, use_assert, expect_failure,
   1.574 +              use_functor, use_user_type):
   1.575 +    """Returns the test for a predicate assertion macro.
   1.576 +
   1.577 +    Args:
   1.578 +      use_format:     true iff the assertion is a *_PRED_FORMAT*.
   1.579 +      use_assert:     true iff the assertion is a ASSERT_*.
   1.580 +      expect_failure: true iff the assertion is expected to fail.
   1.581 +      use_functor:    true iff the first argument of the assertion is
   1.582 +                      a functor (as opposed to a function)
   1.583 +      use_user_type:  true iff the predicate functor/function takes
   1.584 +                      argument(s) of a user-defined type.
   1.585 +
   1.586 +    Example:
   1.587 +
   1.588 +      GenTest(1, 0, 0, 1, 0) returns a test that tests the behavior
   1.589 +      of a successful EXPECT_PRED_FORMATn() that takes a functor
   1.590 +      whose arguments have built-in types."""
   1.591 +
   1.592 +    if use_assert:
   1.593 +      assrt = 'ASSERT'  # 'assert' is reserved, so we cannot use
   1.594 +                        # that identifier here.
   1.595 +    else:
   1.596 +      assrt = 'EXPECT'
   1.597 +
   1.598 +    assertion = assrt + '_PRED'
   1.599 +
   1.600 +    if use_format:
   1.601 +      pred_format = 'PredFormat'
   1.602 +      assertion += '_FORMAT'
   1.603 +    else:
   1.604 +      pred_format = 'Pred'
   1.605 +
   1.606 +    assertion += '%(n)s' % DEFS
   1.607 +
   1.608 +    if use_functor:
   1.609 +      pred_format_type = 'functor'
   1.610 +      pred_format += 'Functor%(n)s()'
   1.611 +    else:
   1.612 +      pred_format_type = 'function'
   1.613 +      pred_format += 'Function%(n)s'
   1.614 +      if not use_format:
   1.615 +        if use_user_type:
   1.616 +          pred_format += 'Bool'
   1.617 +        else:
   1.618 +          pred_format += 'Int'
   1.619 +
   1.620 +    test_name = pred_format_type.title()
   1.621 +
   1.622 +    if use_user_type:
   1.623 +      arg_type = 'user-defined type (Bool)'
   1.624 +      test_name += 'OnUserType'
   1.625 +      if expect_failure:
   1.626 +        arg = 'Bool(n%s_++)'
   1.627 +      else:
   1.628 +        arg = 'Bool(++n%s_)'
   1.629 +    else:
   1.630 +      arg_type = 'built-in type (int)'
   1.631 +      test_name += 'OnBuiltInType'
   1.632 +      if expect_failure:
   1.633 +        arg = 'n%s_++'
   1.634 +      else:
   1.635 +        arg = '++n%s_'
   1.636 +
   1.637 +    if expect_failure:
   1.638 +      successful_or_failed = 'failed'
   1.639 +      expected_or_not = 'expected.'
   1.640 +      test_name +=  'Failure'
   1.641 +    else:
   1.642 +      successful_or_failed = 'successful'
   1.643 +      expected_or_not = 'UNEXPECTED!'
   1.644 +      test_name +=  'Success'
   1.645 +
   1.646 +    # A map that defines the values used in the test template.
   1.647 +    defs = DEFS.copy()
   1.648 +    defs.update({
   1.649 +      'assert' : assrt,
   1.650 +      'assertion' : assertion,
   1.651 +      'test_name' : test_name,
   1.652 +      'pf_type' : pred_format_type,
   1.653 +      'pf' : pred_format,
   1.654 +      'arg_type' : arg_type,
   1.655 +      'arg' : arg,
   1.656 +      'successful' : successful_or_failed,
   1.657 +      'expected' : expected_or_not,
   1.658 +      })
   1.659 +
   1.660 +    test = """
   1.661 +// Tests a %(successful)s %(assertion)s where the
   1.662 +// predicate-formatter is a %(pf_type)s on a %(arg_type)s.
   1.663 +TEST_F(%(assertion)sTest, %(test_name)s) {""" % defs
   1.664 +
   1.665 +    indent = (len(assertion) + 3)*' '
   1.666 +    extra_indent = ''
   1.667 +
   1.668 +    if expect_failure:
   1.669 +      extra_indent = '  '
   1.670 +      if use_assert:
   1.671 +        test += """
   1.672 +  expected_to_finish_ = false;
   1.673 +  EXPECT_FATAL_FAILURE({  // NOLINT"""
   1.674 +      else:
   1.675 +        test += """
   1.676 +  EXPECT_NONFATAL_FAILURE({  // NOLINT"""
   1.677 +
   1.678 +    test += '\n' + extra_indent + """  %(assertion)s(%(pf)s""" % defs
   1.679 +
   1.680 +    test = test % defs
   1.681 +    test += Iter(n, ',\n' + indent + extra_indent + '%(arg)s' % defs)
   1.682 +    test += ');\n' + extra_indent + '  finished_ = true;\n'
   1.683 +
   1.684 +    if expect_failure:
   1.685 +      test += '  }, "");\n'
   1.686 +
   1.687 +    test += '}\n'
   1.688 +    return test
   1.689 +
   1.690 +  # Generates tests for all 2**6 = 64 combinations.
   1.691 +  tests += ''.join([GenTest(use_format, use_assert, expect_failure,
   1.692 +                            use_functor, use_user_type)
   1.693 +                    for use_format in [0, 1]
   1.694 +                    for use_assert in [0, 1]
   1.695 +                    for expect_failure in [0, 1]
   1.696 +                    for use_functor in [0, 1]
   1.697 +                    for use_user_type in [0, 1]
   1.698 +                    ])
   1.699 +
   1.700 +  return tests
   1.701 +
   1.702 +
   1.703 +def UnitTestPostamble():
   1.704 +  """Returns the postamble for the tests."""
   1.705 +
   1.706 +  return ''
   1.707 +
   1.708 +
   1.709 +def GenerateUnitTest(n):
   1.710 +  """Returns the tests for up-to n-ary predicate assertions."""
   1.711 +
   1.712 +  GenerateFile(UNIT_TEST,
   1.713 +               UnitTestPreamble()
   1.714 +               + ''.join([TestsForArity(i) for i in OneTo(n)])
   1.715 +               + UnitTestPostamble())
   1.716 +
   1.717 +
   1.718 +def _Main():
   1.719 +  """The entry point of the script.  Generates the header file and its
   1.720 +  unit test."""
   1.721 +
   1.722 +  if len(sys.argv) != 2:
   1.723 +    print __doc__
   1.724 +    print 'Author: ' + __author__
   1.725 +    sys.exit(1)
   1.726 +
   1.727 +  n = int(sys.argv[1])
   1.728 +  GenerateHeader(n)
   1.729 +  GenerateUnitTest(n)
   1.730 +
   1.731 +
   1.732 +if __name__ == '__main__':
   1.733 +  _Main()

mercurial