Commits

Anonymous committed 2e7906c

Update bundled gtest to latest version (1.3.0) and include it as a
nested autoconf package rather than as raw source. This way we can
trivially update it again in the future.

Actually, this change doesn't even include gtest in protobuf's SVN.
Instead, we auto-download it when autogen.sh is invoked. Note that
it will be included in release distributions, though.

TODO:
* Add a configure option to use the system's installed gtest rather
than the bundled copy. Apparently the gtest maintainers are working
on some general-purpose autoconf macros which will do this
automagically.
* Update MSVC project files.

Comments (0)

Files changed (27)

       Python:  Foo.BAR_BAZ_FIELD_NUMBER
     Constants are also generated for extensions, with the same naming scheme.
     These constants may be used as switch cases.
+  * Updated bundled Google Test to version 1.3.0.  Google Test is now bundled
+    in its verbatim form as a nested autoconf package, so you can drop in any
+    other version of Google Test if needed.
 
   protoc
   * --error_format=msvs option causes errors to be printed in Visual Studio
 
 AUTOMAKE_OPTIONS = foreign
 
-SUBDIRS = src
+# Build . before src so that our all-local and clean-local hooks kicks in at
+# the right time.
+SUBDIRS = . src
+
+# Always include gtest in distributions.
+DIST_SUBDIRS = $(subdirs) src
+
+# Build gtest before we build protobuf tests.  We don't add gtest to SUBDIRS
+# because then "make check" would also build and run all of gtest's own tests,
+# which takes a lot of time and is generally not useful to us.  Also, we don't
+# want "make install" to recurse into gtest since we don't want to overwrite
+# the installed version of gtest if there is one.
+check-local:
+	@echo "Making lib/libgtest.a lib/libgtest_main.a in gtest"
+	@cd gtest && $(MAKE) $(AM_MAKEFLAGS) lib/libgtest.la lib/libgtest_main.la
+
+# We would like to clean gtest when "make clean" is invoked.  But we have to
+# be careful because clean-local is also invoked during "make distclean", but
+# "make distclean" already recurses into gtest because it's listed among the
+# DIST_SUBDIRS.  distclean will delete gtest/Makefile, so if we then try to
+# cd to the directory again and "make clean" it will fail.  So, check that the
+# Makefile exists before recursing.
+clean-local:
+	@if test -e gtest/Makefile; then \
+	  echo "Making clean in gtest"; \
+	  cd gtest && $(MAKE) $(AM_MAKEFLAGS) clean; \
+	fi
 
 EXTRA_DIST =                                                                 \
   autogen.sh                                                                 \
   exit 1
 fi
 
-set -ex
+if test ! -e gtest; then
+  echo "gtest bundle not present.  Downloading gtest-1.3.0 automatically." >&2
+  set -ex
+  curl http://googletest.googlecode.com/files/gtest-1.3.0.tar.bz2 | tar jx
+  mv gtest-1.3.0 gtest
+else
+  set -ex
+fi
 
 # TODO(kenton):  Remove the ",no-obsolete" part and fix the resulting warnings.
 autoreconf -f -i -Wall,no-obsolete
 # * python/setup.py
 # * src/google/protobuf/stubs/common.h
 # * src/Makefile.am (Update -version-info for LDFLAGS if needed)
-AC_INIT([protobuf],[2.0.4-SNAPSHOT],[protobuf@googlegroups.com])
+#
+# In the SVN trunk, the version should always be the next anticipated release
+# version with the "-pre" suffix.  (We used to use "-SNAPSHOT" but this pushed
+# the size of one file name in the dist tarfile over the 99-char limit.)
+AC_INIT([Protocol Buffers],[2.0.4-pre],[protobuf@googlegroups.com],[protobuf])
 
 AC_CONFIG_SRCDIR(src/google/protobuf/message.cc)
 AC_CONFIG_HEADERS([config.h])
 # Checks for programs.
 AC_PROG_CC
 AC_PROG_CXX
+AC_LANG([C++])
 ACX_USE_SYSTEM_EXTENSIONS
 AC_PROG_LIBTOOL
 AM_CONDITIONAL(GCC, test "$GCC" = yes)   # let the Makefile know if we're gcc
 ACX_PTHREAD
 AC_CXX_STL_HASH
 
+AC_CONFIG_SUBDIRS([gtest])
+
 AC_CONFIG_FILES([Makefile src/Makefile ])
 AC_OUTPUT
   google/protobuf/testdata/text_format_unittest_extensions_data.txt  \
   google/protobuf/package_info.h                               \
   google/protobuf/io/package_info.h                            \
-  google/protobuf/compiler/package_info.h                      \
-  gtest/CHANGES                                                \
-  gtest/CONTRIBUTORS                                           \
-  gtest/COPYING                                                \
-  gtest/README                                                 \
-  gtest/gen_gtest_pred_impl.py
+  google/protobuf/compiler/package_info.h
 
 protoc_outputs =                                               \
   google/protobuf/unittest.pb.cc                               \
 $(protoc_outputs): unittest_proto_middleman
 
 check_PROGRAMS = protobuf-test $(GZCHECKPROGRAMS)
-protobuf_test_LDADD = $(PTHREAD_LIBS) libprotobuf.la libprotoc.la
+protobuf_test_LDADD = $(PTHREAD_LIBS) libprotobuf.la libprotoc.la \
+                      $(top_builddir)/gtest/lib/libgtest.la       \
+                      $(top_builddir)/gtest/lib/libgtest_main.la
+protobuf_test_CPPFLAGS = -I$(top_srcdir)/gtest/include         \
+                         -I$(top_builddir)/gtest/include
 protobuf_test_SOURCES =                                        \
   google/protobuf/stubs/common_unittest.cc                     \
   google/protobuf/stubs/strutil_unittest.cc                    \
   google/protobuf/testing/googletest.cc                        \
   google/protobuf/testing/googletest.h                         \
   google/protobuf/testing/file.cc                              \
-  google/protobuf/testing/file.h                               \
-  gtest/gtest.cc                                               \
-  gtest/gtest.h                                                \
-  gtest/gtest-death-test.cc                                    \
-  gtest/gtest-death-test.h                                     \
-  gtest/gtest-filepath.cc                                      \
-  gtest/gtest-internal-inl.h                                   \
-  gtest/gtest-message.h                                        \
-  gtest/gtest-port.cc                                          \
-  gtest/gtest-spi.h                                            \
-  gtest/gtest_main.cc                                          \
-  gtest/gtest_pred_impl.h                                      \
-  gtest/gtest_prod.h                                           \
-  gtest/internal/gtest-death-test-internal.h                   \
-  gtest/internal/gtest-filepath.h                              \
-  gtest/internal/gtest-internal.h                              \
-  gtest/internal/gtest-port.h                                  \
-  gtest/internal/gtest-string.h
+  google/protobuf/testing/file.h
 
 if HAVE_ZLIB
 zcgzip_LDADD = $(PTHREAD_LIBS) libprotobuf.la

src/gtest/CHANGES

-Changes for 1.0.0:
-
- * Initial Open Source release of Google Test

src/gtest/CONTRIBUTORS

-# This file contains a list of people who've made non-trivial
-# contribution to the Google C++ Testing Framework project.  People
-# who commit code to the project are encouraged to add their names
-# here.  Please keep the list sorted by first names.
-
-Ajay Joshi <jaj@google.com>
-Bharat Mediratta <bharat@menalto.com>
-Chandler Carruth <chandlerc@google.com>
-Chris Prince <cprince@google.com>
-Chris Taylor <taylorc@google.com>
-Jeffrey Yasskin <jyasskin@google.com>
-Keir Mierle <mierle@gmail.com>
-Keith Ray <keith.ray@gmail.com>
-Markus Heule <markus.heule@gmail.com>
-Patrick Hanna <phanna@google.com>
-Patrick Riley <pfr@google.com>
-Peter Kaminski <piotrk@google.com>
-Russ Cox <rsc@google.com>
-Russ Rufer <russ@pentad.com>
-Sean Mcafee <eefacm@gmail.com>
-Sigurður Ásgeirsson <siggi@google.com>
-Tracy Bialik <tracy@pentad.com>
-Zhanyong Wan <wan@google.com>

src/gtest/COPYING

-Copyright 2008, Google Inc.
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
-    * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
-    * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
-    * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

src/gtest/README

-This directory contains Google Test, described below.  It is used by the
-Protocol Buffer C++ unit tests.  If you would like to use Google Test
-yourself, you should probably download it from the URL mentioned below,
-not attempt to use the sources in this package.
-
-Two changes were made from the original sources:
-* gtest.cc's #include of gtest-internal-inl.h was modified to reflect the
-  environment it is being built in (replaced "src/" with "gtest/").
-* GetThreadCount() in gtest-port.h was hard-coded to return 1 rather than 0,
-  since the Protocol Buffer tests do not use threads.
-
-The original Google Test README follows.
-
-======================================================================
-
-Google C++ Testing Framework
-============================
-http://code.google.com/p/googletest/
-
-Overview
---------
-Google's framework for writing C++ tests on a variety of platforms (Linux, Mac
-OS X, Windows, Windows CE, and Symbian). Based on the xUnit architecture.
-Supports automatic test discovery, a rich set of assertions, user-defined
-assertions, death tests, fatal and non-fatal failures, various options for
-running the tests, and XML test report generation.
-
-Please see the project page above for more information as well as mailing lists
-for questions, discussions, and development. There is also an IRC channel on
-OFTC (irc.oftc.net) #gtest available. Please join us!
-
-Requirements
-------------
-Google Test is designed to have fairly minimal requirements to build and use
-with your projects, but there are some. Currently, the only Operating System
-(OS) on which Google Test is known to build properly is Linux, but we are
-actively working on Windows and Mac support as well. The source code itself is
-already portable across many other platforms, but we are still developing
-robust build systems for each.
-
-### Linux Requirements ###
-These are the base requirements to build and use Google Test from a source
-package (as described below):
-  * GNU-compatible Make or "gmake"
-  * POSIX-standard shell
-  * POSIX(-2) Regular Expressions (regex.h)
-  * A C++98 standards compliant compiler
-
-Furthermore, if you are building Google Test from a VCS Checkout (also
-described below), there are further requirements:
-  * Automake version 1.9 or newer
-  * Autoconf version 2.59 or newer
-  * Libtool / Libtoolize
-  * Python version 2.4 or newer
-
-Getting the Source
-------------------
-There are two primary ways of getting Google Test's source code: you can
-download a source release in your preferred archive format, or directly check
-out the source from a Version Control System (VCS, we use Google Code's
-Subversion hosting). The VCS checkout requires a few extra steps and some extra
-software packages on your system, but lets you track development, and make
-patches to contribute much more easily, so we highly encourage it.
-
-### VCS Checkout: ###
-The first step is to select whether you want to check out the main line of
-development on Google Test, or one of the released branches. The former will be
-much more active and have the latest features, but the latter provides much
-more stability and predictability. Choose whichever fits your needs best, and
-proceed with the following Subversion commands:
-
-  $ svn checkout http://googletest.googlecode.com/svn/trunk/ gtest-svn
-
-or for a release version X.Y.*'s branch:
-
-  $ svn checkout http://googletest.googlecode.com/svn/branches/release-X.Y/ gtest-X.Y-svn
-
-Next you will need to prepare the GNU Autotools build system. Enter the
-target directory of the checkout command you used ('gtest-svn' or
-'gtest-X.Y-svn' above) and proceed with the following commands:
-
-  $ aclocal-1.9  # Where "1.9" must match the following automake command
-  $ libtoolize -c
-  $ autoheader
-  $ automake-1.9 -ac  # See Automake version requirements above
-  $ autoconf
-
-While this is a bit complicated, it will most often be automatically re-run by
-your "make" invocations, so in practice you shouldn't need to worry too much.
-Once you have completed these steps, your VCS checkout should be equivalent to
-a source package, and you may continue with those directions, skipping over the
-acquiring and unpacking of the source itself, as the VCS has done that for you.
-
-### Source Package: ###
-Google Test is also released in source packages which can be downloaded from
-its Google Code download page[1]. Several different archive formats are
-provided, but the only difference is the tools used to manipulate them, and the
-size of the resulting file. Download whichever you are most comfortable with.
-
-  [1] Google Test Downloads: http://code.google.com/p/googletest/downloads/list
-
-Once downloaded expand the archive using whichever tools you prefer for that
-type. This will always result in a new directory with the name "gtest-X.Y.Z"
-which contains all of the source code. Here are some examples in Linux:
-
-  $ tar -xvzf gtest-X.Y.Z.tar.gz
-  $ tar -xvjf gtest-X.Y.Z.tar.bz2
-  $ unzip gtest-X.Y.Z.zip
-
-Building the Source
--------------------
-There are two primary options for building the source at this point: build it
-inside the source code tree, or in a separate directory. We recommend building
-in a separate directory as that tends to produce both more consistent results
-and be easier to clean up should anything go wrong, but both patterns are
-supported. The only hard restriction is that while the build directory can be
-a subdirectory of the source directory, the opposite is not possible and will
-result in errors. Once you have selected where you wish to build Google Test,
-create the directory if necessary, and enter it. The following steps apply for
-either approach by simply substituting the shell variable SRCDIR with "." for
-building inside the source directory, and the relative path to the source
-directory otherwise.
-
-  $ ${SRCDIR}/configure  # Standard GNU configure script, --help for more info
-  $ make  # Standard makefile following GNU conventions
-
-Other programs will only be able to use Google Test's functionality if you
-install it in a location which they can access, in Linux this is typically
-under '/usr/local'. The following command will install all of the Google Test
-libraries, public headers, and utilities necessary for other programs and
-libraries to leverage it:
-
-  $ sudo make install  # Not necessary, but allows use by other programs
-
-TODO(chandlerc@google.com): This section needs to be expanded when the
-'gtest-config' script is finished and Autoconf macro's are provided (or not
-provided) in order to properly reflect the process for other programs to
-locate, include, and link against Google Test.
-
-Finally, should you need to remove Google Test from your system after having
-installed it, run the following command, and it will back out its changes.
-However, note carefully that you must run this command on the *same* Google
-Test build that you ran the install from, or the results are not predictable.
-If you install Google Test on your system, and are working from a VCS checkout,
-make sure you run this *before* updating your checkout of the source in order
-to uninstall the same version which you installed.
-
-  $ sudo make uninstall  # Must be run against the exact same build as "install"
-
-Happy testing!

src/gtest/gen_gtest_pred_impl.py

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

src/gtest/gtest-death-test.cc

-// Copyright 2005, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-//
-// This file implements death tests.
-
-#include <gtest/gtest-death-test.h>
-#include <gtest/internal/gtest-port.h>
-
-#include <errno.h>
-#include <limits.h>
-#include <stdarg.h>
-
-#include <gtest/gtest-message.h>
-#include <gtest/internal/gtest-string.h>
-
-// Indicates that this translation unit is part of Google Test's
-// implementation.  It must come before gtest-internal-inl.h is
-// included, or there will be a compiler error.  This trick is to
-// prevent a user from accidentally including gtest-internal-inl.h in
-// his code.
-#define GTEST_IMPLEMENTATION
-#include "gtest-internal-inl.h"
-#undef GTEST_IMPLEMENTATION
-
-namespace testing {
-
-// Constants.
-
-// The default death test style.
-static const char kDefaultDeathTestStyle[] = "fast";
-
-GTEST_DEFINE_string(
-    death_test_style,
-    internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
-    "Indicates how to run a death test in a forked child process: "
-    "\"threadsafe\" (child process re-executes the test binary "
-    "from the beginning, running only the specific death test) or "
-    "\"fast\" (child process runs the death test immediately "
-    "after forking).");
-
-namespace internal {
-GTEST_DEFINE_string(
-    internal_run_death_test, "",
-    "Indicates the file, line number, temporal index of "
-    "the single death test to run, and a file descriptor to "
-    "which a success code may be sent, all separated by "
-    "colons.  This flag is specified if and only if the current "
-    "process is a sub-process launched for running a thread-safe "
-    "death test.  FOR INTERNAL USE ONLY.");
-}  // namespace internal
-
-#ifdef GTEST_HAS_DEATH_TEST
-
-// ExitedWithCode constructor.
-ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
-}
-
-// ExitedWithCode function-call operator.
-bool ExitedWithCode::operator()(int exit_status) const {
-  return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
-}
-
-// KilledBySignal constructor.
-KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
-}
-
-// KilledBySignal function-call operator.
-bool KilledBySignal::operator()(int exit_status) const {
-  return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
-}
-
-namespace internal {
-
-// Utilities needed for death tests.
-
-// Generates a textual description of a given exit code, in the format
-// specified by wait(2).
-static String ExitSummary(int exit_code) {
-  Message m;
-  if (WIFEXITED(exit_code)) {
-    m << "Exited with exit status " << WEXITSTATUS(exit_code);
-  } else if (WIFSIGNALED(exit_code)) {
-    m << "Terminated by signal " << WTERMSIG(exit_code);
-  }
-#ifdef WCOREDUMP
-  if (WCOREDUMP(exit_code)) {
-    m << " (core dumped)";
-  }
-#endif
-  return m.GetString();
-}
-
-// Returns true if exit_status describes a process that was terminated
-// by a signal, or exited normally with a nonzero exit code.
-bool ExitedUnsuccessfully(int exit_status) {
-  return !ExitedWithCode(0)(exit_status);
-}
-
-// Generates a textual failure message when a death test finds more than
-// one thread running, or cannot determine the number of threads, prior
-// to executing the given statement.  It is the responsibility of the
-// caller not to pass a thread_count of 1.
-static String DeathTestThreadWarning(size_t thread_count) {
-  Message msg;
-  msg << "Death tests use fork(), which is unsafe particularly"
-      << " in a threaded context. For this test, " << GTEST_NAME << " ";
-  if (thread_count == 0)
-    msg << "couldn't detect the number of threads.";
-  else
-    msg << "detected " << thread_count << " threads.";
-  return msg.GetString();
-}
-
-// Static string containing a description of the outcome of the
-// last death test.
-static String last_death_test_message;
-
-// Flag characters for reporting a death test that did not die.
-static const char kDeathTestLived = 'L';
-static const char kDeathTestReturned = 'R';
-static const char kDeathTestInternalError = 'I';
-
-// An enumeration describing all of the possible ways that a death test
-// can conclude.  DIED means that the process died while executing the
-// test code; LIVED means that process lived beyond the end of the test
-// code; and RETURNED means that the test statement attempted a "return,"
-// which is not allowed.  IN_PROGRESS means the test has not yet
-// concluded.
-enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED };
-
-// Routine for aborting the program which is safe to call from an
-// exec-style death test child process, in which case the the error
-// message is propagated back to the parent process.  Otherwise, the
-// message is simply printed to stderr.  In either case, the program
-// then exits with status 1.
-void DeathTestAbort(const char* format, ...) {
-  // This function may be called from a threadsafe-style death test
-  // child process, which operates on a very small stack.  Use the
-  // heap for any additional non-miniscule memory requirements.
-  const InternalRunDeathTestFlag* const flag =
-      GetUnitTestImpl()->internal_run_death_test_flag();
-  va_list args;
-  va_start(args, format);
-
-  if (flag != NULL) {
-    FILE* parent = fdopen(flag->status_fd, "w");
-    fputc(kDeathTestInternalError, parent);
-    vfprintf(parent, format, args);
-    fclose(parent);
-    va_end(args);
-    _exit(1);
-  } else {
-    vfprintf(stderr, format, args);
-    va_end(args);
-    abort();
-  }
-}
-
-// A replacement for CHECK that calls DeathTestAbort if the assertion
-// fails.
-#define GTEST_DEATH_TEST_CHECK(expression) \
-  do { \
-    if (!(expression)) { \
-      DeathTestAbort("CHECK failed: File %s, line %d: %s", \
-                     __FILE__, __LINE__, #expression); \
-    } \
-  } while (0)
-
-// This macro is similar to GTEST_DEATH_TEST_CHECK, but it is meant for
-// evaluating any system call that fulfills two conditions: it must return
-// -1 on failure, and set errno to EINTR when it is interrupted and
-// should be tried again.  The macro expands to a loop that repeatedly
-// evaluates the expression as long as it evaluates to -1 and sets
-// errno to EINTR.  If the expression evaluates to -1 but errno is
-// something other than EINTR, DeathTestAbort is called.
-#define GTEST_DEATH_TEST_CHECK_SYSCALL(expression) \
-  do { \
-    int retval; \
-    do { \
-      retval = (expression); \
-    } while (retval == -1 && errno == EINTR); \
-    if (retval == -1) { \
-      DeathTestAbort("CHECK failed: File %s, line %d: %s != -1", \
-                     __FILE__, __LINE__, #expression); \
-    } \
-  } while (0)
-
-// Death test constructor.  Increments the running death test count
-// for the current test.
-DeathTest::DeathTest() {
-  TestInfo* const info = GetUnitTestImpl()->current_test_info();
-  if (info == NULL) {
-    DeathTestAbort("Cannot run a death test outside of a TEST or "
-                   "TEST_F construct");
-  }
-}
-
-// Creates and returns a death test by dispatching to the current
-// death test factory.
-bool DeathTest::Create(const char* statement, const RE* regex,
-                       const char* file, int line, DeathTest** test) {
-  return GetUnitTestImpl()->death_test_factory()->Create(
-      statement, regex, file, line, test);
-}
-
-const char* DeathTest::LastMessage() {
-  return last_death_test_message.c_str();
-}
-
-// ForkingDeathTest provides implementations for most of the abstract
-// methods of the DeathTest interface.  Only the AssumeRole method is
-// left undefined.
-class ForkingDeathTest : public DeathTest {
- public:
-  ForkingDeathTest(const char* statement, const RE* regex);
-
-  // All of these virtual functions are inherited from DeathTest.
-  virtual int Wait();
-  virtual bool Passed(bool status_ok);
-  virtual void Abort(AbortReason reason);
-
- protected:
-  void set_forked(bool forked) { forked_ = forked; }
-  void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
-  void set_read_fd(int fd) { read_fd_ = fd; }
-  void set_write_fd(int fd) { write_fd_ = fd; }
-
- private:
-  // The textual content of the code this object is testing.
-  const char* const statement_;
-  // The regular expression which test output must match.
-  const RE* const regex_;
-  // True if the death test successfully forked.
-  bool forked_;
-  // PID of child process during death test; 0 in the child process itself.
-  pid_t child_pid_;
-  // File descriptors for communicating the death test's status byte.
-  int read_fd_;   // Always -1 in the child process.
-  int write_fd_;  // Always -1 in the parent process.
-  // The exit status of the child process.
-  int status_;
-  // How the death test concluded.
-  DeathTestOutcome outcome_;
-};
-
-// Constructs a ForkingDeathTest.
-ForkingDeathTest::ForkingDeathTest(const char* statement, const RE* regex)
-    : DeathTest(),
-      statement_(statement),
-      regex_(regex),
-      forked_(false),
-      child_pid_(-1),
-      read_fd_(-1),
-      write_fd_(-1),
-      status_(-1),
-      outcome_(IN_PROGRESS) {
-}
-
-// Reads an internal failure message from a file descriptor, then calls
-// LOG(FATAL) with that message.  Called from a death test parent process
-// to read a failure message from the death test child process.
-static void FailFromInternalError(int fd) {
-  Message error;
-  char buffer[256];
-  ssize_t num_read;
-
-  do {
-    while ((num_read = read(fd, buffer, 255)) > 0) {
-      buffer[num_read] = '\0';
-      error << buffer;
-    }
-  } while (num_read == -1 && errno == EINTR);
-
-  // TODO(smcafee):  Maybe just FAIL the test instead?
-  if (num_read == 0) {
-    GTEST_LOG(FATAL, error);
-  } else {
-    GTEST_LOG(FATAL,
-              Message() << "Error while reading death test internal: "
-              << strerror(errno) << " [" << errno << "]");
-  }
-}
-
-// Waits for the child in a death test to exit, returning its exit
-// status, or 0 if no child process exists.  As a side effect, sets the
-// outcome data member.
-int ForkingDeathTest::Wait() {
-  if (!forked_)
-    return 0;
-
-  // The read() here blocks until data is available (signifying the
-  // failure of the death test) or until the pipe is closed (signifying
-  // its success), so it's okay to call this in the parent before
-  // the child process has exited.
-  char flag;
-  ssize_t bytes_read;
-
-  do {
-    bytes_read = read(read_fd_, &flag, 1);
-  } while (bytes_read == -1 && errno == EINTR);
-
-  if (bytes_read == 0) {
-    outcome_ = DIED;
-  } else if (bytes_read == 1) {
-    switch (flag) {
-      case kDeathTestReturned:
-        outcome_ = RETURNED;
-        break;
-      case kDeathTestLived:
-        outcome_ = LIVED;
-        break;
-      case kDeathTestInternalError:
-        FailFromInternalError(read_fd_);  // Does not return.
-        break;
-      default:
-        GTEST_LOG(FATAL,
-                  Message() << "Death test child process reported unexpected "
-                  << "status byte (" << static_cast<unsigned int>(flag)
-                  << ")");
-    }
-  } else {
-    GTEST_LOG(FATAL,
-              Message() << "Read from death test child process failed: "
-              << strerror(errno));
-  }
-
-  GTEST_DEATH_TEST_CHECK_SYSCALL(close(read_fd_));
-  GTEST_DEATH_TEST_CHECK_SYSCALL(waitpid(child_pid_, &status_, 0));
-  return status_;
-}
-
-// Assesses the success or failure of a death test, using both private
-// members which have previously been set, and one argument:
-//
-// Private data members:
-//   outcome:  an enumeration describing how the death test
-//             concluded: DIED, LIVED, or RETURNED.  The death test fails
-//             in the latter two cases
-//   status:   the exit status of the child process, in the format
-//             specified by wait(2)
-//   regex:    a regular expression object to be applied to
-//             the test's captured standard error output; the death test
-//             fails if it does not match
-//
-// Argument:
-//   status_ok: true if exit_status is acceptable in the context of
-//              this particular death test, which fails if it is false
-//
-// Returns true iff all of the above conditions are met.  Otherwise, the
-// first failing condition, in the order given above, is the one that is
-// reported. Also sets the static variable last_death_test_message.
-bool ForkingDeathTest::Passed(bool status_ok) {
-  if (!forked_)
-    return false;
-
-#if GTEST_HAS_GLOBAL_STRING
-  const ::string error_message = GetCapturedStderr();
-#else
-  const ::std::string error_message = GetCapturedStderr();
-#endif  // GTEST_HAS_GLOBAL_STRING
-
-  bool success = false;
-  Message buffer;
-
-  buffer << "Death test: " << statement_ << "\n";
-  switch (outcome_) {
-    case LIVED:
-      buffer << "    Result: failed to die.\n"
-             << " Error msg: " << error_message;
-      break;
-    case RETURNED:
-      buffer << "    Result: illegal return in test statement.\n"
-             << " Error msg: " << error_message;
-      break;
-    case DIED:
-      if (status_ok) {
-        if (RE::PartialMatch(error_message, *regex_)) {
-          success = true;
-        } else {
-          buffer << "    Result: died but not with expected error.\n"
-                 << "  Expected: " << regex_->pattern() << "\n"
-                 << "Actual msg: " << error_message;
-        }
-      } else {
-        buffer << "    Result: died but not with expected exit code:\n"
-               << "            " << ExitSummary(status_) << "\n";
-      }
-      break;
-    default:
-      GTEST_LOG(FATAL,
-                "DeathTest::Passed somehow called before conclusion of test");
-  }
-
-  last_death_test_message = buffer.GetString();
-  return success;
-}
-
-// Signals that the death test code which should have exited, didn't.
-// Should be called only in a death test child process.
-// Writes a status byte to the child's status file desriptor, then
-// calls _exit(1).
-void ForkingDeathTest::Abort(AbortReason reason) {
-  // The parent process considers the death test to be a failure if
-  // it finds any data in our pipe.  So, here we write a single flag byte
-  // to the pipe, then exit.
-  const char flag =
-      reason == TEST_DID_NOT_DIE ? kDeathTestLived : kDeathTestReturned;
-  GTEST_DEATH_TEST_CHECK_SYSCALL(write(write_fd_, &flag, 1));
-  GTEST_DEATH_TEST_CHECK_SYSCALL(close(write_fd_));
-  _exit(1);  // Exits w/o any normal exit hooks (we were supposed to crash)
-}
-
-// A concrete death test class that forks, then immediately runs the test
-// in the child process.
-class NoExecDeathTest : public ForkingDeathTest {
- public:
-  NoExecDeathTest(const char* statement, const RE* regex) :
-      ForkingDeathTest(statement, regex) { }
-  virtual TestRole AssumeRole();
-};
-
-// The AssumeRole process for a fork-and-run death test.  It implements a
-// straightforward fork, with a simple pipe to transmit the status byte.
-DeathTest::TestRole NoExecDeathTest::AssumeRole() {
-  const size_t thread_count = GetThreadCount();
-  if (thread_count != 1) {
-    GTEST_LOG(WARNING, DeathTestThreadWarning(thread_count));
-  }
-
-  int pipe_fd[2];
-  GTEST_DEATH_TEST_CHECK(pipe(pipe_fd) != -1);
-
-  last_death_test_message = "";
-  CaptureStderr();
-  // When we fork the process below, the log file buffers are copied, but the
-  // file descriptors are shared.  We flush all log files here so that closing
-  // the file descriptors in the child process doesn't throw off the
-  // synchronization between descriptors and buffers in the parent process.
-  // This is as close to the fork as possible to avoid a race condition in case
-  // there are multiple threads running before the death test, and another
-  // thread writes to the log file.
-  FlushInfoLog();
-
-  const pid_t child_pid = fork();
-  GTEST_DEATH_TEST_CHECK(child_pid != -1);
-  set_child_pid(child_pid);
-  if (child_pid == 0) {
-    GTEST_DEATH_TEST_CHECK_SYSCALL(close(pipe_fd[0]));
-    set_write_fd(pipe_fd[1]);
-    // Redirects all logging to stderr in the child process to prevent
-    // concurrent writes to the log files.  We capture stderr in the parent
-    // process and append the child process' output to a log.
-    LogToStderr();
-    return EXECUTE_TEST;
-  } else {
-    GTEST_DEATH_TEST_CHECK_SYSCALL(close(pipe_fd[1]));
-    set_read_fd(pipe_fd[0]);
-    set_forked(true);
-    return OVERSEE_TEST;
-  }
-}
-
-// A concrete death test class that forks and re-executes the main
-// program from the beginning, with command-line flags set that cause
-// only this specific death test to be run.
-class ExecDeathTest : public ForkingDeathTest {
- public:
-  ExecDeathTest(const char* statement, const RE* regex,
-                const char* file, int line) :
-      ForkingDeathTest(statement, regex), file_(file), line_(line) { }
-  virtual TestRole AssumeRole();
- private:
-  // The name of the file in which the death test is located.
-  const char* const file_;
-  // The line number on which the death test is located.
-  const int line_;
-};
-
-// Utility class for accumulating command-line arguments.
-class Arguments {
- public:
-  Arguments() {
-    args_.push_back(NULL);
-  }
-  ~Arguments() {
-    for (std::vector<char*>::iterator i = args_.begin();
-         i + 1 != args_.end();
-         ++i) {
-      free(*i);
-    }
-  }
-  void AddArgument(const char* argument) {
-    args_.insert(args_.end() - 1, strdup(argument));
-  }
-
-  template <typename Str>
-  void AddArguments(const ::std::vector<Str>& arguments) {
-    for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
-         i != arguments.end();
-         ++i) {
-      args_.insert(args_.end() - 1, strdup(i->c_str()));
-    }
-  }
-  char* const* Argv() {
-    return &args_[0];
-  }
- private:
-  std::vector<char*> args_;
-};
-
-// A struct that encompasses the arguments to the child process of a
-// threadsafe-style death test process.
-struct ExecDeathTestArgs {
-  char* const* argv;  // Command-line arguments for the child's call to exec
-  int close_fd;       // File descriptor to close; the read end of a pipe
-};
-
-// The main function for a threadsafe-style death test child process.
-static int ExecDeathTestChildMain(void* child_arg) {
-  ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
-  GTEST_DEATH_TEST_CHECK_SYSCALL(close(args->close_fd));
-  execve(args->argv[0], args->argv, environ);
-  DeathTestAbort("execve failed: %s", strerror(errno));
-  return EXIT_FAILURE;
-}
-
-// Two utility routines that together determine the direction the stack
-// grows.
-// This could be accomplished more elegantly by a single recursive
-// function, but we want to guard against the unlikely possibility of
-// a smart compiler optimizing the recursion away.
-static bool StackLowerThanAddress(const void* ptr) {
-  int dummy;
-  return &dummy < ptr;
-}
-
-static bool StackGrowsDown() {
-  int dummy;
-  return StackLowerThanAddress(&dummy);
-}
-
-// A threadsafe implementation of fork(2) for threadsafe-style death tests
-// that uses clone(2).  It dies with an error message if anything goes
-// wrong.
-static pid_t ExecDeathTestFork(char* const* argv, int close_fd) {
-  static const bool stack_grows_down = StackGrowsDown();
-  const size_t stack_size = getpagesize();
-  void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
-                           MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
-  GTEST_DEATH_TEST_CHECK(stack != MAP_FAILED);
-  void* const stack_top =
-      static_cast<char*>(stack) + (stack_grows_down ? stack_size : 0);
-  ExecDeathTestArgs args = { argv, close_fd };
-  const pid_t child_pid = clone(&ExecDeathTestChildMain, stack_top,
-                                SIGCHLD, &args);
-  GTEST_DEATH_TEST_CHECK(child_pid != -1);
-  GTEST_DEATH_TEST_CHECK(munmap(stack, stack_size) != -1);
-  return child_pid;
-}
-
-// The AssumeRole process for a fork-and-exec death test.  It re-executes the
-// main program from the beginning, setting the --gtest_filter
-// and --gtest_internal_run_death_test flags to cause only the current
-// death test to be re-run.
-DeathTest::TestRole ExecDeathTest::AssumeRole() {
-  const UnitTestImpl* const impl = GetUnitTestImpl();
-  const InternalRunDeathTestFlag* const flag =
-      impl->internal_run_death_test_flag();
-  const TestInfo* const info = impl->current_test_info();
-  const int death_test_index = info->result()->death_test_count();
-
-  if (flag != NULL) {
-    set_write_fd(flag->status_fd);
-    return EXECUTE_TEST;
-  }
-
-  int pipe_fd[2];
-  GTEST_DEATH_TEST_CHECK(pipe(pipe_fd) != -1);
-  // Clear the close-on-exec flag on the write end of the pipe, lest
-  // it be closed when the child process does an exec:
-  GTEST_DEATH_TEST_CHECK(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
-
-  const String filter_flag =
-      String::Format("--%s%s=%s.%s",
-                     GTEST_FLAG_PREFIX, kFilterFlag,
-                     info->test_case_name(), info->name());
-  const String internal_flag =
-      String::Format("--%s%s=%s:%d:%d:%d",
-                     GTEST_FLAG_PREFIX, kInternalRunDeathTestFlag, file_, line_,
-                     death_test_index, pipe_fd[1]);
-  Arguments args;
-  args.AddArguments(GetArgvs());
-  args.AddArgument("--logtostderr");
-  args.AddArgument(filter_flag.c_str());
-  args.AddArgument(internal_flag.c_str());
-
-  last_death_test_message = "";
-
-  CaptureStderr();
-  // See the comment in NoExecDeathTest::AssumeRole for why the next line
-  // is necessary.
-  FlushInfoLog();
-
-  const pid_t child_pid = ExecDeathTestFork(args.Argv(), pipe_fd[0]);
-  GTEST_DEATH_TEST_CHECK_SYSCALL(close(pipe_fd[1]));
-  set_child_pid(child_pid);
-  set_read_fd(pipe_fd[0]);
-  set_forked(true);
-  return OVERSEE_TEST;
-}
-
-// Creates a concrete DeathTest-derived class that depends on the
-// --gtest_death_test_style flag, and sets the pointer pointed to
-// by the "test" argument to its address.  If the test should be
-// skipped, sets that pointer to NULL.  Returns true, unless the
-// flag is set to an invalid value.
-bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
-                                     const char* file, int line,
-                                     DeathTest** test) {
-  UnitTestImpl* const impl = GetUnitTestImpl();
-  const InternalRunDeathTestFlag* const flag =
-      impl->internal_run_death_test_flag();
-  const int death_test_index = impl->current_test_info()
-      ->increment_death_test_count();
-
-  if (flag != NULL) {
-    if (death_test_index > flag->index) {
-      last_death_test_message = String::Format(
-          "Death test count (%d) somehow exceeded expected maximum (%d)",
-          death_test_index, flag->index);
-      return false;
-    }
-
-    if (!(flag->file == file && flag->line == line &&
-          flag->index == death_test_index)) {
-      *test = NULL;
-      return true;
-    }
-  }
-
-  if (GTEST_FLAG(death_test_style) == "threadsafe") {
-    *test = new ExecDeathTest(statement, regex, file, line);
-  } else if (GTEST_FLAG(death_test_style) == "fast") {
-    *test = new NoExecDeathTest(statement, regex);
-  } else {
-    last_death_test_message = String::Format(
-        "Unknown death test style \"%s\" encountered",
-        GTEST_FLAG(death_test_style).c_str());
-    return false;
-  }
-
-  return true;
-}
-
-// Splits a given string on a given delimiter, populating a given
-// vector with the fields.  GTEST_HAS_DEATH_TEST implies that we have
-// ::std::string, so we can use it here.
-static void SplitString(const ::std::string& str, char delimiter,
-                        ::std::vector< ::std::string>* dest) {
-  ::std::vector< ::std::string> parsed;
-  ::std::string::size_type pos = 0;
-  while (true) {
-    const ::std::string::size_type colon = str.find(':', pos);
-    if (colon == ::std::string::npos) {
-      parsed.push_back(str.substr(pos));
-      break;
-    } else {
-      parsed.push_back(str.substr(pos, colon - pos));
-      pos = colon + 1;
-    }
-  }
-  dest->swap(parsed);
-}
-
-// Attempts to parse a string into a positive integer.  Returns true
-// if that is possible.  GTEST_HAS_DEATH_TEST implies that we have
-// ::std::string, so we can use it here.
-static bool ParsePositiveInt(const ::std::string& str, int* number) {
-  // Fail fast if the given string does not begin with a digit;
-  // this bypasses strtol's "optional leading whitespace and plus
-  // or minus sign" semantics, which are undesirable here.
-  if (str.empty() || !isdigit(str[0])) {
-    return false;
-  }
-  char* endptr;
-  const long parsed = strtol(str.c_str(), &endptr, 10);  // NOLINT
-  if (*endptr == '\0' && parsed <= INT_MAX) {
-    *number = static_cast<int>(parsed);
-    return true;
-  } else {
-    return false;
-  }
-}
-
-// Returns a newly created InternalRunDeathTestFlag object with fields
-// initialized from the GTEST_FLAG(internal_run_death_test) flag if
-// the flag is specified; otherwise returns NULL.
-InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
-  if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
-
-  InternalRunDeathTestFlag* const internal_run_death_test_flag =
-      new InternalRunDeathTestFlag;
-  // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
-  // can use it here.
-  ::std::vector< ::std::string> fields;
-  SplitString(GTEST_FLAG(internal_run_death_test).c_str(), ':', &fields);
-  if (fields.size() != 4
-      || !ParsePositiveInt(fields[1], &internal_run_death_test_flag->line)
-      || !ParsePositiveInt(fields[2], &internal_run_death_test_flag->index)
-      || !ParsePositiveInt(fields[3],
-                           &internal_run_death_test_flag->status_fd)) {
-    DeathTestAbort("Bad --gtest_internal_run_death_test flag: %s",
-                   GTEST_FLAG(internal_run_death_test).c_str());
-  }
-  internal_run_death_test_flag->file = fields[0].c_str();
-  return internal_run_death_test_flag;
-}
-
-}  // namespace internal
-
-#endif  // GTEST_HAS_DEATH_TEST
-
-}  // namespace testing

src/gtest/gtest-death-test.h

-// Copyright 2005, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Author: wan@google.com (Zhanyong Wan)
-//
-// The Google C++ Testing Framework (Google Test)
-//
-// This header file defines the public API for death tests.  It is
-// #included by gtest.h so a user doesn't need to include this
-// directly.
-
-#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
-#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
-
-#include <gtest/internal/gtest-death-test-internal.h>
-
-namespace testing {
-
-// This flag controls the style of death tests.  Valid values are "threadsafe",
-// meaning that the death test child process will re-execute the test binary
-// from the start, running only a single death test, or "fast",
-// meaning that the child process will execute the test logic immediately
-// after forking.
-GTEST_DECLARE_string(death_test_style);
-
-#ifdef GTEST_HAS_DEATH_TEST
-
-// The following macros are useful for writing death tests.
-
-// Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is
-// executed:
-//
-//   1. The assertion fails immediately if there are more than one
-//   active threads.  This is because it's safe to fork() only when
-//   there is a single thread.
-//
-//   2. The parent process forks a sub-process and runs the death test
-//   in it; the sub-process exits with code 0 at the end of the death
-//   test, if it hasn't exited already.
-//
-//   3. The parent process waits for the sub-process to terminate.
-//
-//   4. The parent process checks the exit code and error message of
-//   the sub-process.
-//
-// Note:
-//
-// It's not safe to call exit() if the current process is forked from
-// a multi-threaded process, so people usually call _exit() instead in
-// such a case.  However, we are not concerned with this as we run
-// death tests only when there is a single thread.  Since exit() has a
-// cleaner semantics (it also calls functions registered with atexit()
-// and on_exit()), this macro calls exit() instead of _exit() to
-// terminate the child process.
-//
-// Examples:
-//
-//   ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number");
-//   for (int i = 0; i < 5; i++) {
-//     EXPECT_DEATH(server.ProcessRequest(i),
-//                  "Invalid request .* in ProcessRequest()")
-//         << "Failed to die on request " << i);
-//   }
-//
-//   ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting");
-//
-//   bool KilledBySIGHUP(int exit_code) {
-//     return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP;
-//   }
-//
-//   ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");
-
-// Asserts that a given statement causes the program to exit, with an
-// integer exit status that satisfies predicate, and emitting error output
-// that matches regex.
-#define ASSERT_EXIT(statement, predicate, regex) \
-  GTEST_DEATH_TEST(statement, predicate, regex, GTEST_FATAL_FAILURE)
-
-// Like ASSERT_EXIT, but continues on to successive tests in the
-// test case, if any:
-#define EXPECT_EXIT(statement, predicate, regex) \
-  GTEST_DEATH_TEST(statement, predicate, regex, GTEST_NONFATAL_FAILURE)
-
-// Asserts that a given statement causes the program to exit, either by
-// explicitly exiting with a nonzero exit code or being killed by a
-// signal, and emitting error output that matches regex.
-#define ASSERT_DEATH(statement, regex) \
-  ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
-
-// Like ASSERT_DEATH, but continues on to successive tests in the
-// test case, if any:
-#define EXPECT_DEATH(statement, regex) \
-  EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
-
-// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
-
-// Tests that an exit code describes a normal exit with a given exit code.
-class ExitedWithCode {
- public:
-  explicit ExitedWithCode(int exit_code);
-  bool operator()(int exit_status) const;
- private:
-  const int exit_code_;
-};
-
-// Tests that an exit code describes an exit due to termination by a
-// given signal.
-class KilledBySignal {
- public:
-  explicit KilledBySignal(int signum);
-  bool operator()(int exit_status) const;
- private:
-  const int signum_;
-};
-
-// EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.
-// The death testing framework causes this to have interesting semantics,
-// since the sideeffects of the call are only visible in opt mode, and not
-// in debug mode.
-//
-// In practice, this can be used to test functions that utilize the
-// LOG(DFATAL) macro using the following style:
-//
-// int DieInDebugOr12(int* sideeffect) {
-//   if (sideeffect) {
-//     *sideeffect = 12;
-//   }
-//   LOG(DFATAL) << "death";
-//   return 12;
-// }
-//
-// TEST(TestCase, TestDieOr12WorksInDgbAndOpt) {
-//   int sideeffect = 0;
-//   // Only asserts in dbg.
-//   EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death");
-//
-// #ifdef NDEBUG
-//   // opt-mode has sideeffect visible.
-//   EXPECT_EQ(12, sideeffect);
-// #else
-//   // dbg-mode no visible sideeffect.
-//   EXPECT_EQ(0, sideeffect);
-// #endif
-// }
-//
-// This will assert that DieInDebugReturn12InOpt() crashes in debug
-// mode, usually due to a DCHECK or LOG(DFATAL), but returns the
-// appropriate fallback value (12 in this case) in opt mode. If you
-// need to test that a function has appropriate side-effects in opt
-// mode, include assertions against the side-effects.  A general
-// pattern for this is:
-//
-// EXPECT_DEBUG_DEATH({
-//   // Side-effects here will have an effect after this statement in
-//   // opt mode, but none in debug mode.
-//   EXPECT_EQ(12, DieInDebugOr12(&sideeffect));
-// }, "death");
-//
-#ifdef NDEBUG
-
-#define EXPECT_DEBUG_DEATH(statement, regex) \
-  do { statement; } while (false)
-
-#define ASSERT_DEBUG_DEATH(statement, regex) \
-  do { statement; } while (false)
-
-#else
-
-#define EXPECT_DEBUG_DEATH(statement, regex) \
-  EXPECT_DEATH(statement, regex)
-
-#define ASSERT_DEBUG_DEATH(statement, regex) \
-  ASSERT_DEATH(statement, regex)
-
-#endif  // NDEBUG for EXPECT_DEBUG_DEATH
-#endif  // GTEST_HAS_DEATH_TEST
-}  // namespace testing
-
-#endif  // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_

src/gtest/gtest-filepath.cc

-// Copyright 2008, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Authors: keith.ray@gmail.com (Keith Ray)
-
-#include <gtest/internal/gtest-filepath.h>
-#include <gtest/internal/gtest-port.h>
-
-#ifdef _WIN32
-#include <direct.h>
-#include <io.h>
-#endif  // _WIN32
-
-#include <sys/stat.h>
-
-#include <gtest/internal/gtest-string.h>
-
-namespace testing {
-namespace internal {
-
-#ifdef GTEST_OS_WINDOWS