Blame googletest/scripts/gen_gtest_pred_impl.py

Packit bd1cd8
#!/usr/bin/env python
Packit bd1cd8
#
Packit bd1cd8
# Copyright 2006, Google Inc.
Packit bd1cd8
# All rights reserved.
Packit bd1cd8
#
Packit bd1cd8
# Redistribution and use in source and binary forms, with or without
Packit bd1cd8
# modification, are permitted provided that the following conditions are
Packit bd1cd8
# met:
Packit bd1cd8
#
Packit bd1cd8
#     * Redistributions of source code must retain the above copyright
Packit bd1cd8
# notice, this list of conditions and the following disclaimer.
Packit bd1cd8
#     * Redistributions in binary form must reproduce the above
Packit bd1cd8
# copyright notice, this list of conditions and the following disclaimer
Packit bd1cd8
# in the documentation and/or other materials provided with the
Packit bd1cd8
# distribution.
Packit bd1cd8
#     * Neither the name of Google Inc. nor the names of its
Packit bd1cd8
# contributors may be used to endorse or promote products derived from
Packit bd1cd8
# this software without specific prior written permission.
Packit bd1cd8
#
Packit bd1cd8
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
Packit bd1cd8
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
Packit bd1cd8
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
Packit bd1cd8
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
Packit bd1cd8
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
Packit bd1cd8
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
Packit bd1cd8
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
Packit bd1cd8
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
Packit bd1cd8
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
Packit bd1cd8
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
Packit bd1cd8
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Packit bd1cd8
Packit bd1cd8
"""gen_gtest_pred_impl.py v0.1
Packit bd1cd8
Packit bd1cd8
Generates the implementation of Google Test predicate assertions and
Packit bd1cd8
accompanying tests.
Packit bd1cd8
Packit bd1cd8
Usage:
Packit bd1cd8
Packit bd1cd8
  gen_gtest_pred_impl.py MAX_ARITY
Packit bd1cd8
Packit bd1cd8
where MAX_ARITY is a positive integer.
Packit bd1cd8
Packit bd1cd8
The command generates the implementation of up-to MAX_ARITY-ary
Packit bd1cd8
predicate assertions, and writes it to file gtest_pred_impl.h in the
Packit bd1cd8
directory where the script is.  It also generates the accompanying
Packit bd1cd8
unit test in file gtest_pred_impl_unittest.cc.
Packit bd1cd8
"""
Packit bd1cd8
Packit bd1cd8
__author__ = 'wan@google.com (Zhanyong Wan)'
Packit bd1cd8
Packit bd1cd8
import os
Packit bd1cd8
import sys
Packit bd1cd8
import time
Packit bd1cd8
Packit bd1cd8
# Where this script is.
Packit bd1cd8
SCRIPT_DIR = os.path.dirname(sys.argv[0])
Packit bd1cd8
Packit bd1cd8
# Where to store the generated header.
Packit bd1cd8
HEADER = os.path.join(SCRIPT_DIR, '../include/gtest/gtest_pred_impl.h')
Packit bd1cd8
Packit bd1cd8
# Where to store the generated unit test.
Packit bd1cd8
UNIT_TEST = os.path.join(SCRIPT_DIR, '../test/gtest_pred_impl_unittest.cc')
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
def HeaderPreamble(n):
Packit bd1cd8
  """Returns the preamble for the header file.
Packit bd1cd8
Packit bd1cd8
  Args:
Packit bd1cd8
    n:  the maximum arity of the predicate macros to be generated.
Packit bd1cd8
  """
Packit bd1cd8
Packit bd1cd8
  # A map that defines the values used in the preamble template.
Packit bd1cd8
  DEFS = {
Packit bd1cd8
    'today' : time.strftime('%m/%d/%Y'),
Packit bd1cd8
    'year' : time.strftime('%Y'),
Packit bd1cd8
    'command' : '%s %s' % (os.path.basename(sys.argv[0]), n),
Packit bd1cd8
    'n' : n
Packit bd1cd8
    }
Packit bd1cd8
Packit bd1cd8
  return (
Packit bd1cd8
"""// Copyright 2006, Google Inc.
Packit bd1cd8
// All rights reserved.
Packit bd1cd8
//
Packit bd1cd8
// Redistribution and use in source and binary forms, with or without
Packit bd1cd8
// modification, are permitted provided that the following conditions are
Packit bd1cd8
// met:
Packit bd1cd8
//
Packit bd1cd8
//     * Redistributions of source code must retain the above copyright
Packit bd1cd8
// notice, this list of conditions and the following disclaimer.
Packit bd1cd8
//     * Redistributions in binary form must reproduce the above
Packit bd1cd8
// copyright notice, this list of conditions and the following disclaimer
Packit bd1cd8
// in the documentation and/or other materials provided with the
Packit bd1cd8
// distribution.
Packit bd1cd8
//     * Neither the name of Google Inc. nor the names of its
Packit bd1cd8
// contributors may be used to endorse or promote products derived from
Packit bd1cd8
// this software without specific prior written permission.
Packit bd1cd8
//
Packit bd1cd8
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
Packit bd1cd8
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
Packit bd1cd8
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
Packit bd1cd8
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
Packit bd1cd8
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
Packit bd1cd8
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
Packit bd1cd8
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
Packit bd1cd8
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
Packit bd1cd8
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
Packit bd1cd8
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
Packit bd1cd8
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Packit bd1cd8
Packit bd1cd8
// This file is AUTOMATICALLY GENERATED on %(today)s by command
Packit bd1cd8
// '%(command)s'.  DO NOT EDIT BY HAND!
Packit bd1cd8
//
Packit bd1cd8
// Implements a family of generic predicate assertion macros.
Packit bd1cd8
Packit bd1cd8
#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
Packit bd1cd8
#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
Packit bd1cd8
Packit bd1cd8
// Makes sure this header is not included before gtest.h.
Packit bd1cd8
#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
Packit bd1cd8
# error Do not include gtest_pred_impl.h directly.  Include gtest.h instead.
Packit bd1cd8
#endif  // GTEST_INCLUDE_GTEST_GTEST_H_
Packit bd1cd8
Packit bd1cd8
// This header implements a family of generic predicate assertion
Packit bd1cd8
// macros:
Packit bd1cd8
//
Packit bd1cd8
//   ASSERT_PRED_FORMAT1(pred_format, v1)
Packit bd1cd8
//   ASSERT_PRED_FORMAT2(pred_format, v1, v2)
Packit bd1cd8
//   ...
Packit bd1cd8
//
Packit bd1cd8
// where pred_format is a function or functor that takes n (in the
Packit bd1cd8
// case of ASSERT_PRED_FORMATn) values and their source expression
Packit bd1cd8
// text, and returns a testing::AssertionResult.  See the definition
Packit bd1cd8
// of ASSERT_EQ in gtest.h for an example.
Packit bd1cd8
//
Packit bd1cd8
// If you don't care about formatting, you can use the more
Packit bd1cd8
// restrictive version:
Packit bd1cd8
//
Packit bd1cd8
//   ASSERT_PRED1(pred, v1)
Packit bd1cd8
//   ASSERT_PRED2(pred, v1, v2)
Packit bd1cd8
//   ...
Packit bd1cd8
//
Packit bd1cd8
// where pred is an n-ary function or functor that returns bool,
Packit bd1cd8
// and the values v1, v2, ..., must support the << operator for
Packit bd1cd8
// streaming to std::ostream.
Packit bd1cd8
//
Packit bd1cd8
// We also define the EXPECT_* variations.
Packit bd1cd8
//
Packit bd1cd8
// For now we only support predicates whose arity is at most %(n)s.
Packit bd1cd8
// Please email googletestframework@googlegroups.com if you need
Packit bd1cd8
// support for higher arities.
Packit bd1cd8
Packit bd1cd8
// GTEST_ASSERT_ is the basic statement to which all of the assertions
Packit bd1cd8
// in this file reduce.  Don't use this in your code.
Packit bd1cd8
Packit bd1cd8
#define GTEST_ASSERT_(expression, on_failure) \\
Packit bd1cd8
  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \\
Packit bd1cd8
  if (const ::testing::AssertionResult gtest_ar = (expression)) \\
Packit bd1cd8
    ; \\
Packit bd1cd8
  else \\
Packit bd1cd8
    on_failure(gtest_ar.failure_message())
Packit bd1cd8
""" % DEFS)
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
def Arity(n):
Packit bd1cd8
  """Returns the English name of the given arity."""
Packit bd1cd8
Packit bd1cd8
  if n < 0:
Packit bd1cd8
    return None
Packit bd1cd8
  elif n <= 3:
Packit bd1cd8
    return ['nullary', 'unary', 'binary', 'ternary'][n]
Packit bd1cd8
  else:
Packit bd1cd8
    return '%s-ary' % n
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
def Title(word):
Packit bd1cd8
  """Returns the given word in title case.  The difference between
Packit bd1cd8
  this and string's title() method is that Title('4-ary') is '4-ary'
Packit bd1cd8
  while '4-ary'.title() is '4-Ary'."""
Packit bd1cd8
Packit bd1cd8
  return word[0].upper() + word[1:]
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
def OneTo(n):
Packit bd1cd8
  """Returns the list [1, 2, 3, ..., n]."""
Packit bd1cd8
Packit bd1cd8
  return range(1, n + 1)
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
def Iter(n, format, sep=''):
Packit bd1cd8
  """Given a positive integer n, a format string that contains 0 or
Packit bd1cd8
  more '%s' format specs, and optionally a separator string, returns
Packit bd1cd8
  the join of n strings, each formatted with the format string on an
Packit bd1cd8
  iterator ranged from 1 to n.
Packit bd1cd8
Packit bd1cd8
  Example:
Packit bd1cd8
Packit bd1cd8
  Iter(3, 'v%s', sep=', ') returns 'v1, v2, v3'.
Packit bd1cd8
  """
Packit bd1cd8
Packit bd1cd8
  # How many '%s' specs are in format?
Packit bd1cd8
  spec_count = len(format.split('%s')) - 1
Packit bd1cd8
  return sep.join([format % (spec_count * (i,)) for i in OneTo(n)])
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
def ImplementationForArity(n):
Packit bd1cd8
  """Returns the implementation of n-ary predicate assertions."""
Packit bd1cd8
Packit bd1cd8
  # A map the defines the values used in the implementation template.
Packit bd1cd8
  DEFS = {
Packit bd1cd8
    'n' : str(n),
Packit bd1cd8
    'vs' : Iter(n, 'v%s', sep=', '),
Packit bd1cd8
    'vts' : Iter(n, '#v%s', sep=', '),
Packit bd1cd8
    'arity' : Arity(n),
Packit bd1cd8
    'Arity' : Title(Arity(n))
Packit bd1cd8
    }
Packit bd1cd8
Packit bd1cd8
  impl = """
Packit bd1cd8
Packit bd1cd8
// Helper function for implementing {EXPECT|ASSERT}_PRED%(n)s.  Don't use
Packit bd1cd8
// this in your code.
Packit bd1cd8
template 
Packit bd1cd8
Packit bd1cd8
  impl += Iter(n, """,
Packit bd1cd8
          typename T%s""")
Packit bd1cd8
Packit bd1cd8
  impl += """>
Packit bd1cd8
AssertionResult AssertPred%(n)sHelper(const char* pred_text""" % DEFS
Packit bd1cd8
Packit bd1cd8
  impl += Iter(n, """,
Packit bd1cd8
                                  const char* e%s""")
Packit bd1cd8
Packit bd1cd8
  impl += """,
Packit bd1cd8
                                  Pred pred"""
Packit bd1cd8
Packit bd1cd8
  impl += Iter(n, """,
Packit bd1cd8
                                  const T%s& v%s""")
Packit bd1cd8
Packit bd1cd8
  impl += """) {
Packit bd1cd8
  if (pred(%(vs)s)) return AssertionSuccess();
Packit bd1cd8
Packit bd1cd8
""" % DEFS
Packit bd1cd8
Packit bd1cd8
  impl += '  return AssertionFailure() << pred_text << "("'
Packit bd1cd8
Packit bd1cd8
  impl += Iter(n, """
Packit bd1cd8
                            << e%s""", sep=' << ", "')
Packit bd1cd8
Packit bd1cd8
  impl += ' << ") evaluates to false, where"'
Packit bd1cd8
Packit bd1cd8
  impl += Iter(n, """
Packit bd1cd8
                            << "\\n" << e%s << " evaluates to " << v%s""")
Packit bd1cd8
Packit bd1cd8
  impl += """;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
Packit bd1cd8
// Don't use this in your code.
Packit bd1cd8
#define GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, on_failure)\\
Packit bd1cd8
  GTEST_ASSERT_(pred_format(%(vts)s, %(vs)s), \\
Packit bd1cd8
                on_failure)
Packit bd1cd8
Packit bd1cd8
// Internal macro for implementing {EXPECT|ASSERT}_PRED%(n)s.  Don't use
Packit bd1cd8
// this in your code.
Packit bd1cd8
#define GTEST_PRED%(n)s_(pred, %(vs)s, on_failure)\\
Packit bd1cd8
  GTEST_ASSERT_(::testing::AssertPred%(n)sHelper(#pred""" % DEFS
Packit bd1cd8
Packit bd1cd8
  impl += Iter(n, """, \\
Packit bd1cd8
                                             #v%s""")
Packit bd1cd8
Packit bd1cd8
  impl += """, \\
Packit bd1cd8
                                             pred"""
Packit bd1cd8
Packit bd1cd8
  impl += Iter(n, """, \\
Packit bd1cd8
                                             v%s""")
Packit bd1cd8
Packit bd1cd8
  impl += """), on_failure)
Packit bd1cd8
Packit bd1cd8
// %(Arity)s predicate assertion macros.
Packit bd1cd8
#define EXPECT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
Packit bd1cd8
  GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_NONFATAL_FAILURE_)
Packit bd1cd8
#define EXPECT_PRED%(n)s(pred, %(vs)s) \\
Packit bd1cd8
  GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_NONFATAL_FAILURE_)
Packit bd1cd8
#define ASSERT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
Packit bd1cd8
  GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_FATAL_FAILURE_)
Packit bd1cd8
#define ASSERT_PRED%(n)s(pred, %(vs)s) \\
Packit bd1cd8
  GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_FATAL_FAILURE_)
Packit bd1cd8
Packit bd1cd8
""" % DEFS
Packit bd1cd8
Packit bd1cd8
  return impl
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
def HeaderPostamble():
Packit bd1cd8
  """Returns the postamble for the header file."""
Packit bd1cd8
Packit bd1cd8
  return """
Packit bd1cd8
Packit bd1cd8
#endif  // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
Packit bd1cd8
"""
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
def GenerateFile(path, content):
Packit bd1cd8
  """Given a file path and a content string, overwrites it with the
Packit bd1cd8
  given content."""
Packit bd1cd8
Packit bd1cd8
  print 'Updating file %s . . .' % path
Packit bd1cd8
Packit bd1cd8
  f = file(path, 'w+')
Packit bd1cd8
  print >>f, content,
Packit bd1cd8
  f.close()
Packit bd1cd8
Packit bd1cd8
  print 'File %s has been updated.' % path
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
def GenerateHeader(n):
Packit bd1cd8
  """Given the maximum arity n, updates the header file that implements
Packit bd1cd8
  the predicate assertions."""
Packit bd1cd8
Packit bd1cd8
  GenerateFile(HEADER,
Packit bd1cd8
               HeaderPreamble(n)
Packit bd1cd8
               + ''.join([ImplementationForArity(i) for i in OneTo(n)])
Packit bd1cd8
               + HeaderPostamble())
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
def UnitTestPreamble():
Packit bd1cd8
  """Returns the preamble for the unit test file."""
Packit bd1cd8
Packit bd1cd8
  # A map that defines the values used in the preamble template.
Packit bd1cd8
  DEFS = {
Packit bd1cd8
    'today' : time.strftime('%m/%d/%Y'),
Packit bd1cd8
    'year' : time.strftime('%Y'),
Packit bd1cd8
    'command' : '%s %s' % (os.path.basename(sys.argv[0]), sys.argv[1]),
Packit bd1cd8
    }
Packit bd1cd8
Packit bd1cd8
  return (
Packit bd1cd8
"""// Copyright 2006, Google Inc.
Packit bd1cd8
// All rights reserved.
Packit bd1cd8
//
Packit bd1cd8
// Redistribution and use in source and binary forms, with or without
Packit bd1cd8
// modification, are permitted provided that the following conditions are
Packit bd1cd8
// met:
Packit bd1cd8
//
Packit bd1cd8
//     * Redistributions of source code must retain the above copyright
Packit bd1cd8
// notice, this list of conditions and the following disclaimer.
Packit bd1cd8
//     * Redistributions in binary form must reproduce the above
Packit bd1cd8
// copyright notice, this list of conditions and the following disclaimer
Packit bd1cd8
// in the documentation and/or other materials provided with the
Packit bd1cd8
// distribution.
Packit bd1cd8
//     * Neither the name of Google Inc. nor the names of its
Packit bd1cd8
// contributors may be used to endorse or promote products derived from
Packit bd1cd8
// this software without specific prior written permission.
Packit bd1cd8
//
Packit bd1cd8
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
Packit bd1cd8
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
Packit bd1cd8
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
Packit bd1cd8
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
Packit bd1cd8
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
Packit bd1cd8
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
Packit bd1cd8
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
Packit bd1cd8
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
Packit bd1cd8
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
Packit bd1cd8
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
Packit bd1cd8
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Packit bd1cd8
Packit bd1cd8
// This file is AUTOMATICALLY GENERATED on %(today)s by command
Packit bd1cd8
// '%(command)s'.  DO NOT EDIT BY HAND!
Packit bd1cd8
Packit bd1cd8
// Regression test for gtest_pred_impl.h
Packit bd1cd8
//
Packit bd1cd8
// This file is generated by a script and quite long.  If you intend to
Packit bd1cd8
// learn how Google Test works by reading its unit tests, read
Packit bd1cd8
// gtest_unittest.cc instead.
Packit bd1cd8
//
Packit bd1cd8
// This is intended as a regression test for the Google Test predicate
Packit bd1cd8
// assertions.  We compile it as part of the gtest_unittest target
Packit bd1cd8
// only to keep the implementation tidy and compact, as it is quite
Packit bd1cd8
// involved to set up the stage for testing Google Test using Google
Packit bd1cd8
// Test itself.
Packit bd1cd8
//
Packit bd1cd8
// Currently, gtest_unittest takes ~11 seconds to run in the testing
Packit bd1cd8
// daemon.  In the future, if it grows too large and needs much more
Packit bd1cd8
// time to finish, we should consider separating this file into a
Packit bd1cd8
// stand-alone regression test.
Packit bd1cd8
Packit bd1cd8
#include <iostream>
Packit bd1cd8
Packit bd1cd8
#include "gtest/gtest.h"
Packit bd1cd8
#include "gtest/gtest-spi.h"
Packit bd1cd8
Packit bd1cd8
// A user-defined data type.
Packit bd1cd8
struct Bool {
Packit bd1cd8
  explicit Bool(int val) : value(val != 0) {}
Packit bd1cd8
Packit bd1cd8
  bool operator>(int n) const { return value > Bool(n).value; }
Packit bd1cd8
Packit bd1cd8
  Bool operator+(const Bool& rhs) const { return Bool(value + rhs.value); }
Packit bd1cd8
Packit bd1cd8
  bool operator==(const Bool& rhs) const { return value == rhs.value; }
Packit bd1cd8
Packit bd1cd8
  bool value;
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
// Enables Bool to be used in assertions.
Packit bd1cd8
std::ostream& operator<<(std::ostream& os, const Bool& x) {
Packit bd1cd8
  return os << (x.value ? "true" : "false");
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
""" % DEFS)
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
def TestsForArity(n):
Packit bd1cd8
  """Returns the tests for n-ary predicate assertions."""
Packit bd1cd8
Packit bd1cd8
  # A map that defines the values used in the template for the tests.
Packit bd1cd8
  DEFS = {
Packit bd1cd8
    'n' : n,
Packit bd1cd8
    'es' : Iter(n, 'e%s', sep=', '),
Packit bd1cd8
    'vs' : Iter(n, 'v%s', sep=', '),
Packit bd1cd8
    'vts' : Iter(n, '#v%s', sep=', '),
Packit bd1cd8
    'tvs' : Iter(n, 'T%s v%s', sep=', '),
Packit bd1cd8
    'int_vs' : Iter(n, 'int v%s', sep=', '),
Packit bd1cd8
    'Bool_vs' : Iter(n, 'Bool v%s', sep=', '),
Packit bd1cd8
    'types' : Iter(n, 'typename T%s', sep=', '),
Packit bd1cd8
    'v_sum' : Iter(n, 'v%s', sep=' + '),
Packit bd1cd8
    'arity' : Arity(n),
Packit bd1cd8
    'Arity' : Title(Arity(n)),
Packit bd1cd8
    }
Packit bd1cd8
Packit bd1cd8
  tests = (
Packit bd1cd8
"""// Sample functions/functors for testing %(arity)s predicate assertions.
Packit bd1cd8
Packit bd1cd8
// A %(arity)s predicate function.
Packit bd1cd8
template <%(types)s>
Packit bd1cd8
bool PredFunction%(n)s(%(tvs)s) {
Packit bd1cd8
  return %(v_sum)s > 0;
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
// The following two functions are needed to circumvent a bug in
Packit bd1cd8
// gcc 2.95.3, which sometimes has problem with the above template
Packit bd1cd8
// function.
Packit bd1cd8
bool PredFunction%(n)sInt(%(int_vs)s) {
Packit bd1cd8
  return %(v_sum)s > 0;
Packit bd1cd8
}
Packit bd1cd8
bool PredFunction%(n)sBool(%(Bool_vs)s) {
Packit bd1cd8
  return %(v_sum)s > 0;
Packit bd1cd8
}
Packit bd1cd8
""" % DEFS)
Packit bd1cd8
Packit bd1cd8
  tests += """
Packit bd1cd8
// A %(arity)s predicate functor.
Packit bd1cd8
struct PredFunctor%(n)s {
Packit bd1cd8
  template <%(types)s>
Packit bd1cd8
  bool operator()(""" % DEFS
Packit bd1cd8
Packit bd1cd8
  tests += Iter(n, 'const T%s& v%s', sep=""",
Packit bd1cd8
                  """)
Packit bd1cd8
Packit bd1cd8
  tests += """) {
Packit bd1cd8
    return %(v_sum)s > 0;
Packit bd1cd8
  }
Packit bd1cd8
};
Packit bd1cd8
""" % DEFS
Packit bd1cd8
Packit bd1cd8
  tests += """
Packit bd1cd8
// A %(arity)s predicate-formatter function.
Packit bd1cd8
template <%(types)s>
Packit bd1cd8
testing::AssertionResult PredFormatFunction%(n)s(""" % DEFS
Packit bd1cd8
Packit bd1cd8
  tests += Iter(n, 'const char* e%s', sep=""",
Packit bd1cd8
                                             """)
Packit bd1cd8
Packit bd1cd8
  tests += Iter(n, """,
Packit bd1cd8
                                             const T%s& v%s""")
Packit bd1cd8
Packit bd1cd8
  tests += """) {
Packit bd1cd8
  if (PredFunction%(n)s(%(vs)s))
Packit bd1cd8
    return testing::AssertionSuccess();
Packit bd1cd8
Packit bd1cd8
  return testing::AssertionFailure()
Packit bd1cd8
      << """ % DEFS
Packit bd1cd8
Packit bd1cd8
  tests += Iter(n, 'e%s', sep=' << " + " << ')
Packit bd1cd8
Packit bd1cd8
  tests += """
Packit bd1cd8
      << " is expected to be positive, but evaluates to "
Packit bd1cd8
      << %(v_sum)s << ".";
Packit bd1cd8
}
Packit bd1cd8
""" % DEFS
Packit bd1cd8
Packit bd1cd8
  tests += """
Packit bd1cd8
// A %(arity)s predicate-formatter functor.
Packit bd1cd8
struct PredFormatFunctor%(n)s {
Packit bd1cd8
  template <%(types)s>
Packit bd1cd8
  testing::AssertionResult operator()(""" % DEFS
Packit bd1cd8
Packit bd1cd8
  tests += Iter(n, 'const char* e%s', sep=""",
Packit bd1cd8
                                      """)
Packit bd1cd8
Packit bd1cd8
  tests += Iter(n, """,
Packit bd1cd8
                                      const T%s& v%s""")
Packit bd1cd8
Packit bd1cd8
  tests += """) const {
Packit bd1cd8
    return PredFormatFunction%(n)s(%(es)s, %(vs)s);
Packit bd1cd8
  }
Packit bd1cd8
};
Packit bd1cd8
""" % DEFS
Packit bd1cd8
Packit bd1cd8
  tests += """
Packit bd1cd8
// Tests for {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
Packit bd1cd8
Packit bd1cd8
class Predicate%(n)sTest : public testing::Test {
Packit bd1cd8
 protected:
Packit bd1cd8
  virtual void SetUp() {
Packit bd1cd8
    expected_to_finish_ = true;
Packit bd1cd8
    finished_ = false;""" % DEFS
Packit bd1cd8
Packit bd1cd8
  tests += """
Packit bd1cd8
    """ + Iter(n, 'n%s_ = ') + """0;
Packit bd1cd8
  }
Packit bd1cd8
"""
Packit bd1cd8
Packit bd1cd8
  tests += """
Packit bd1cd8
  virtual void TearDown() {
Packit bd1cd8
    // Verifies that each of the predicate's arguments was evaluated
Packit bd1cd8
    // exactly once."""
Packit bd1cd8
Packit bd1cd8
  tests += ''.join(["""
Packit bd1cd8
    EXPECT_EQ(1, n%s_) <<
Packit bd1cd8
        "The predicate assertion didn't evaluate argument %s "
Packit bd1cd8
        "exactly once.";""" % (i, i + 1) for i in OneTo(n)])
Packit bd1cd8
Packit bd1cd8
  tests += """
Packit bd1cd8
Packit bd1cd8
    // Verifies that the control flow in the test function is expected.
Packit bd1cd8
    if (expected_to_finish_ && !finished_) {
Packit bd1cd8
      FAIL() << "The predicate assertion unexpactedly aborted the test.";
Packit bd1cd8
    } else if (!expected_to_finish_ && finished_) {
Packit bd1cd8
      FAIL() << "The failed predicate assertion didn't abort the test "
Packit bd1cd8
                "as expected.";
Packit bd1cd8
    }
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  // true iff the test function is expected to run to finish.
Packit bd1cd8
  static bool expected_to_finish_;
Packit bd1cd8
Packit bd1cd8
  // true iff the test function did run to finish.
Packit bd1cd8
  static bool finished_;
Packit bd1cd8
""" % DEFS
Packit bd1cd8
Packit bd1cd8
  tests += Iter(n, """
Packit bd1cd8
  static int n%s_;""")
Packit bd1cd8
Packit bd1cd8
  tests += """
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
bool Predicate%(n)sTest::expected_to_finish_;
Packit bd1cd8
bool Predicate%(n)sTest::finished_;
Packit bd1cd8
""" % DEFS
Packit bd1cd8
Packit bd1cd8
  tests += Iter(n, """int Predicate%%(n)sTest::n%s_;
Packit bd1cd8
""") % DEFS
Packit bd1cd8
Packit bd1cd8
  tests += """
Packit bd1cd8
typedef Predicate%(n)sTest EXPECT_PRED_FORMAT%(n)sTest;
Packit bd1cd8
typedef Predicate%(n)sTest ASSERT_PRED_FORMAT%(n)sTest;
Packit bd1cd8
typedef Predicate%(n)sTest EXPECT_PRED%(n)sTest;
Packit bd1cd8
typedef Predicate%(n)sTest ASSERT_PRED%(n)sTest;
Packit bd1cd8
""" % DEFS
Packit bd1cd8
Packit bd1cd8
  def GenTest(use_format, use_assert, expect_failure,
Packit bd1cd8
              use_functor, use_user_type):
Packit bd1cd8
    """Returns the test for a predicate assertion macro.
Packit bd1cd8
Packit bd1cd8
    Args:
Packit bd1cd8
      use_format:     true iff the assertion is a *_PRED_FORMAT*.
Packit bd1cd8
      use_assert:     true iff the assertion is a ASSERT_*.
Packit bd1cd8
      expect_failure: true iff the assertion is expected to fail.
Packit bd1cd8
      use_functor:    true iff the first argument of the assertion is
Packit bd1cd8
                      a functor (as opposed to a function)
Packit bd1cd8
      use_user_type:  true iff the predicate functor/function takes
Packit bd1cd8
                      argument(s) of a user-defined type.
Packit bd1cd8
Packit bd1cd8
    Example:
Packit bd1cd8
Packit bd1cd8
      GenTest(1, 0, 0, 1, 0) returns a test that tests the behavior
Packit bd1cd8
      of a successful EXPECT_PRED_FORMATn() that takes a functor
Packit bd1cd8
      whose arguments have built-in types."""
Packit bd1cd8
Packit bd1cd8
    if use_assert:
Packit bd1cd8
      assrt = 'ASSERT'  # 'assert' is reserved, so we cannot use
Packit bd1cd8
                        # that identifier here.
Packit bd1cd8
    else:
Packit bd1cd8
      assrt = 'EXPECT'
Packit bd1cd8
Packit bd1cd8
    assertion = assrt + '_PRED'
Packit bd1cd8
Packit bd1cd8
    if use_format:
Packit bd1cd8
      pred_format = 'PredFormat'
Packit bd1cd8
      assertion += '_FORMAT'
Packit bd1cd8
    else:
Packit bd1cd8
      pred_format = 'Pred'
Packit bd1cd8
Packit bd1cd8
    assertion += '%(n)s' % DEFS
Packit bd1cd8
Packit bd1cd8
    if use_functor:
Packit bd1cd8
      pred_format_type = 'functor'
Packit bd1cd8
      pred_format += 'Functor%(n)s()'
Packit bd1cd8
    else:
Packit bd1cd8
      pred_format_type = 'function'
Packit bd1cd8
      pred_format += 'Function%(n)s'
Packit bd1cd8
      if not use_format:
Packit bd1cd8
        if use_user_type:
Packit bd1cd8
          pred_format += 'Bool'
Packit bd1cd8
        else:
Packit bd1cd8
          pred_format += 'Int'
Packit bd1cd8
Packit bd1cd8
    test_name = pred_format_type.title()
Packit bd1cd8
Packit bd1cd8
    if use_user_type:
Packit bd1cd8
      arg_type = 'user-defined type (Bool)'
Packit bd1cd8
      test_name += 'OnUserType'
Packit bd1cd8
      if expect_failure:
Packit bd1cd8
        arg = 'Bool(n%s_++)'
Packit bd1cd8
      else:
Packit bd1cd8
        arg = 'Bool(++n%s_)'
Packit bd1cd8
    else:
Packit bd1cd8
      arg_type = 'built-in type (int)'
Packit bd1cd8
      test_name += 'OnBuiltInType'
Packit bd1cd8
      if expect_failure:
Packit bd1cd8
        arg = 'n%s_++'
Packit bd1cd8
      else:
Packit bd1cd8
        arg = '++n%s_'
Packit bd1cd8
Packit bd1cd8
    if expect_failure:
Packit bd1cd8
      successful_or_failed = 'failed'
Packit bd1cd8
      expected_or_not = 'expected.'
Packit bd1cd8
      test_name +=  'Failure'
Packit bd1cd8
    else:
Packit bd1cd8
      successful_or_failed = 'successful'
Packit bd1cd8
      expected_or_not = 'UNEXPECTED!'
Packit bd1cd8
      test_name +=  'Success'
Packit bd1cd8
Packit bd1cd8
    # A map that defines the values used in the test template.
Packit bd1cd8
    defs = DEFS.copy()
Packit bd1cd8
    defs.update({
Packit bd1cd8
      'assert' : assrt,
Packit bd1cd8
      'assertion' : assertion,
Packit bd1cd8
      'test_name' : test_name,
Packit bd1cd8
      'pf_type' : pred_format_type,
Packit bd1cd8
      'pf' : pred_format,
Packit bd1cd8
      'arg_type' : arg_type,
Packit bd1cd8
      'arg' : arg,
Packit bd1cd8
      'successful' : successful_or_failed,
Packit bd1cd8
      'expected' : expected_or_not,
Packit bd1cd8
      })
Packit bd1cd8
Packit bd1cd8
    test = """
Packit bd1cd8
// Tests a %(successful)s %(assertion)s where the
Packit bd1cd8
// predicate-formatter is a %(pf_type)s on a %(arg_type)s.
Packit bd1cd8
TEST_F(%(assertion)sTest, %(test_name)s) {""" % defs
Packit bd1cd8
Packit bd1cd8
    indent = (len(assertion) + 3)*' '
Packit bd1cd8
    extra_indent = ''
Packit bd1cd8
Packit bd1cd8
    if expect_failure:
Packit bd1cd8
      extra_indent = '  '
Packit bd1cd8
      if use_assert:
Packit bd1cd8
        test += """
Packit bd1cd8
  expected_to_finish_ = false;
Packit bd1cd8
  EXPECT_FATAL_FAILURE({  // NOLINT"""
Packit bd1cd8
      else:
Packit bd1cd8
        test += """
Packit bd1cd8
  EXPECT_NONFATAL_FAILURE({  // NOLINT"""
Packit bd1cd8
Packit bd1cd8
    test += '\n' + extra_indent + """  %(assertion)s(%(pf)s""" % defs
Packit bd1cd8
Packit bd1cd8
    test = test % defs
Packit bd1cd8
    test += Iter(n, ',\n' + indent + extra_indent + '%(arg)s' % defs)
Packit bd1cd8
    test += ');\n' + extra_indent + '  finished_ = true;\n'
Packit bd1cd8
Packit bd1cd8
    if expect_failure:
Packit bd1cd8
      test += '  }, "");\n'
Packit bd1cd8
Packit bd1cd8
    test += '}\n'
Packit bd1cd8
    return test
Packit bd1cd8
Packit bd1cd8
  # Generates tests for all 2**6 = 64 combinations.
Packit bd1cd8
  tests += ''.join([GenTest(use_format, use_assert, expect_failure,
Packit bd1cd8
                            use_functor, use_user_type)
Packit bd1cd8
                    for use_format in [0, 1]
Packit bd1cd8
                    for use_assert in [0, 1]
Packit bd1cd8
                    for expect_failure in [0, 1]
Packit bd1cd8
                    for use_functor in [0, 1]
Packit bd1cd8
                    for use_user_type in [0, 1]
Packit bd1cd8
                    ])
Packit bd1cd8
Packit bd1cd8
  return tests
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
def UnitTestPostamble():
Packit bd1cd8
  """Returns the postamble for the tests."""
Packit bd1cd8
Packit bd1cd8
  return ''
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
def GenerateUnitTest(n):
Packit bd1cd8
  """Returns the tests for up-to n-ary predicate assertions."""
Packit bd1cd8
Packit bd1cd8
  GenerateFile(UNIT_TEST,
Packit bd1cd8
               UnitTestPreamble()
Packit bd1cd8
               + ''.join([TestsForArity(i) for i in OneTo(n)])
Packit bd1cd8
               + UnitTestPostamble())
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
def _Main():
Packit bd1cd8
  """The entry point of the script.  Generates the header file and its
Packit bd1cd8
  unit test."""
Packit bd1cd8
Packit bd1cd8
  if len(sys.argv) != 2:
Packit bd1cd8
    print __doc__
Packit bd1cd8
    print 'Author: ' + __author__
Packit bd1cd8
    sys.exit(1)
Packit bd1cd8
Packit bd1cd8
  n = int(sys.argv[1])
Packit bd1cd8
  GenerateHeader(n)
Packit bd1cd8
  GenerateUnitTest(n)
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
if __name__ == '__main__':
Packit bd1cd8
  _Main()