Initial import.

This commit is contained in:
shiqian 2008-07-03 22:38:12 +00:00
commit d201456903
78 changed files with 25998 additions and 0 deletions

3
CHANGES Normal file
View File

@ -0,0 +1,3 @@
Changes for 1.0.0:
* Initial Open Source release of Google Test

25
CONTRIBUTORS Normal file
View File

@ -0,0 +1,25 @@
# 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>
Kenton Varda <kenton@google.com>
Markus Heule <markus.heule@gmail.com>
Mika Raento <mikie@iki.fi>
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>

28
COPYING Normal file
View File

@ -0,0 +1,28 @@
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.

250
Makefile.am Normal file
View File

@ -0,0 +1,250 @@
# Automake file
# Nonstandard package files for distribution
EXTRA_DIST = \
CHANGES \
CONTRIBUTORS \
scripts/gen_gtest_pred_impl.py
# TODO(wan@google.com): integrate scripts/gen_gtest_pred_impl.py into
# the build system such that a user can specify the maximum predicate
# arity here and have the script automatically generate the
# corresponding .h and .cc files.
# Scripts and utilities
bin_SCRIPTS = scripts/gtest-config
CLEANFILES = $(bin_SCRIPTS)
# Distribute and install M4 macro
m4datadir = $(datadir)/aclocal
m4data_DATA = m4/gtest.m4
EXTRA_DIST += $(m4data_DATA)
# We define the global AM_CPPFLAGS as everything we compile includes from these
# directories.
AM_CPPFLAGS = -I$(srcdir) -I$(srcdir)/include
# Build rules for libraries.
lib_LTLIBRARIES = lib/libgtest.la lib/libgtest_main.la
lib_libgtest_la_SOURCES = src/gtest.cc \
src/gtest-death-test.cc \
src/gtest-filepath.cc \
src/gtest-internal-inl.h \
src/gtest-port.cc
pkginclude_HEADERS = include/gtest/gtest.h \
include/gtest/gtest-death-test.h \
include/gtest/gtest-message.h \
include/gtest/gtest-spi.h \
include/gtest/gtest_pred_impl.h \
include/gtest/gtest_prod.h
pkginclude_internaldir = $(pkgincludedir)/internal
pkginclude_internal_HEADERS = \
include/gtest/internal/gtest-death-test-internal.h \
include/gtest/internal/gtest-filepath.h \
include/gtest/internal/gtest-internal.h \
include/gtest/internal/gtest-port.h \
include/gtest/internal/gtest-string.h
lib_libgtest_main_la_SOURCES = src/gtest_main.cc
lib_libgtest_main_la_LIBADD = lib/libgtest.la
# Bulid rules for samples and tests. Automake's naming for some of
# these variables isn't terribly obvious, so this is a brief
# reference:
#
# TESTS -- Programs run automatically by "make check"
# check_PROGRAMS -- Programs built by "make check" but not necessarily run
noinst_LTLIBRARIES = samples/libsamples.la
samples_libsamples_la_SOURCES = samples/sample1.cc \
samples/sample1.h \
samples/sample2.cc \
samples/sample2.h \
samples/sample3-inl.h \
samples/sample4.cc \
samples/sample4.h
TESTS=
TESTS_ENVIRONMENT = GTEST_SOURCE_DIR="$(srcdir)/test" \
GTEST_BUILD_DIR="$(top_builddir)/test"
check_PROGRAMS=
TESTS += samples/sample1_unittest
check_PROGRAMS += samples/sample1_unittest
samples_sample1_unittest_SOURCES = samples/sample1_unittest.cc
samples_sample1_unittest_LDADD = lib/libgtest_main.la \
samples/libsamples.la
TESTS += samples/sample2_unittest
check_PROGRAMS += samples/sample2_unittest
samples_sample2_unittest_SOURCES = samples/sample2_unittest.cc
samples_sample2_unittest_LDADD = lib/libgtest_main.la \
samples/libsamples.la
TESTS += samples/sample3_unittest
check_PROGRAMS += samples/sample3_unittest
samples_sample3_unittest_SOURCES = samples/sample3_unittest.cc
samples_sample3_unittest_LDADD = lib/libgtest_main.la \
samples/libsamples.la
TESTS += samples/sample4_unittest
check_PROGRAMS += samples/sample4_unittest
samples_sample4_unittest_SOURCES = samples/sample4_unittest.cc
samples_sample4_unittest_LDADD = lib/libgtest_main.la \
samples/libsamples.la
TESTS += samples/sample5_unittest
check_PROGRAMS += samples/sample5_unittest
samples_sample5_unittest_SOURCES = samples/sample5_unittest.cc
samples_sample5_unittest_LDADD = lib/libgtest_main.la \
samples/libsamples.la
TESTS += test/gtest_unittest
check_PROGRAMS += test/gtest_unittest
test_gtest_unittest_SOURCES = test/gtest_unittest.cc
test_gtest_unittest_LDADD = lib/libgtest.la
TESTS += test/gtest-death-test_test
check_PROGRAMS += test/gtest-death-test_test
test_gtest_death_test_test_SOURCES = test/gtest-death-test_test.cc
test_gtest_death_test_test_CXXFLAGS = $(AM_CXXFLAGS) -pthread
test_gtest_death_test_test_LDADD = -lpthread lib/libgtest_main.la
TESTS += test/gtest-filepath_test
check_PROGRAMS += test/gtest-filepath_test
test_gtest_filepath_test_SOURCES = test/gtest-filepath_test.cc
test_gtest_filepath_test_LDADD = lib/libgtest_main.la
TESTS += test/gtest-message_test
check_PROGRAMS += test/gtest-message_test
test_gtest_message_test_SOURCES = test/gtest-message_test.cc
test_gtest_message_test_LDADD = lib/libgtest_main.la
TESTS += test/gtest-options_test
check_PROGRAMS += test/gtest-options_test
test_gtest_options_test_SOURCES = test/gtest-options_test.cc
test_gtest_options_test_LDADD = lib/libgtest_main.la
TESTS += test/gtest_pred_impl_unittest
check_PROGRAMS += test/gtest_pred_impl_unittest
test_gtest_pred_impl_unittest_SOURCES = test/gtest_pred_impl_unittest.cc
test_gtest_pred_impl_unittest_LDADD = lib/libgtest_main.la
TESTS += test/gtest_environment_test
check_PROGRAMS += test/gtest_environment_test
test_gtest_environment_test_SOURCES = test/gtest_environment_test.cc
test_gtest_environment_test_LDADD = lib/libgtest.la
TESTS += test/gtest_no_test_unittest
check_PROGRAMS += test/gtest_no_test_unittest
test_gtest_no_test_unittest_SOURCES = test/gtest_no_test_unittest.cc
test_gtest_no_test_unittest_LDADD = lib/libgtest.la
TESTS += test/gtest_main_unittest
check_PROGRAMS += test/gtest_main_unittest
test_gtest_main_unittest_SOURCES = test/gtest_main_unittest.cc
test_gtest_main_unittest_LDADD = lib/libgtest_main.la
TESTS += test/gtest_prod_test
check_PROGRAMS += test/gtest_prod_test
test_gtest_prod_test_SOURCES = test/gtest_prod_test.cc \
test/production.cc \
test/production.h
test_gtest_prod_test_LDADD = lib/libgtest_main.la
TESTS += test/gtest_repeat_test
check_PROGRAMS += test/gtest_repeat_test
test_gtest_repeat_test_SOURCES = test/gtest_repeat_test.cc
test_gtest_repeat_test_LDADD = lib/libgtest.la
TESTS += test/gtest_stress_test
check_PROGRAMS += test/gtest_stress_test
test_gtest_stress_test_SOURCES = test/gtest_stress_test.cc
test_gtest_stress_test_LDADD = lib/libgtest.la
# The following tests depend on the presence of a Python installation and are
# keyed off of it. TODO(chandlerc@google.com): While we currently only attempt
# to build and execute these tests if Autoconf has found Python v2.4 on the
# system, we don't use the PYTHON variable it specified as the valid
# interpreter. The problem is that TESTS_ENVIRONMENT is a global variable, and
# thus we cannot distinguish between C++ unit tests and Python unit tests.
if HAVE_PYTHON
check_SCRIPTS =
# These two Python modules are used by multiple Pythong tests below.
check_SCRIPTS += test/gtest_test_utils.py \
test/gtest_xml_test_utils.py
check_PROGRAMS += test/gtest_output_test_
test_gtest_output_test__SOURCES = test/gtest_output_test_.cc
test_gtest_output_test__LDADD = lib/libgtest.la
check_SCRIPTS += test/gtest_output_test.py
EXTRA_DIST += test/gtest_output_test_golden_lin.txt \
test/gtest_output_test_golden_win.txt
TESTS += test/gtest_output_test.py
check_PROGRAMS += test/gtest_color_test_
test_gtest_color_test__SOURCES = test/gtest_color_test_.cc
test_gtest_color_test__LDADD = lib/libgtest.la
check_SCRIPTS += test/gtest_color_test.py
TESTS += test/gtest_color_test.py
check_PROGRAMS += test/gtest_env_var_test_
test_gtest_env_var_test__SOURCES = test/gtest_env_var_test_.cc
test_gtest_env_var_test__LDADD = lib/libgtest.la
check_SCRIPTS += test/gtest_env_var_test.py
TESTS += test/gtest_env_var_test.py
check_PROGRAMS += test/gtest_filter_unittest_
test_gtest_filter_unittest__SOURCES = test/gtest_filter_unittest_.cc
test_gtest_filter_unittest__LDADD = lib/libgtest.la
check_SCRIPTS += test/gtest_filter_unittest.py
TESTS += test/gtest_filter_unittest.py
check_PROGRAMS += test/gtest_break_on_failure_unittest_
test_gtest_break_on_failure_unittest__SOURCES = \
test/gtest_break_on_failure_unittest_.cc
test_gtest_break_on_failure_unittest__LDADD = lib/libgtest.la
check_SCRIPTS += test/gtest_break_on_failure_unittest.py
TESTS += test/gtest_break_on_failure_unittest.py
check_PROGRAMS += test/gtest_list_tests_unittest_
test_gtest_list_tests_unittest__SOURCES = test/gtest_list_tests_unittest_.cc
test_gtest_list_tests_unittest__LDADD = lib/libgtest.la
check_SCRIPTS += test/gtest_list_tests_unittest.py
TESTS += test/gtest_list_tests_unittest.py
check_PROGRAMS += test/gtest_xml_output_unittest_
test_gtest_xml_output_unittest__SOURCES = test/gtest_xml_output_unittest_.cc
test_gtest_xml_output_unittest__LDADD = lib/libgtest_main.la
check_SCRIPTS += test/gtest_xml_output_unittest.py
TESTS += test/gtest_xml_output_unittest.py
check_PROGRAMS += test/gtest_xml_outfile1_test_
test_gtest_xml_outfile1_test__SOURCES = test/gtest_xml_outfile1_test_.cc
test_gtest_xml_outfile1_test__LDADD = lib/libgtest_main.la
check_PROGRAMS += test/gtest_xml_outfile2_test_
test_gtest_xml_outfile2_test__SOURCES = test/gtest_xml_outfile2_test_.cc
test_gtest_xml_outfile2_test__LDADD = lib/libgtest_main.la
check_SCRIPTS += test/gtest_xml_outfiles_test.py
TESTS += test/gtest_xml_outfiles_test.py
check_PROGRAMS += test/gtest_uninitialized_test_
test_gtest_uninitialized_test__SOURCES = test/gtest_uninitialized_test_.cc
test_gtest_uninitialized_test__LDADD = lib/libgtest.la
check_SCRIPTS += test/gtest_uninitialized_test.py
TESTS += test/gtest_uninitialized_test.py
# TODO(wan@google.com): make the build script compile and run the
# negative-compilation tests. (The test/gtest_nc* files are unfinished
# implementation of tests for verifying that certain kinds of misuse
# of Google Test don't compile.)
EXTRA_DIST += $(check_SCRIPTS) \
test/gtest_nc.cc \
test/gtest_nc_test.py
endif

134
README Normal file
View File

@ -0,0 +1,134 @@
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, you are ready to build the library.
### 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
$ make check # Builds and runs all tests - all should pass
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!

0
config_aux/.keep Normal file
View File

43
configure.ac Normal file
View File

@ -0,0 +1,43 @@
AC_INIT([Google C++ Testing Framework],
[1.0.0],
[googletestframework@googlegroups.com],
[gtest])
# Provide various options to initialize the Autoconf and configure processes.
AC_PREREQ([2.59])
AC_CONFIG_SRCDIR([./COPYING])
AC_CONFIG_AUX_DIR([config_aux])
AC_CONFIG_HEADERS([config_aux/config.h])
AC_CONFIG_FILES([Makefile])
AC_CONFIG_FILES([scripts/gtest-config], [chmod +x scripts/gtest-config])
# Initialize Automake with various options. We require at least v1.9, prevent
# pedantic complaints about package files, and enable various distribution
# targets.
AM_INIT_AUTOMAKE([1.9 dist-bzip2 dist-zip foreign subdir-objects])
# Check for programs used in building Google Test.
AC_PROG_CC
AC_PROG_CXX
AC_LANG([C++])
AC_PROG_LIBTOOL
# TODO(chandlerc@google.com): Currently we aren't running the Python tests
# against the interpreter detected by AM_PATH_PYTHON, and so we condition
# HAVE_PYTHON by requiring "python" to be in the PATH, and that interpreter's
# version to be >= 2.4. This will allow the scripts to use a "/usr/bin/env"
# hashbang.
#AM_PATH_PYTHON([2.4],,[:])
PYTHON= # We *do not* allow the user to specify a python interpreter
AC_PATH_PROG([PYTHON],[python],[:])
AS_IF([test "$PYTHON" != ":"],
[AM_PYTHON_CHECK_VERSION([$PYTHON],[2.4],[:],[PYTHON=":"])])
AM_CONDITIONAL([HAVE_PYTHON],[test "$PYTHON" != ":"])
# TODO(chandlerc@google.com) Check for the necessary system headers.
# TODO(chandlerc@google.com) Check the types, structures, and other compiler
# and architecture characteristics.
# Output the generated files. No further autoconf macros may be used.
AC_OUTPUT

View File

@ -0,0 +1,205 @@
// 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_

View File

@ -0,0 +1,236 @@
// 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 Message class.
//
// IMPORTANT NOTE: Due to limitation of the C++ language, we have to
// leave some internal implementation details in this header file.
// They are clearly marked by comments like this:
//
// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
//
// Such code is NOT meant to be used by a user directly, and is subject
// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
// program!
#ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
#if defined(__APPLE__) && !defined(GTEST_NOT_MAC_FRAMEWORK_MODE)
// When using Google Test on the Mac as a framework, all the includes will be
// in the framework headers folder along with gtest.h.
// Define GTEST_NOT_MAC_FRAMEWORK_MODE if you are building Google Test on
// the Mac and are not using it as a framework.
// More info on frameworks available here:
// http://developer.apple.com/documentation/MacOSX/Conceptual/BPFrameworks/
// Concepts/WhatAreFrameworks.html.
#include "gtest-string.h" // NOLINT
#include "gtest-internal.h" // NOLINT
#else
#include <gtest/internal/gtest-string.h>
#include <gtest/internal/gtest-internal.h>
#endif // defined(__APPLE__) && !defined(GTEST_NOT_MAC_FRAMEWORK_MODE)
namespace testing {
// The Message class works like an ostream repeater.
//
// Typical usage:
//
// 1. You stream a bunch of values to a Message object.
// It will remember the text in a StrStream.
// 2. Then you stream the Message object to an ostream.
// This causes the text in the Message to be streamed
// to the ostream.
//
// For example;
//
// testing::Message foo;
// foo << 1 << " != " << 2;
// std::cout << foo;
//
// will print "1 != 2".
//
// Message is not intended to be inherited from. In particular, its
// destructor is not virtual.
//
// Note that StrStream behaves differently in gcc and in MSVC. You
// can stream a NULL char pointer to it in the former, but not in the
// latter (it causes an access violation if you do). The Message
// class hides this difference by treating a NULL char pointer as
// "(null)".
class Message {
private:
// The type of basic IO manipulators (endl, ends, and flush) for
// narrow streams.
typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&);
public:
// Constructs an empty Message.
// We allocate the StrStream separately because it otherwise each use of
// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
// stack frame leading to huge stack frames in some cases; gcc does not reuse
// the stack space.
Message() : ss_(new internal::StrStream) {}
// Copy constructor.
Message(const Message& msg) : ss_(new internal::StrStream) { // NOLINT
*ss_ << msg.GetString();
}
// Constructs a Message from a C-string.
explicit Message(const char* str) : ss_(new internal::StrStream) {
*ss_ << str;
}
~Message() { delete ss_; }
#ifdef __SYMBIAN32__
// Streams a value (either a pointer or not) to this object.
template <typename T>
inline Message& operator <<(const T& value) {
StreamHelper(typename internal::is_pointer<T>::type(), value);
return *this;
}
#else
// Streams a non-pointer value to this object.
template <typename T>
inline Message& operator <<(const T& val) {
::GTestStreamToHelper(ss_, val);
return *this;
}
// Streams a pointer value to this object.
//
// This function is an overload of the previous one. When you
// stream a pointer to a Message, this definition will be used as it
// is more specialized. (The C++ Standard, section
// [temp.func.order].) If you stream a non-pointer, then the
// previous definition will be used.
//
// The reason for this overload is that streaming a NULL pointer to
// ostream is undefined behavior. Depending on the compiler, you
// may get "0", "(nil)", "(null)", or an access violation. To
// ensure consistent result across compilers, we always treat NULL
// as "(null)".
template <typename T>
inline Message& operator <<(T* const& pointer) { // NOLINT
if (pointer == NULL) {
*ss_ << "(null)";
} else {
::GTestStreamToHelper(ss_, pointer);
}
return *this;
}
#endif // __SYMBIAN32__
// Since the basic IO manipulators are overloaded for both narrow
// and wide streams, we have to provide this specialized definition
// of operator <<, even though its body is the same as the
// templatized version above. Without this definition, streaming
// endl or other basic IO manipulators to Message will confuse the
// compiler.
Message& operator <<(BasicNarrowIoManip val) {
*ss_ << val;
return *this;
}
// Instead of 1/0, we want to see true/false for bool values.
Message& operator <<(bool b) {
return *this << (b ? "true" : "false");
}
// These two overloads allow streaming a wide C string to a Message
// using the UTF-8 encoding.
Message& operator <<(const wchar_t* wide_c_str) {
return *this << internal::String::ShowWideCString(wide_c_str);
}
Message& operator <<(wchar_t* wide_c_str) {
return *this << internal::String::ShowWideCString(wide_c_str);
}
#if GTEST_HAS_STD_WSTRING
// Converts the given wide string to a narrow string using the UTF-8
// encoding, and streams the result to this Message object.
Message& operator <<(const ::std::wstring& wstr);
#endif // GTEST_HAS_STD_WSTRING
#if GTEST_HAS_GLOBAL_WSTRING
// Converts the given wide string to a narrow string using the UTF-8
// encoding, and streams the result to this Message object.
Message& operator <<(const ::wstring& wstr);
#endif // GTEST_HAS_GLOBAL_WSTRING
// Gets the text streamed to this object so far as a String.
// Each '\0' character in the buffer is replaced with "\\0".
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
internal::String GetString() const {
return internal::StrStreamToString(ss_);
}
private:
#ifdef __SYMBIAN32__
// These are needed as the Nokia Symbian Compiler cannot decide between
// const T& and const T* in a function template. The Nokia compiler _can_
// decide between class template specializations for T and T*, so a
// tr1::type_traits-like is_pointer works, and we can overload on that.
template <typename T>
inline void StreamHelper(internal::true_type dummy, T* pointer) {
if (pointer == NULL) {
*ss_ << "(null)";
} else {
::GTestStreamToHelper(ss_, pointer);
}
}
template <typename T>
inline void StreamHelper(internal::false_type dummy, const T& value) {
::GTestStreamToHelper(ss_, value);
}
#endif // __SYMBIAN32__
// We'll hold the text streamed to this object here.
internal::StrStream* const ss_;
// We declare (but don't implement) this to prevent the compiler
// from implementing the assignment operator.
void operator=(const Message&);
};
// Streams a Message to an ostream.
inline std::ostream& operator <<(std::ostream& os, const Message& sb) {
return os << sb.GetString();
}
} // namespace testing
#endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_

247
include/gtest/gtest-spi.h Normal file
View File

@ -0,0 +1,247 @@
// Copyright 2007, 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)
//
// Utilities for testing Google Test itself and code that uses Google Test
// (e.g. frameworks built on top of Google Test).
#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
#include <gtest/gtest.h>
namespace testing {
// A copyable object representing the result of a test part (i.e. an
// assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()).
//
// Don't inherit from TestPartResult as its destructor is not virtual.
class TestPartResult {
public:
// C'tor. TestPartResult does NOT have a default constructor.
// Always use this constructor (with parameters) to create a
// TestPartResult object.
TestPartResult(TestPartResultType type,
const char* file_name,
int line_number,
const char* message)
: type_(type),
file_name_(file_name),
line_number_(line_number),
message_(message) {
}
// Gets the outcome of the test part.
TestPartResultType type() const { return type_; }
// Gets the name of the source file where the test part took place, or
// NULL if it's unknown.
const char* file_name() const { return file_name_.c_str(); }
// Gets the line in the source file where the test part took place,
// or -1 if it's unknown.
int line_number() const { return line_number_; }
// Gets the message associated with the test part.
const char* message() const { return message_.c_str(); }
// Returns true iff the test part passed.
bool passed() const { return type_ == TPRT_SUCCESS; }
// Returns true iff the test part failed.
bool failed() const { return type_ != TPRT_SUCCESS; }
// Returns true iff the test part non-fatally failed.
bool nonfatally_failed() const { return type_ == TPRT_NONFATAL_FAILURE; }
// Returns true iff the test part fatally failed.
bool fatally_failed() const { return type_ == TPRT_FATAL_FAILURE; }
private:
TestPartResultType type_;
// The name of the source file where the test part took place, or
// NULL if the source file is unknown.
internal::String file_name_;
// The line in the source file where the test part took place, or -1
// if the line number is unknown.
int line_number_;
internal::String message_; // The test failure message.
};
// Prints a TestPartResult object.
std::ostream& operator<<(std::ostream& os, const TestPartResult& result);
// An array of TestPartResult objects.
//
// We define this class as we cannot use STL containers when compiling
// Google Test with MSVC 7.1 and exceptions disabled.
//
// Don't inherit from TestPartResultArray as its destructor is not
// virtual.
class TestPartResultArray {
public:
TestPartResultArray();
~TestPartResultArray();
// Appends the given TestPartResult to the array.
void Append(const TestPartResult& result);
// Returns the TestPartResult at the given index (0-based).
const TestPartResult& GetTestPartResult(int index) const;
// Returns the number of TestPartResult objects in the array.
int size() const;
private:
// Internally we use a list to simulate the array. Yes, this means
// that random access is O(N) in time, but it's OK for its purpose.
internal::List<TestPartResult>* const list_;
GTEST_DISALLOW_COPY_AND_ASSIGN(TestPartResultArray);
};
// This interface knows how to report a test part result.
class TestPartResultReporterInterface {
public:
virtual ~TestPartResultReporterInterface() {}
virtual void ReportTestPartResult(const TestPartResult& result) = 0;
};
// This helper class can be used to mock out Google Test failure reporting
// so that we can test Google Test or code that builds on Google Test.
//
// An object of this class appends a TestPartResult object to the
// TestPartResultArray object given in the constructor whenever a
// Google Test failure is reported.
class ScopedFakeTestPartResultReporter
: public TestPartResultReporterInterface {
public:
// The c'tor sets this object as the test part result reporter used
// by Google Test. The 'result' parameter specifies where to report the
// results.
explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
// The d'tor restores the previous test part result reporter.
virtual ~ScopedFakeTestPartResultReporter();
// Appends the TestPartResult object to the TestPartResultArray
// received in the constructor.
//
// This method is from the TestPartResultReporterInterface
// interface.
virtual void ReportTestPartResult(const TestPartResult& result);
private:
TestPartResultReporterInterface* const old_reporter_;
TestPartResultArray* const result_;
GTEST_DISALLOW_COPY_AND_ASSIGN(ScopedFakeTestPartResultReporter);
};
namespace internal {
// A helper class for implementing EXPECT_FATAL_FAILURE() and
// EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
// TestPartResultArray contains exactly one failure that has the given
// type and contains the given substring. If that's not the case, a
// non-fatal failure will be generated.
class SingleFailureChecker {
public:
// The constructor remembers the arguments.
SingleFailureChecker(const TestPartResultArray* results,
TestPartResultType type,
const char* substr);
~SingleFailureChecker();
private:
const TestPartResultArray* const results_;
const TestPartResultType type_;
const String substr_;
GTEST_DISALLOW_COPY_AND_ASSIGN(SingleFailureChecker);
};
} // namespace internal
} // namespace testing
// A macro for testing Google Test assertions or code that's expected to
// generate Google Test fatal failures. It verifies that the given
// statement will cause exactly one fatal Google Test failure with 'substr'
// being part of the failure message.
//
// Implementation note: The verification is done in the destructor of
// SingleFailureChecker, to make sure that it's done even when
// 'statement' throws an exception.
//
// Known restrictions:
// - 'statement' cannot reference local non-static variables or
// non-static members of the current object.
// - 'statement' cannot return a value.
// - You cannot stream a failure message to this macro.
#define EXPECT_FATAL_FAILURE(statement, substr) do {\
class GTestExpectFatalFailureHelper {\
public:\
static void Execute() { statement; }\
};\
::testing::TestPartResultArray gtest_failures;\
::testing::internal::SingleFailureChecker gtest_checker(\
&gtest_failures, ::testing::TPRT_FATAL_FAILURE, (substr));\
{\
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
&gtest_failures);\
GTestExpectFatalFailureHelper::Execute();\
}\
} while (false)
// A macro for testing Google Test assertions or code that's expected to
// generate Google Test non-fatal failures. It asserts that the given
// statement will cause exactly one non-fatal Google Test failure with
// 'substr' being part of the failure message.
//
// 'statement' is allowed to reference local variables and members of
// the current object.
//
// Implementation note: The verification is done in the destructor of
// SingleFailureChecker, to make sure that it's done even when
// 'statement' throws an exception or aborts the function.
//
// Known restrictions:
// - You cannot stream a failure message to this macro.
#define EXPECT_NONFATAL_FAILURE(statement, substr) do {\
::testing::TestPartResultArray gtest_failures;\
::testing::internal::SingleFailureChecker gtest_checker(\
&gtest_failures, ::testing::TPRT_NONFATAL_FAILURE, (substr));\
{\
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
&gtest_failures);\
statement;\
}\
} while (false)
#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_

1242
include/gtest/gtest.h Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,368 @@
// 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 06/22/2008 by command
// 'gen_gtest_pred_impl.py 5'. 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 5.
// 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())
// Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use
// this in your code.
template <typename Pred,
typename T1>
AssertionResult AssertPred1Helper(const char* pred_text,
const char* e1,
Pred pred,
const T1& v1) {
if (pred(v1)) return AssertionSuccess();
Message msg;
msg << pred_text << "("
<< e1 << ") evaluates to false, where"
<< "\n" << e1 << " evaluates to " << v1;
return AssertionFailure(msg);
}
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
// Don't use this in your code.
#define GTEST_PRED_FORMAT1(pred_format, v1, on_failure)\
GTEST_ASSERT(pred_format(#v1, v1),\
on_failure)
// Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use
// this in your code.
#define GTEST_PRED1(pred, v1, on_failure)\
GTEST_ASSERT(::testing::AssertPred1Helper(#pred, \
#v1, \
pred, \
v1), on_failure)
// Unary predicate assertion macros.
#define EXPECT_PRED_FORMAT1(pred_format, v1) \
GTEST_PRED_FORMAT1(pred_format, v1, GTEST_NONFATAL_FAILURE)
#define EXPECT_PRED1(pred, v1) \
GTEST_PRED1(pred, v1, GTEST_NONFATAL_FAILURE)
#define ASSERT_PRED_FORMAT1(pred_format, v1) \
GTEST_PRED_FORMAT1(pred_format, v1, GTEST_FATAL_FAILURE)
#define ASSERT_PRED1(pred, v1) \
GTEST_PRED1(pred, v1, GTEST_FATAL_FAILURE)
// Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use
// this in your code.
template <typename Pred,
typename T1,
typename T2>
AssertionResult AssertPred2Helper(const char* pred_text,
const char* e1,
const char* e2,
Pred pred,
const T1& v1,
const T2& v2) {
if (pred(v1, v2)) return AssertionSuccess();
Message msg;
msg << pred_text << "("
<< e1 << ", "
<< e2 << ") evaluates to false, where"
<< "\n" << e1 << " evaluates to " << v1
<< "\n" << e2 << " evaluates to " << v2;
return AssertionFailure(msg);
}
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
// Don't use this in your code.
#define GTEST_PRED_FORMAT2(pred_format, v1, v2, on_failure)\
GTEST_ASSERT(pred_format(#v1, #v2, v1, v2),\
on_failure)
// Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use
// this in your code.
#define GTEST_PRED2(pred, v1, v2, on_failure)\
GTEST_ASSERT(::testing::AssertPred2Helper(#pred, \
#v1, \
#v2, \
pred, \
v1, \
v2), on_failure)
// Binary predicate assertion macros.
#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \
GTEST_PRED_FORMAT2(pred_format, v1, v2, GTEST_NONFATAL_FAILURE)
#define EXPECT_PRED2(pred, v1, v2) \
GTEST_PRED2(pred, v1, v2, GTEST_NONFATAL_FAILURE)
#define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \
GTEST_PRED_FORMAT2(pred_format, v1, v2, GTEST_FATAL_FAILURE)
#define ASSERT_PRED2(pred, v1, v2) \
GTEST_PRED2(pred, v1, v2, GTEST_FATAL_FAILURE)
// Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use
// this in your code.
template <typename Pred,
typename T1,
typename T2,
typename T3>
AssertionResult AssertPred3Helper(const char* pred_text,
const char* e1,
const char* e2,
const char* e3,
Pred pred,
const T1& v1,
const T2& v2,
const T3& v3) {
if (pred(v1, v2, v3)) return AssertionSuccess();
Message msg;
msg << pred_text << "("
<< e1 << ", "
<< e2 << ", "
<< e3 << ") evaluates to false, where"
<< "\n" << e1 << " evaluates to " << v1
<< "\n" << e2 << " evaluates to " << v2
<< "\n" << e3 << " evaluates to " << v3;
return AssertionFailure(msg);
}
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
// Don't use this in your code.
#define GTEST_PRED_FORMAT3(pred_format, v1, v2, v3, on_failure)\
GTEST_ASSERT(pred_format(#v1, #v2, #v3, v1, v2, v3),\
on_failure)
// Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use
// this in your code.
#define GTEST_PRED3(pred, v1, v2, v3, on_failure)\
GTEST_ASSERT(::testing::AssertPred3Helper(#pred, \
#v1, \
#v2, \
#v3, \
pred, \
v1, \
v2, \
v3), on_failure)
// Ternary predicate assertion macros.
#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \
GTEST_PRED_FORMAT3(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE)
#define EXPECT_PRED3(pred, v1, v2, v3) \
GTEST_PRED3(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE)
#define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \
GTEST_PRED_FORMAT3(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE)
#define ASSERT_PRED3(pred, v1, v2, v3) \
GTEST_PRED3(pred, v1, v2, v3, GTEST_FATAL_FAILURE)
// Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use
// this in your code.
template <typename Pred,
typename T1,
typename T2,
typename T3,
typename T4>
AssertionResult AssertPred4Helper(const char* pred_text,
const char* e1,
const char* e2,
const char* e3,
const char* e4,
Pred pred,
const T1& v1,
const T2& v2,
const T3& v3,
const T4& v4) {
if (pred(v1, v2, v3, v4)) return AssertionSuccess();
Message msg;
msg << pred_text << "("
<< e1 << ", "
<< e2 << ", "
<< e3 << ", "
<< e4 << ") evaluates to false, where"
<< "\n" << e1 << " evaluates to " << v1
<< "\n" << e2 << " evaluates to " << v2
<< "\n" << e3 << " evaluates to " << v3
<< "\n" << e4 << " evaluates to " << v4;
return AssertionFailure(msg);
}
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
// Don't use this in your code.
#define GTEST_PRED_FORMAT4(pred_format, v1, v2, v3, v4, on_failure)\
GTEST_ASSERT(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4),\
on_failure)
// Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use
// this in your code.
#define GTEST_PRED4(pred, v1, v2, v3, v4, on_failure)\
GTEST_ASSERT(::testing::AssertPred4Helper(#pred, \
#v1, \
#v2, \
#v3, \
#v4, \
pred, \
v1, \
v2, \
v3, \
v4), on_failure)
// 4-ary predicate assertion macros.
#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
GTEST_PRED_FORMAT4(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE)
#define EXPECT_PRED4(pred, v1, v2, v3, v4) \
GTEST_PRED4(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE)
#define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
GTEST_PRED_FORMAT4(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE)
#define ASSERT_PRED4(pred, v1, v2, v3, v4) \
GTEST_PRED4(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE)
// Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use
// this in your code.
template <typename Pred,
typename T1,
typename T2,
typename T3,
typename T4,
typename T5>
AssertionResult AssertPred5Helper(const char* pred_text,
const char* e1,
const char* e2,
const char* e3,
const char* e4,
const char* e5,
Pred pred,
const T1& v1,
const T2& v2,
const T3& v3,
const T4& v4,
const T5& v5) {
if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
Message msg;
msg << pred_text << "("
<< e1 << ", "
<< e2 << ", "
<< e3 << ", "
<< e4 << ", "
<< e5 << ") evaluates to false, where"
<< "\n" << e1 << " evaluates to " << v1
<< "\n" << e2 << " evaluates to " << v2
<< "\n" << e3 << " evaluates to " << v3
<< "\n" << e4 << " evaluates to " << v4
<< "\n" << e5 << " evaluates to " << v5;
return AssertionFailure(msg);
}
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.
// Don't use this in your code.
#define GTEST_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5, on_failure)\
GTEST_ASSERT(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5),\
on_failure)
// Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use
// this in your code.
#define GTEST_PRED5(pred, v1, v2, v3, v4, v5, on_failure)\
GTEST_ASSERT(::testing::AssertPred5Helper(#pred, \
#v1, \
#v2, \
#v3, \
#v4, \
#v5, \
pred, \
v1, \
v2, \
v3, \
v4, \
v5), on_failure)
// 5-ary predicate assertion macros.
#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
GTEST_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE)
#define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \
GTEST_PRED5(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE)
#define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
GTEST_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE)
#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \
GTEST_PRED5(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE)
#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_

View File

@ -0,0 +1,58 @@
// 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.
//
// Author: wan@google.com (Zhanyong Wan)
//
// Google C++ Testing Framework definitions useful in production code.
#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_
#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_
// When you need to test the private or protected members of a class,
// use the FRIEND_TEST macro to declare your tests as friends of the
// class. For example:
//
// class MyClass {
// private:
// void MyMethod();
// FRIEND_TEST(MyClassTest, MyMethod);
// };
//
// class MyClassTest : public testing::Test {
// // ...
// };
//
// TEST_F(MyClassTest, MyMethod) {
// // Can call MyClass::MyMethod() here.
// }
#define FRIEND_TEST(test_case_name, test_name)\
friend class test_case_name##_##test_name##_Test
#endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_

View File

@ -0,0 +1,201 @@
// 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.
//
// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
//
// The Google C++ Testing Framework (Google Test)
//
// This header file defines internal utilities needed for implementing
// death tests. They are subject to change without notice.
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
#include <gtest/internal/gtest-internal.h>
namespace testing {
namespace internal {
GTEST_DECLARE_string(internal_run_death_test);
// Names of the flags (needed for parsing Google Test flags).
const char kDeathTestStyleFlag[] = "death_test_style";
const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
#ifdef GTEST_HAS_DEATH_TEST
// DeathTest is a class that hides much of the complexity of the
// GTEST_DEATH_TEST macro. It is abstract; its static Create method
// returns a concrete class that depends on the prevailing death test
// style, as defined by the --gtest_death_test_style and/or
// --gtest_internal_run_death_test flags.
// In describing the results of death tests, these terms are used with
// the corresponding definitions:
//
// exit status: The integer exit information in the format specified
// by wait(2)
// exit code: The integer code passed to exit(3), _exit(2), or
// returned from main()
class DeathTest {
public:
// Create returns false if there was an error determining the
// appropriate action to take for the current death test; for example,
// if the gtest_death_test_style flag is set to an invalid value.
// The LastMessage method will return a more detailed message in that
// case. Otherwise, the DeathTest pointer pointed to by the "test"
// argument is set. If the death test should be skipped, the pointer
// is set to NULL; otherwise, it is set to the address of a new concrete
// DeathTest object that controls the execution of the current test.
static bool Create(const char* statement, const RE* regex,
const char* file, int line, DeathTest** test);
DeathTest();
virtual ~DeathTest() { }
// A helper class that aborts a death test when it's deleted.
class ReturnSentinel {
public:
explicit ReturnSentinel(DeathTest* test) : test_(test) { }
~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
private:
DeathTest* const test_;
GTEST_DISALLOW_COPY_AND_ASSIGN(ReturnSentinel);
} GTEST_ATTRIBUTE_UNUSED;
// An enumeration of possible roles that may be taken when a death
// test is encountered. EXECUTE means that the death test logic should
// be executed immediately. OVERSEE means that the program should prepare
// the appropriate environment for a child process to execute the death
// test, then wait for it to complete.
enum TestRole { OVERSEE_TEST, EXECUTE_TEST };
// An enumeration of the two reasons that a test might be aborted.
enum AbortReason { TEST_ENCOUNTERED_RETURN_STATEMENT, TEST_DID_NOT_DIE };
// Assumes one of the above roles.
virtual TestRole AssumeRole() = 0;
// Waits for the death test to finish and returns its status.
virtual int Wait() = 0;
// Returns true if the death test passed; that is, the test process
// exited during the test, its exit status matches a user-supplied
// predicate, and its stderr output matches a user-supplied regular
// expression.
// The user-supplied predicate may be a macro expression rather
// than a function pointer or functor, or else Wait and Passed could
// be combined.
virtual bool Passed(bool exit_status_ok) = 0;
// Signals that the death test did not die as expected.
virtual void Abort(AbortReason reason) = 0;
// Returns a human-readable outcome message regarding the outcome of
// the last death test.
static const char* LastMessage();
private:
GTEST_DISALLOW_COPY_AND_ASSIGN(DeathTest);
};
// Factory interface for death tests. May be mocked out for testing.
class DeathTestFactory {
public:
virtual ~DeathTestFactory() { }
virtual bool Create(const char* statement, const RE* regex,
const char* file, int line, DeathTest** test) = 0;
};
// A concrete DeathTestFactory implementation for normal use.
class DefaultDeathTestFactory : public DeathTestFactory {
public:
virtual bool Create(const char* statement, const RE* regex,
const char* file, int line, DeathTest** test);
};
// 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);
// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
// ASSERT_EXIT*, and EXPECT_EXIT*.
#define GTEST_DEATH_TEST(statement, predicate, regex, fail) \
GTEST_AMBIGUOUS_ELSE_BLOCKER \
if (true) { \
const ::testing::internal::RE& gtest_regex = (regex); \
::testing::internal::DeathTest* gtest_dt; \
if (!::testing::internal::DeathTest::Create(#statement, &gtest_regex, \
__FILE__, __LINE__, &gtest_dt)) { \
goto GTEST_CONCAT_TOKEN(gtest_label_, __LINE__); \
} \
if (gtest_dt != NULL) { \
::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \
gtest_dt_ptr(gtest_dt); \
switch (gtest_dt->AssumeRole()) { \
case ::testing::internal::DeathTest::OVERSEE_TEST: \
if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
goto GTEST_CONCAT_TOKEN(gtest_label_, __LINE__); \
} \
break; \
case ::testing::internal::DeathTest::EXECUTE_TEST: { \
::testing::internal::DeathTest::ReturnSentinel \
gtest_sentinel(gtest_dt); \
{ statement; } \
gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
break; \
} \
} \
} \
} else \
GTEST_CONCAT_TOKEN(gtest_label_, __LINE__): \
fail(::testing::internal::DeathTest::LastMessage())
// The symbol "fail" here expands to something into which a message
// can be streamed.
// A struct representing the parsed contents of the
// --gtest_internal_run_death_test flag, as it existed when
// RUN_ALL_TESTS was called.
struct InternalRunDeathTestFlag {
String file;
int line;
int index;
int status_fd;
};
// 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();
#endif // GTEST_HAS_DEATH_TEST
} // namespace internal
} // namespace testing
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_

View File

@ -0,0 +1,168 @@
// 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.
//
// Author: keith.ray@gmail.com (Keith Ray)
//
// Google Test filepath utilities
//
// This header file declares classes and functions used internally by
// Google Test. They are subject to change without notice.
//
// This file is #included in testing/base/internal/gtest-internal.h
// Do not include this header file separately!
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
#if defined(__APPLE__) && !defined(GTEST_NOT_MAC_FRAMEWORK_MODE)
// When using Google Test on the Mac as a framework, all the includes will be
// in the framework headers folder along with gtest.h.
// Define GTEST_NOT_MAC_FRAMEWORK_MODE if you are building Google Test on
// the Mac and are not using it as a framework.
// More info on frameworks available here:
// http://developer.apple.com/documentation/MacOSX/Conceptual/BPFrameworks/
// Concepts/WhatAreFrameworks.html.
#include "gtest-string.h" // NOLINT
#else
#include <gtest/internal/gtest-string.h>
#endif // defined(__APPLE__) && !defined(GTEST_NOT_MAC_FRAMEWORK_MODE)
namespace testing {
namespace internal {
// FilePath - a class for file and directory pathname manipulation which
// handles platform-specific conventions (like the pathname separator).
// Used for helper functions for naming files in a directory for xml output.
// Except for Set methods, all methods are const or static, which provides an
// "immutable value object" -- useful for peace of mind.
// A FilePath with a value ending in a path separator ("like/this/") represents
// a directory, otherwise it is assumed to represent a file. In either case,
// it may or may not represent an actual file or directory in the file system.
// Names are NOT checked for syntax correctness -- no checking for illegal
// characters, malformed paths, etc.
class FilePath {
public:
FilePath() : pathname_("") { }
FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { }
explicit FilePath(const char* pathname) : pathname_(pathname) { }
explicit FilePath(const String& pathname) : pathname_(pathname) { }
void Set(const FilePath& rhs) {
pathname_ = rhs.pathname_;
}
String ToString() const { return pathname_; }
const char* c_str() const { return pathname_.c_str(); }
// Given directory = "dir", base_name = "test", number = 0,
// extension = "xml", returns "dir/test.xml". If number is greater
// than zero (e.g., 12), returns "dir/test_12.xml".
// On Windows platform, uses \ as the separator rather than /.
static FilePath MakeFileName(const FilePath& directory,
const FilePath& base_name,
int number,
const char* extension);
// Returns a pathname for a file that does not currently exist. The pathname
// will be directory/base_name.extension or
// directory/base_name_<number>.extension if directory/base_name.extension
// already exists. The number will be incremented until a pathname is found
// that does not already exist.
// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
// There could be a race condition if two or more processes are calling this
// function at the same time -- they could both pick the same filename.
static FilePath GenerateUniqueFileName(const FilePath& directory,
const FilePath& base_name,
const char* extension);
// If input name has a trailing separator character, removes it and returns
// the name, otherwise return the name string unmodified.
// On Windows platform, uses \ as the separator, other platforms use /.
FilePath RemoveTrailingPathSeparator() const;
// Returns a copy of the FilePath with the directory part removed.
// Example: FilePath("path/to/file").RemoveDirectoryName() returns
// FilePath("file"). If there is no directory part ("just_a_file"), it returns
// the FilePath unmodified. If there is no file part ("just_a_dir/") it
// returns an empty FilePath ("").
// On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath RemoveDirectoryName() const;
// RemoveFileName returns the directory path with the filename removed.
// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
// On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath RemoveFileName() const;
// Returns a copy of the FilePath with the case-insensitive extension removed.
// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
// FilePath("dir/file"). If a case-insensitive extension is not
// found, returns a copy of the original FilePath.
FilePath RemoveExtension(const char* extension) const;
// Creates directories so that path exists. Returns true if successful or if
// the directories already exist; returns false if unable to create
// directories for any reason. Will also return false if the FilePath does
// not represent a directory (that is, it doesn't end with a path separator).
bool CreateDirectoriesRecursively() const;
// Create the directory so that path exists. Returns true if successful or
// if the directory already exists; returns false if unable to create the
// directory for any reason, including if the parent directory does not
// exist. Not named "CreateDirectory" because that's a macro on Windows.
bool CreateFolder() const;
// Returns true if FilePath describes something in the file-system,
// either a file, directory, or whatever, and that something exists.
bool FileOrDirectoryExists() const;
// Returns true if pathname describes a directory in the file-system
// that exists.
bool DirectoryExists() const;
// Returns true if FilePath ends with a path separator, which indicates that
// it is intended to represent a directory. Returns false otherwise.
// This does NOT check that a directory (or file) actually exists.
bool IsDirectory() const;
private:
String pathname_;
// Don't implement operator= because it is banned by the style guide.
FilePath& operator=(const FilePath& rhs);
}; // class FilePath
} // namespace internal
} // namespace testing
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_

View File

@ -0,0 +1,569 @@
// 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.
//
// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
//
// The Google C++ Testing Framework (Google Test)
//
// This header file declares functions and macros used internally by
// Google Test. They are subject to change without notice.
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
#if defined(__APPLE__) && !defined(GTEST_NOT_MAC_FRAMEWORK_MODE)
// When using Google Test on the Mac as a framework, all the includes will be
// in the framework headers folder along with gtest.h.
// Define GTEST_NOT_MAC_FRAMEWORK_MODE if you are building Google Test on
// the Mac and are not using it as a framework.
// More info on frameworks available here:
// http://developer.apple.com/documentation/MacOSX/Conceptual/BPFrameworks/
// Concepts/WhatAreFrameworks.html.
#include "gtest-port.h" // NOLINT
#else
#include <gtest/internal/gtest-port.h>
#endif // defined(__APPLE__) && !defined(GTEST_NOT_MAC_FRAMEWORK_MODE)
#ifdef GTEST_OS_LINUX
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif // GTEST_OS_LINUX
#include <iomanip> // NOLINT
#include <limits> // NOLINT
#if defined(__APPLE__) && !defined(GTEST_NOT_MAC_FRAMEWORK_MODE)
// When using Google Test on the Mac as a framework, all the includes will be
// in the framework headers folder along with gtest.h.
// Define GTEST_NOT_MAC_FRAMEWORK_MODE if you are building Google Test on
// the Mac and are not using it as a framework.
// More info on frameworks available here:
// http://developer.apple.com/documentation/MacOSX/Conceptual/BPFrameworks/
// Concepts/WhatAreFrameworks.html.
#include "gtest-string.h" // NOLINT
#include "gtest-filepath.h" // NOLINT
#else
#include <gtest/internal/gtest-string.h>
#include <gtest/internal/gtest-filepath.h>
#endif // defined(__APPLE__) && !defined(GTEST_NOT_MAC_FRAMEWORK_MODE)
// Due to C++ preprocessor weirdness, we need double indirection to
// concatenate two tokens when one of them is __LINE__. Writing
//
// foo ## __LINE__
//
// will result in the token foo__LINE__, instead of foo followed by
// the current line number. For more details, see
// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
#define GTEST_CONCAT_TOKEN(foo, bar) GTEST_CONCAT_TOKEN_IMPL(foo, bar)
#define GTEST_CONCAT_TOKEN_IMPL(foo, bar) foo ## bar
// Google Test defines the testing::Message class to allow construction of
// test messages via the << operator. The idea is that anything
// streamable to std::ostream can be streamed to a testing::Message.
// This allows a user to use his own types in Google Test assertions by
// overloading the << operator.
//
// util/gtl/stl_logging-inl.h overloads << for STL containers. These
// overloads cannot be defined in the std namespace, as that will be
// undefined behavior. Therefore, they are defined in the global
// namespace instead.
//
// C++'s symbol lookup rule (i.e. Koenig lookup) says that these
// overloads are visible in either the std namespace or the global
// namespace, but not other namespaces, including the testing
// namespace which Google Test's Message class is in.
//
// To allow STL containers (and other types that has a << operator
// defined in the global namespace) to be used in Google Test assertions,
// testing::Message must access the custom << operator from the global
// namespace. Hence this helper function.
//
// Note: Jeffrey Yasskin suggested an alternative fix by "using
// ::operator<<;" in the definition of Message's operator<<. That fix
// doesn't require a helper function, but unfortunately doesn't
// compile with MSVC.
template <typename T>
inline void GTestStreamToHelper(std::ostream* os, const T& val) {
*os << val;
}
namespace testing {
// Forward declaration of classes.
class Message; // Represents a failure message.
class TestCase; // A collection of related tests.
class TestPartResult; // Result of a test part.
class TestInfo; // Information about a test.
class UnitTest; // A collection of test cases.
class UnitTestEventListenerInterface; // Listens to Google Test events.
class AssertionResult; // Result of an assertion.
namespace internal {
struct TraceInfo; // Information about a trace point.
class ScopedTrace; // Implements scoped trace.
class TestInfoImpl; // Opaque implementation of TestInfo
class TestResult; // Result of a single Test.
class UnitTestImpl; // Opaque implementation of UnitTest
template <typename E> class List; // A generic list.
template <typename E> class ListNode; // A node in a generic list.
// A secret type that Google Test users don't know about. It has no
// definition on purpose. Therefore it's impossible to create a
// Secret object, which is what we want.
class Secret;
// Two overloaded helpers for checking at compile time whether an
// expression is a null pointer literal (i.e. NULL or any 0-valued
// compile-time integral constant). Their return values have
// different sizes, so we can use sizeof() to test which version is
// picked by the compiler. These helpers have no implementations, as
// we only need their signatures.
//
// Given IsNullLiteralHelper(x), the compiler will pick the first
// version if x can be implicitly converted to Secret*, and pick the
// second version otherwise. Since Secret is a secret and incomplete
// type, the only expression a user can write that has type Secret* is
// a null pointer literal. Therefore, we know that x is a null
// pointer literal if and only if the first version is picked by the
// compiler.
char IsNullLiteralHelper(Secret* p);
char (&IsNullLiteralHelper(...))[2]; // NOLINT
// A compile-time bool constant that is true if and only if x is a
// null pointer literal (i.e. NULL or any 0-valued compile-time
// integral constant).
#ifdef __SYMBIAN32__ // Symbian
// Passing non-POD classes through ellipsis (...) crashes the ARM compiler.
// The Nokia Symbian compiler tries to instantiate a copy constructor for
// objects passed through ellipsis (...), failing for uncopyable objects.
// Hence we define this to false (and lose support for NULL detection).
#define GTEST_IS_NULL_LITERAL(x) false
#else // ! __SYMBIAN32__
#define GTEST_IS_NULL_LITERAL(x) \
(sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1)
#endif // __SYMBIAN32__
// Appends the user-supplied message to the Google-Test-generated message.
String AppendUserMessage(const String& gtest_msg,
const Message& user_msg);
// A helper class for creating scoped traces in user programs.
class ScopedTrace {
public:
// The c'tor pushes the given source file location and message onto
// a trace stack maintained by Google Test.
ScopedTrace(const char* file, int line, const Message& message);
// The d'tor pops the info pushed by the c'tor.
//
// Note that the d'tor is not virtual in order to be efficient.
// Don't inherit from ScopedTrace!
~ScopedTrace();
private:
GTEST_DISALLOW_COPY_AND_ASSIGN(ScopedTrace);
} GTEST_ATTRIBUTE_UNUSED; // A ScopedTrace object does its job in its
// c'tor and d'tor. Therefore it doesn't
// need to be used otherwise.
// Converts a streamable value to a String. A NULL pointer is
// converted to "(null)". When the input value is a ::string,
// ::std::string, ::wstring, or ::std::wstring object, each NUL
// character in it is replaced with "\\0".
// Declared here but defined in gtest.h, so that it has access
// to the definition of the Message class, required by the ARM
// compiler.
template <typename T>
String StreamableToString(const T& streamable);
// Formats a value to be used in a failure message.
#ifdef __SYMBIAN32__
// These are needed as the Nokia Symbian Compiler cannot decide between
// const T& and const T* in a function template. The Nokia compiler _can_
// decide between class template specializations for T and T*, so a
// tr1::type_traits-like is_pointer works, and we can overload on that.
// This overload makes sure that all pointers (including
// those to char or wchar_t) are printed as raw pointers.
template <typename T>
inline String FormatValueForFailureMessage(internal::true_type dummy,
T* pointer) {
return StreamableToString(static_cast<const void*>(pointer));
}
template <typename T>
inline String FormatValueForFailureMessage(internal::false_type dummy,
const T& value) {
return StreamableToString(value);
}
template <typename T>
inline String FormatForFailureMessage(const T& value) {
return FormatValueForFailureMessage(
typename internal::is_pointer<T>::type(), value);
}
#else
template <typename T>
inline String FormatForFailureMessage(const T& value) {
return StreamableToString(value);
}
// This overload makes sure that all pointers (including
// those to char or wchar_t) are printed as raw pointers.
template <typename T>
inline String FormatForFailureMessage(T* pointer) {
return StreamableToString(static_cast<const void*>(pointer));
}
#endif // __SYMBIAN32__
// These overloaded versions handle narrow and wide characters.
String FormatForFailureMessage(char ch);
String FormatForFailureMessage(wchar_t wchar);
// When this operand is a const char* or char*, and the other operand
// is a ::std::string or ::string, we print this operand as a C string
// rather than a pointer. We do the same for wide strings.
// This internal macro is used to avoid duplicated code.
#define GTEST_FORMAT_IMPL(operand2_type, operand1_printer)\
inline String FormatForComparisonFailureMessage(\
operand2_type::value_type* str, const operand2_type& operand2) {\
return operand1_printer(str);\
}\
inline String FormatForComparisonFailureMessage(\
const operand2_type::value_type* str, const operand2_type& operand2) {\
return operand1_printer(str);\
}
#if GTEST_HAS_STD_STRING
GTEST_FORMAT_IMPL(::std::string, String::ShowCStringQuoted)
#endif // GTEST_HAS_STD_STRING
#if GTEST_HAS_STD_WSTRING
GTEST_FORMAT_IMPL(::std::wstring, String::ShowWideCStringQuoted)
#endif // GTEST_HAS_STD_WSTRING
#if GTEST_HAS_GLOBAL_STRING
GTEST_FORMAT_IMPL(::string, String::ShowCStringQuoted)
#endif // GTEST_HAS_GLOBAL_STRING
#if GTEST_HAS_GLOBAL_WSTRING
GTEST_FORMAT_IMPL(::wstring, String::ShowWideCStringQuoted)
#endif // GTEST_HAS_GLOBAL_WSTRING
#undef GTEST_FORMAT_IMPL
// Constructs and returns the message for an equality assertion
// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
//
// The first four parameters are the expressions used in the assertion
// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
// where foo is 5 and bar is 6, we have:
//
// expected_expression: "foo"
// actual_expression: "bar"
// expected_value: "5"
// actual_value: "6"
//
// The ignoring_case parameter is true iff the assertion is a
// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
// be inserted into the message.
AssertionResult EqFailure(const char* expected_expression,
const char* actual_expression,
const String& expected_value,
const String& actual_value,
bool ignoring_case);
// This template class represents an IEEE floating-point number
// (either single-precision or double-precision, depending on the
// template parameters).
//
// The purpose of this class is to do more sophisticated number
// comparison. (Due to round-off error, etc, it's very unlikely that
// two floating-points will be equal exactly. Hence a naive
// comparison by the == operation often doesn't work.)
//
// Format of IEEE floating-point:
//
// The most-significant bit being the leftmost, an IEEE
// floating-point looks like
//
// sign_bit exponent_bits fraction_bits
//
// Here, sign_bit is a single bit that designates the sign of the
// number.
//
// For float, there are 8 exponent bits and 23 fraction bits.
//
// For double, there are 11 exponent bits and 52 fraction bits.
//
// More details can be found at
// http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
//
// Template parameter:
//
// RawType: the raw floating-point type (either float or double)
template <typename RawType>
class FloatingPoint {
public:
// Defines the unsigned integer type that has the same size as the
// floating point number.
typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;
// Constants.
// # of bits in a number.
static const size_t kBitCount = 8*sizeof(RawType);
// # of fraction bits in a number.
static const size_t kFractionBitCount =
std::numeric_limits<RawType>::digits - 1;
// # of exponent bits in a number.
static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
// The mask for the sign bit.
static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
// The mask for the fraction bits.
static const Bits kFractionBitMask =
~static_cast<Bits>(0) >> (kExponentBitCount + 1);
// The mask for the exponent bits.
static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
// How many ULP's (Units in the Last Place) we want to tolerate when
// comparing two numbers. The larger the value, the more error we
// allow. A 0 value means that two numbers must be exactly the same
// to be considered equal.
//
// The maximum error of a single floating-point operation is 0.5
// units in the last place. On Intel CPU's, all floating-point
// calculations are done with 80-bit precision, while double has 64
// bits. Therefore, 4 should be enough for ordinary use.
//
// See the following article for more details on ULP:
// http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm.
static const size_t kMaxUlps = 4;
// Constructs a FloatingPoint from a raw floating-point number.
//
// On an Intel CPU, passing a non-normalized NAN (Not a Number)
// around may change its bits, although the new value is guaranteed
// to be also a NAN. Therefore, don't expect this constructor to
// preserve the bits in x when x is a NAN.
explicit FloatingPoint(const RawType& x) : value_(x) {}
// Static methods
// Reinterprets a bit pattern as a floating-point number.
//
// This function is needed to test the AlmostEquals() method.
static RawType ReinterpretBits(const Bits bits) {
FloatingPoint fp(0);
fp.bits_ = bits;
return fp.value_;
}
// Returns the floating-point number that represent positive infinity.
static RawType Infinity() {
return ReinterpretBits(kExponentBitMask);
}
// Non-static methods
// Returns the bits that represents this number.
const Bits &bits() const { return bits_; }
// Returns the exponent bits of this number.
Bits exponent_bits() const { return kExponentBitMask & bits_; }
// Returns the fraction bits of this number.
Bits fraction_bits() const { return kFractionBitMask & bits_; }
// Returns the sign bit of this number.
Bits sign_bit() const { return kSignBitMask & bits_; }
// Returns true iff this is NAN (not a number).
bool is_nan() const {
// It's a NAN if the exponent bits are all ones and the fraction
// bits are not entirely zeros.
return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
}
// Returns true iff this number is at most kMaxUlps ULP's away from
// rhs. In particular, this function:
//
// - returns false if either number is (or both are) NAN.
// - treats really large numbers as almost equal to infinity.
// - thinks +0.0 and -0.0 are 0 DLP's apart.
bool AlmostEquals(const FloatingPoint& rhs) const {
// The IEEE standard says that any comparison operation involving
// a NAN must return false.
if (is_nan() || rhs.is_nan()) return false;
return DistanceBetweenSignAndMagnitudeNumbers(bits_, rhs.bits_) <= kMaxUlps;
}
private:
// Converts an integer from the sign-and-magnitude representation to
// the biased representation. More precisely, let N be 2 to the
// power of (kBitCount - 1), an integer x is represented by the
// unsigned number x + N.
//
// For instance,
//
// -N + 1 (the most negative number representable using
// sign-and-magnitude) is represented by 1;
// 0 is represented by N; and
// N - 1 (the biggest number representable using
// sign-and-magnitude) is represented by 2N - 1.
//
// Read http://en.wikipedia.org/wiki/Signed_number_representations
// for more details on signed number representations.
static Bits SignAndMagnitudeToBiased(const Bits &sam) {
if (kSignBitMask & sam) {
// sam represents a negative number.
return ~sam + 1;
} else {
// sam represents a positive number.
return kSignBitMask | sam;
}
}
// Given two numbers in the sign-and-magnitude representation,
// returns the distance between them as an unsigned number.
static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
const Bits &sam2) {
const Bits biased1 = SignAndMagnitudeToBiased(sam1);
const Bits biased2 = SignAndMagnitudeToBiased(sam2);
return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
}
union {
RawType value_; // The raw floating-point number.
Bits bits_; // The bits that represent the number.
};
};
// Typedefs the instances of the FloatingPoint template class that we
// care to use.
typedef FloatingPoint<float> Float;
typedef FloatingPoint<double> Double;
// In order to catch the mistake of putting tests that use different
// test fixture classes in the same test case, we need to assign
// unique IDs to fixture classes and compare them. The TypeId type is
// used to hold such IDs. The user should treat TypeId as an opaque
// type: the only operation allowed on TypeId values is to compare
// them for equality using the == operator.
typedef void* TypeId;
// GetTypeId<T>() returns the ID of type T. Different values will be
// returned for different types. Calling the function twice with the
// same type argument is guaranteed to return the same ID.
template <typename T>
inline TypeId GetTypeId() {
static bool dummy = false;
// The compiler is required to create an instance of the static
// variable dummy for each T used to instantiate the template.
// Therefore, the address of dummy is guaranteed to be unique.
return &dummy;
}
#ifdef GTEST_OS_WINDOWS
// Predicate-formatters for implementing the HRESULT checking macros
// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
// We pass a long instead of HRESULT to avoid causing an
// include dependency for the HRESULT type.
AssertionResult IsHRESULTSuccess(const char* expr, long hr); // NOLINT
AssertionResult IsHRESULTFailure(const char* expr, long hr); // NOLINT
#endif // GTEST_OS_WINDOWS
} // namespace internal
} // namespace testing
#define GTEST_MESSAGE(message, result_type) \
::testing::internal::AssertHelper(result_type, __FILE__, __LINE__, message) \
= ::testing::Message()
#define GTEST_FATAL_FAILURE(message) \
return GTEST_MESSAGE(message, ::testing::TPRT_FATAL_FAILURE)
#define GTEST_NONFATAL_FAILURE(message) \
GTEST_MESSAGE(message, ::testing::TPRT_NONFATAL_FAILURE)
#define GTEST_SUCCESS(message) \
GTEST_MESSAGE(message, ::testing::TPRT_SUCCESS)
#define GTEST_TEST_BOOLEAN(boolexpr, booltext, actual, expected, fail) \
GTEST_AMBIGUOUS_ELSE_BLOCKER \
if (boolexpr) \
; \
else \
fail("Value of: " booltext "\n Actual: " #actual "\nExpected: " #expected)
// Helper macro for defining tests.
#define GTEST_TEST(test_case_name, test_name, parent_class)\
class test_case_name##_##test_name##_Test : public parent_class {\
public:\
test_case_name##_##test_name##_Test() {}\
static ::testing::Test* NewTest() {\
return new test_case_name##_##test_name##_Test;\
}\
private:\
virtual void TestBody();\
static ::testing::TestInfo* const test_info_;\
GTEST_DISALLOW_COPY_AND_ASSIGN(test_case_name##_##test_name##_Test);\
};\
\
::testing::TestInfo* const test_case_name##_##test_name##_Test::test_info_ =\
::testing::TestInfo::MakeAndRegisterInstance(\
#test_case_name, \
#test_name, \
::testing::internal::GetTypeId< parent_class >(), \
parent_class::SetUpTestCase, \
parent_class::TearDownTestCase, \
test_case_name##_##test_name##_Test::NewTest);\
void test_case_name##_##test_name##_Test::TestBody()
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_

View File

@ -0,0 +1,618 @@
// 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.
//
// Authors: wan@google.com (Zhanyong Wan)
//
// Low-level types and utilities for porting Google Test to various
// platforms. They are subject to change without notice. DO NOT USE
// THEM IN USER CODE.
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
// The user can define the following macros in the build script to
// control Google Test's behavior:
//
// GTEST_HAS_STD_STRING - Define it to 1/0 to indicate that
// std::string does/doesn't work (Google Test can
// be used where std::string is unavailable).
// Leave it undefined to let Google Test define it.
// GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string
// is/isn't available (some systems define
// ::string, which is different to std::string).
// Leave it undefined to let Google Test define it.
// GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that
// std::wstring does/doesn't work (Google Test can
// be used where std::wstring is unavailable).
// Leave it undefined to let Google Test define it.
// GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string
// is/isn't available (some systems define
// ::wstring, which is different to std::wstring).
// Leave it undefined to let Google Test define it.
// This header defines the following utilities:
//
// Macros indicating the name of the Google C++ Testing Framework project:
// GTEST_NAME - a string literal of the project name.
// GTEST_FLAG_PREFIX - a string literal of the prefix all Google
// Test flag names share.
// GTEST_FLAG_PREFIX_UPPER - a string literal of the prefix all Google
// Test flag names share, in upper case.
//
// Macros indicating the current platform:
// GTEST_OS_LINUX - defined iff compiled on Linux.
// GTEST_OS_MAC - defined iff compiled on Mac OS X.
// GTEST_OS_WINDOWS - defined iff compiled on Windows.
// Note that it is possible that none of the GTEST_OS_ macros are defined.
//
// Macros indicating available Google Test features:
// GTEST_HAS_DEATH_TEST - defined iff death tests are supported.
//
// Macros for basic C++ coding:
// GTEST_AMBIGUOUS_ELSE_BLOCKER - for disabling a gcc warning.
// GTEST_ATTRIBUTE_UNUSED - declares that a class' instances don't have to
// be used.
// GTEST_DISALLOW_COPY_AND_ASSIGN() - disables copy ctor and operator=.
// GTEST_MUST_USE_RESULT - declares that a function's result must be used.
//
// Synchronization:
// Mutex, MutexLock, ThreadLocal, GetThreadCount()
// - synchronization primitives.
//
// Template meta programming:
// is_pointer - as in TR1; needed on Symbian only.
//
// Smart pointers:
// scoped_ptr - as in TR2.
//
// Regular expressions:
// RE - a simple regular expression class using the POSIX
// Extended Regular Expression syntax. Not available on
// Windows.
//
// Logging:
// GTEST_LOG() - logs messages at the specified severity level.
// LogToStderr() - directs all log messages to stderr.
// FlushInfoLog() - flushes informational log messages.
//
// Stderr capturing:
// CaptureStderr() - starts capturing stderr.
// GetCapturedStderr() - stops capturing stderr and returns the captured
// string.
//
// Integer types:
// TypeWithSize - maps an integer to a int type.
// Int32, UInt32, Int64, UInt64, TimeInMillis
// - integers of known sizes.
// BiggestInt - the biggest signed integer type.
//
// Command-line utilities:
// GTEST_FLAG() - references a flag.
// GTEST_DECLARE_*() - declares a flag.
// GTEST_DEFINE_*() - defines a flag.
// GetArgvs() - returns the command line as a vector of strings.
//
// Environment variable utilities:
// GetEnv() - gets the value of an environment variable.
// BoolFromGTestEnv() - parses a bool environment variable.
// Int32FromGTestEnv() - parses an Int32 environment variable.
// StringFromGTestEnv() - parses a string environment variable.
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#define GTEST_NAME "Google Test"
#define GTEST_FLAG_PREFIX "gtest_"
#define GTEST_FLAG_PREFIX_UPPER "GTEST_"
// Determines the platform on which Google Test is compiled.
#ifdef _MSC_VER
// TODO(kenton@google.com): GTEST_OS_WINDOWS is currently used to mean
// both "The OS is Windows" and "The compiler is MSVC". These
// meanings really should be separated in order to better support
// Windows compilers other than MSVC.
#define GTEST_OS_WINDOWS
#elif defined __APPLE__
#define GTEST_OS_MAC
#elif defined __linux__
#define GTEST_OS_LINUX
#endif // _MSC_VER
// Determines whether ::std::string and ::string are available.
#ifndef GTEST_HAS_STD_STRING
// The user didn't tell us whether ::std::string is available, so we
// need to figure it out.
#ifdef GTEST_OS_WINDOWS
// Assumes that exceptions are enabled by default.
#ifndef _HAS_EXCEPTIONS
#define _HAS_EXCEPTIONS 1
#endif // _HAS_EXCEPTIONS
// GTEST_HAS_EXCEPTIONS is non-zero iff exceptions are enabled. It is
// always defined, while _HAS_EXCEPTIONS is defined only on Windows.
#define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
// On Windows, we can use ::std::string if the compiler version is VS
// 2005 or above, or if exceptions are enabled.
#define GTEST_HAS_STD_STRING ((_MSC_VER >= 1400) || GTEST_HAS_EXCEPTIONS)
#else // We are on Linux or Mac OS.
#define GTEST_HAS_EXCEPTIONS 0
#define GTEST_HAS_STD_STRING 1
#endif // GTEST_OS_WINDOWS
#endif // GTEST_HAS_STD_STRING
#ifndef GTEST_HAS_GLOBAL_STRING
// The user didn't tell us whether ::string is available, so we need
// to figure it out.
#define GTEST_HAS_GLOBAL_STRING 0
#endif // GTEST_HAS_GLOBAL_STRING
#ifndef GTEST_HAS_STD_WSTRING
// The user didn't tell us whether ::std::wstring is available, so we need
// to figure it out.
// TODO(wan@google.com): uses autoconf to detect whether ::std::wstring
// is available.
#ifdef GTEST_OS_CYGWIN
// At least some versions of cygwin doesn't support ::std::wstring.
#define GTEST_HAS_STD_WSTRING 0
#else
#define GTEST_HAS_STD_WSTRING GTEST_HAS_STD_STRING
#endif // GTEST_OS_CYGWIN
#endif // GTEST_HAS_STD_WSTRING
#ifndef GTEST_HAS_GLOBAL_WSTRING
// The user didn't tell us whether ::wstring is available, so we need
// to figure it out.
#define GTEST_HAS_GLOBAL_WSTRING GTEST_HAS_GLOBAL_STRING
#endif // GTEST_HAS_GLOBAL_WSTRING
#if GTEST_HAS_STD_STRING || GTEST_HAS_GLOBAL_STRING || \
GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
#include <string> // NOLINT
#endif // GTEST_HAS_STD_STRING || GTEST_HAS_GLOBAL_STRING ||
// GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
#if GTEST_HAS_STD_STRING
#include <sstream> // NOLINT
#else
#include <strstream> // NOLINT
#endif // GTEST_HAS_STD_STRING
// Determines whether to support death tests.
#if GTEST_HAS_STD_STRING && defined(GTEST_OS_LINUX)
#define GTEST_HAS_DEATH_TEST
// On some platforms, <regex.h> needs someone to define size_t, and
// won't compile if being #included first. Therefore it's important
// that we #include it after <sys/types.h>.
#include <regex.h>
#include <vector>
#include <fcntl.h>
#include <sys/mman.h>
#endif // GTEST_HAS_STD_STRING && defined(GTEST_OS_LINUX)
// Defines some utility macros.
// The GNU compiler emits a warning if nested "if" statements are followed by
// an "else" statement and braces are not used to explicitly disambiguate the
// "else" binding. This leads to problems with code like:
//
// if (gate)
// ASSERT_*(condition) << "Some message";
//
// The "switch (0) case 0:" idiom is used to suppress this.
#ifdef __INTEL_COMPILER
#define GTEST_AMBIGUOUS_ELSE_BLOCKER
#else
#define GTEST_AMBIGUOUS_ELSE_BLOCKER switch (0) case 0: // NOLINT
#endif
// Use this annotation at the end of a struct / class definition to
// prevent the compiler from optimizing away instances that are never
// used. This is useful when all interesting logic happens inside the
// c'tor and / or d'tor. Example:
//
// struct Foo {
// Foo() { ... }
// } GTEST_ATTRIBUTE_UNUSED;
#if defined(GTEST_OS_WINDOWS) || (defined(GTEST_OS_LINUX) && defined(SWIG))
#define GTEST_ATTRIBUTE_UNUSED
#else
#define GTEST_ATTRIBUTE_UNUSED __attribute__ ((unused))
#endif // GTEST_OS_WINDOWS || (GTEST_OS_LINUX && SWIG)
// A macro to disallow the evil copy constructor and operator= functions
// This should be used in the private: declarations for a class.
#define GTEST_DISALLOW_COPY_AND_ASSIGN(type)\
type(const type &);\
void operator=(const type &)
// Tell the compiler to warn about unused return values for functions declared
// with this macro. The macro should be used on function declarations
// following the argument list:
//
// Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT;
#if defined(__GNUC__) \
&& (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) \
&& !defined(COMPILER_ICC)
#define GTEST_MUST_USE_RESULT __attribute__ ((warn_unused_result))
#else
#define GTEST_MUST_USE_RESULT
#endif // (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 4)
namespace testing {
class Message;
namespace internal {
class String;
// std::strstream is deprecated. However, we have to use it on
// Windows as std::stringstream won't compile on Windows when
// exceptions are disabled. We use std::stringstream on other
// platforms to avoid compiler warnings there.
#if GTEST_HAS_STD_STRING
typedef ::std::stringstream StrStream;
#else
typedef ::std::strstream StrStream;
#endif // GTEST_HAS_STD_STRING
// Defines scoped_ptr.
// This implementation of scoped_ptr is PARTIAL - it only contains
// enough stuff to satisfy Google Test's need.
template <typename T>
class scoped_ptr {
public:
explicit scoped_ptr(T* p = NULL) : ptr_(p) {}
~scoped_ptr() { reset(); }
T& operator*() const { return *ptr_; }
T* operator->() const { return ptr_; }
T* get() const { return ptr_; }
T* release() {
T* const ptr = ptr_;
ptr_ = NULL;
return ptr;
}
void reset(T* p = NULL) {
if (p != ptr_) {
if (sizeof(T) > 0) { // Makes sure T is a complete type.
delete ptr_;
}
ptr_ = p;
}
}
private:
T* ptr_;
GTEST_DISALLOW_COPY_AND_ASSIGN(scoped_ptr);
};
#ifdef GTEST_HAS_DEATH_TEST
// Defines RE. Currently only needed for death tests.
// A simple C++ wrapper for <regex.h>. It uses the POSIX Enxtended
// Regular Expression syntax.
class RE {
public:
// Constructs an RE from a string.
#if GTEST_HAS_STD_STRING
RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT
#endif // GTEST_HAS_STD_STRING
#if GTEST_HAS_GLOBAL_STRING
RE(const ::string& regex) { Init(regex.c_str()); } // NOLINT
#endif // GTEST_HAS_GLOBAL_STRING
RE(const char* regex) { Init(regex); } // NOLINT
~RE();
// Returns the string representation of the regex.
const char* pattern() const { return pattern_; }
// Returns true iff str contains regular expression re.
// TODO(wan): make PartialMatch() work when str contains NUL
// characters.
#if GTEST_HAS_STD_STRING
static bool PartialMatch(const ::std::string& str, const RE& re) {
return PartialMatch(str.c_str(), re);
}
#endif // GTEST_HAS_STD_STRING
#if GTEST_HAS_GLOBAL_STRING
static bool PartialMatch(const ::string& str, const RE& re) {
return PartialMatch(str.c_str(), re);
}
#endif // GTEST_HAS_GLOBAL_STRING
static bool PartialMatch(const char* str, const RE& re);
private:
void Init(const char* regex);
// We use a const char* instead of a string, as Google Test may be used
// where string is not available. We also do not use Google Test's own
// String type here, in order to simplify dependencies between the
// files.
const char* pattern_;
regex_t regex_;
bool is_valid_;
};
#endif // GTEST_HAS_DEATH_TEST
// Defines logging utilities:
// GTEST_LOG() - logs messages at the specified severity level.
// LogToStderr() - directs all log messages to stderr.
// FlushInfoLog() - flushes informational log messages.
enum GTestLogSeverity {
GTEST_INFO,
GTEST_WARNING,
GTEST_ERROR,
GTEST_FATAL
};
void GTestLog(GTestLogSeverity severity, const char* file,
int line, const char* msg);
#define GTEST_LOG(severity, msg)\
::testing::internal::GTestLog(\
::testing::internal::GTEST_##severity, __FILE__, __LINE__, \
(::testing::Message() << (msg)).GetString().c_str())
inline void LogToStderr() {}
inline void FlushInfoLog() { fflush(NULL); }
// Defines the stderr capturer:
// CaptureStderr - starts capturing stderr.
// GetCapturedStderr - stops capturing stderr and returns the captured string.
#ifdef GTEST_HAS_DEATH_TEST
// A copy of all command line arguments. Set by InitGoogleTest().
extern ::std::vector<String> g_argvs;
void CaptureStderr();
// GTEST_HAS_DEATH_TEST implies we have ::std::string.
::std::string GetCapturedStderr();
const ::std::vector<String>& GetArgvs();
#endif // GTEST_HAS_DEATH_TEST
// Defines synchronization primitives.
// A dummy implementation of synchronization primitives (mutex, lock,
// and thread-local variable). Necessary for compiling Google Test where
// mutex is not supported - using Google Test in multiple threads is not
// supported on such platforms.
class Mutex {
public:
Mutex() {}
explicit Mutex(int unused) {}
void AssertHeld() const {}
enum { NO_CONSTRUCTOR_NEEDED_FOR_STATIC_MUTEX = 0 };
};
// We cannot call it MutexLock directly as the ctor declaration would
// conflict with a macro named MutexLock, which is defined on some
// platforms. Hence the typedef trick below.
class GTestMutexLock {
public:
explicit GTestMutexLock(Mutex*) {} // NOLINT
};
typedef GTestMutexLock MutexLock;
template <typename T>
class ThreadLocal {
public:
T* pointer() { return &value_; }
const T* pointer() const { return &value_; }
const T& get() const { return value_; }
void set(const T& value) { value_ = value; }
private:
T value_;
};
// There's no portable way to detect the number of threads, so we just
// return 0 to indicate that we cannot detect it.
inline size_t GetThreadCount() { return 0; }
// Defines tr1::is_pointer (only needed for Symbian).
#ifdef __SYMBIAN32__
// Symbian does not have tr1::type_traits, so we define our own is_pointer
// These are needed as the Nokia Symbian Compiler cannot decide between
// const T& and const T* in a function template.
template <bool bool_value>
struct bool_constant {
typedef bool_constant<bool_value> type;
static const bool value = bool_value;
};
template <bool bool_value> const bool bool_constant<bool_value>::value;
typedef bool_constant<false> false_type;
typedef bool_constant<true> true_type;
template <typename T>
struct is_pointer : public false_type {};
template <typename T>
struct is_pointer<T*> : public true_type {};
#endif // __SYMBIAN32__
// Defines BiggestInt as the biggest signed integer type the compiler
// supports.
#ifdef GTEST_OS_WINDOWS
typedef __int64 BiggestInt;
#else
typedef long long BiggestInt; // NOLINT
#endif // GTEST_OS_WINDOWS
// The maximum number a BiggestInt can represent. This definition
// works no matter BiggestInt is represented in one's complement or
// two's complement.
//
// We cannot rely on numeric_limits in STL, as __int64 and long long
// are not part of standard C++ and numeric_limits doesn't need to be
// defined for them.
const BiggestInt kMaxBiggestInt =
~(static_cast<BiggestInt>(1) << (8*sizeof(BiggestInt) - 1));
// This template class serves as a compile-time function from size to
// type. It maps a size in bytes to a primitive type with that
// size. e.g.
//
// TypeWithSize<4>::UInt
//
// is typedef-ed to be unsigned int (unsigned integer made up of 4
// bytes).
//
// Such functionality should belong to STL, but I cannot find it
// there.
//
// Google Test uses this class in the implementation of floating-point
// comparison.
//
// For now it only handles UInt (unsigned int) as that's all Google Test
// needs. Other types can be easily added in the future if need
// arises.
template <size_t size>
class TypeWithSize {
public:
// This prevents the user from using TypeWithSize<N> with incorrect
// values of N.
typedef void UInt;
};
// The specialization for size 4.
template <>
class TypeWithSize<4> {
public:
// unsigned int has size 4 in both gcc and MSVC.
//
// As base/basictypes.h doesn't compile on Windows, we cannot use
// uint32, uint64, and etc here.
typedef int Int;
typedef unsigned int UInt;
};
// The specialization for size 8.
template <>
class TypeWithSize<8> {
public:
#ifdef GTEST_OS_WINDOWS
typedef __int64 Int;
typedef unsigned __int64 UInt;
#else
typedef long long Int; // NOLINT
typedef unsigned long long UInt; // NOLINT
#endif // GTEST_OS_WINDOWS
};
// Integer types of known sizes.
typedef TypeWithSize<4>::Int Int32;
typedef TypeWithSize<4>::UInt UInt32;
typedef TypeWithSize<8>::Int Int64;
typedef TypeWithSize<8>::UInt UInt64;
typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds.
// Utilities for command line flags and environment variables.
// A wrapper for getenv() that works on Linux, Windows, and Mac OS.
inline const char* GetEnv(const char* name) {
#ifdef _WIN32_WCE // We are on Windows CE.
// CE has no environment variables.
return NULL;
#elif defined(GTEST_OS_WINDOWS) // We are on Windows proper.
// MSVC 8 deprecates getenv(), so we want to suppress warning 4996
// (deprecated function) there.
#pragma warning(push) // Saves the current warning state.
#pragma warning(disable:4996) // Temporarily disables warning 4996.
return getenv(name);
#pragma warning(pop) // Restores the warning state.
#else // We are on Linux or Mac OS.
return getenv(name);
#endif
}
// Macro for referencing flags.
#define GTEST_FLAG(name) FLAGS_gtest_##name
// Macros for declaring flags.
#define GTEST_DECLARE_bool(name) extern bool GTEST_FLAG(name)
#define GTEST_DECLARE_int32(name) \
extern ::testing::internal::Int32 GTEST_FLAG(name)
#define GTEST_DECLARE_string(name) \
extern ::testing::internal::String GTEST_FLAG(name)
// Macros for defining flags.
#define GTEST_DEFINE_bool(name, default_val, doc) \
bool GTEST_FLAG(name) = (default_val)
#define GTEST_DEFINE_int32(name, default_val, doc) \
::testing::internal::Int32 GTEST_FLAG(name) = (default_val)
#define GTEST_DEFINE_string(name, default_val, doc) \
::testing::internal::String GTEST_FLAG(name) = (default_val)
// Parses 'str' for a 32-bit signed integer. If successful, writes the result
// to *value and returns true; otherwise leaves *value unchanged and returns
// false.
// TODO(chandlerc): Find a better way to refactor flag and environment parsing
// out of both gtest-port.cc and gtest.cc to avoid exporting this utility
// function.
bool ParseInt32(const Message& src_text, const char* str, Int32* value);
// Parses a bool/Int32/string from the environment variable
// corresponding to the given Google Test flag.
bool BoolFromGTestEnv(const char* flag, bool default_val);
Int32 Int32FromGTestEnv(const char* flag, Int32 default_val);
const char* StringFromGTestEnv(const char* flag, const char* default_val);
} // namespace internal
} // namespace testing
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_

View File

@ -0,0 +1,280 @@
// 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.
//
// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
//
// The Google C++ Testing Framework (Google Test)
//
// This header file declares the String class and functions used internally by
// Google Test. They are subject to change without notice. They should not used
// by code external to Google Test.
//
// This header file is #included by testing/base/internal/gtest-internal.h.
// It should not be #included by other files.
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
#include <string.h>
#if defined(__APPLE__) && !defined(GTEST_NOT_MAC_FRAMEWORK_MODE)
// When using Google Test on the Mac as a framework, all the includes will be
// in the framework headers folder along with gtest.h.
// Define GTEST_NOT_MAC_FRAMEWORK_MODE if you are building Google Test on
// the Mac and are not using it as a framework.
// More info on frameworks available here:
// http://developer.apple.com/documentation/MacOSX/Conceptual/BPFrameworks/
// Concepts/WhatAreFrameworks.html.
#include "gtest-port.h" // NOLINT
#else
#include <gtest/internal/gtest-port.h>
#endif // defined(__APPLE__) && !defined(GTEST_NOT_MAC_FRAMEWORK_MODE)
namespace testing {
namespace internal {
// String - a UTF-8 string class.
//
// We cannot use std::string as Microsoft's STL implementation in
// Visual C++ 7.1 has problems when exception is disabled. There is a
// hack to work around this, but we've seen cases where the hack fails
// to work.
//
// Also, String is different from std::string in that it can represent
// both NULL and the empty string, while std::string cannot represent
// NULL.
//
// NULL and the empty string are considered different. NULL is less
// than anything (including the empty string) except itself.
//
// This class only provides minimum functionality necessary for
// implementing Google Test. We do not intend to implement a full-fledged
// string class here.
//
// Since the purpose of this class is to provide a substitute for
// std::string on platforms where it cannot be used, we define a copy
// constructor and assignment operators such that we don't need
// conditional compilation in a lot of places.
//
// In order to make the representation efficient, the d'tor of String
// is not virtual. Therefore DO NOT INHERIT FROM String.
class String {
public:
// Static utility methods
// Returns the input if it's not NULL, otherwise returns "(null)".
// This function serves two purposes:
//
// 1. ShowCString(NULL) has type 'const char *', instead of the
// type of NULL (which is int).
//
// 2. In MSVC, streaming a null char pointer to StrStream generates
// an access violation, so we need to convert NULL to "(null)"
// before streaming it.
static inline const char* ShowCString(const char* c_str) {
return c_str ? c_str : "(null)";
}
// Returns the input enclosed in double quotes if it's not NULL;
// otherwise returns "(null)". For example, "\"Hello\"" is returned
// for input "Hello".
//
// This is useful for printing a C string in the syntax of a literal.
//
// Known issue: escape sequences are not handled yet.
static String ShowCStringQuoted(const char* c_str);
// Clones a 0-terminated C string, allocating memory using new. The
// caller is responsible for deleting the return value using
// delete[]. Returns the cloned string, or NULL if the input is
// NULL.
//
// This is different from strdup() in string.h, which allocates
// memory using malloc().
static const char* CloneCString(const char* c_str);
// Compares two C strings. Returns true iff they have the same content.
//
// Unlike strcmp(), this function can handle NULL argument(s). A
// NULL C string is considered different to any non-NULL C string,
// including the empty string.
static bool CStringEquals(const char* lhs, const char* rhs);
// Converts a wide C string to a String using the UTF-8 encoding.
// NULL will be converted to "(null)". If an error occurred during
// the conversion, "(failed to convert from wide string)" is
// returned.
static String ShowWideCString(const wchar_t* wide_c_str);
// Similar to ShowWideCString(), except that this function encloses
// the converted string in double quotes.
static String ShowWideCStringQuoted(const wchar_t* wide_c_str);
// Compares two wide C strings. Returns true iff they have the same
// content.
//
// Unlike wcscmp(), this function can handle NULL argument(s). A
// NULL C string is considered different to any non-NULL C string,
// including the empty string.
static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);
// Compares two C strings, ignoring case. Returns true iff they
// have the same content.
//
// Unlike strcasecmp(), this function can handle NULL argument(s).
// A NULL C string is considered different to any non-NULL C string,
// including the empty string.
static bool CaseInsensitiveCStringEquals(const char* lhs,
const char* rhs);
// Formats a list of arguments to a String, using the same format
// spec string as for printf.
//
// We do not use the StringPrintf class as it is not universally
// available.
//
// The result is limited to 4096 characters (including the tailing
// 0). If 4096 characters are not enough to format the input,
// "<buffer exceeded>" is returned.
static String Format(const char* format, ...);
// C'tors
// The default c'tor constructs a NULL string.
String() : c_str_(NULL) {}
// Constructs a String by cloning a 0-terminated C string.
String(const char* c_str) : c_str_(NULL) { // NOLINT
*this = c_str;
}
// Constructs a String by copying a given number of chars from a
// buffer. E.g. String("hello", 3) will create the string "hel".
String(const char* buffer, size_t len);
// The copy c'tor creates a new copy of the string. The two
// String objects do not share content.
String(const String& str) : c_str_(NULL) {
*this = str;
}
// D'tor. String is intended to be a final class, so the d'tor
// doesn't need to be virtual.
~String() { delete[] c_str_; }
// Returns true iff this is an empty string (i.e. "").
bool empty() const {
return (c_str_ != NULL) && (*c_str_ == '\0');
}
// Compares this with another String.
// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
// if this is greater than rhs.
int Compare(const String& rhs) const;
// Returns true iff this String equals the given C string. A NULL
// string and a non-NULL string are considered not equal.
bool operator==(const char* c_str) const {
return CStringEquals(c_str_, c_str);
}
// Returns true iff this String doesn't equal the given C string. A NULL
// string and a non-NULL string are considered not equal.
bool operator!=(const char* c_str) const {
return !CStringEquals(c_str_, c_str);
}
// Returns true iff this String ends with the given suffix. *Any*
// String is considered to end with a NULL or empty suffix.
bool EndsWith(const char* suffix) const;
// Returns true iff this String ends with the given suffix, not considering
// case. Any String is considered to end with a NULL or empty suffix.
bool EndsWithCaseInsensitive(const char* suffix) const;
// Returns the length of the encapsulated string, or -1 if the
// string is NULL.
int GetLength() const {
return c_str_ ? static_cast<int>(strlen(c_str_)) : -1;
}
// Gets the 0-terminated C string this String object represents.
// The String object still owns the string. Therefore the caller
// should NOT delete the return value.
const char* c_str() const { return c_str_; }
// Sets the 0-terminated C string this String object represents.
// The old string in this object is deleted, and this object will
// own a clone of the input string. This function copies only up to
// length bytes (plus a terminating null byte), or until the first
// null byte, whichever comes first.
//
// This function works even when the c_str parameter has the same
// value as that of the c_str_ field.
void Set(const char* c_str, size_t length);
// Assigns a C string to this object. Self-assignment works.
const String& operator=(const char* c_str);
// Assigns a String object to this object. Self-assignment works.
const String& operator=(const String &rhs) {
*this = rhs.c_str_;
return *this;
}
private:
const char* c_str_;
};
// Streams a String to an ostream.
inline ::std::ostream& operator <<(::std::ostream& os, const String& str) {
// We call String::ShowCString() to convert NULL to "(null)".
// Otherwise we'll get an access violation on Windows.
return os << String::ShowCString(str.c_str());
}
// Gets the content of the StrStream's buffer as a String. Each '\0'
// character in the buffer is replaced with "\\0".
String StrStreamToString(StrStream* stream);
// Converts a streamable value to a String. A NULL pointer is
// converted to "(null)". When the input value is a ::string,
// ::std::string, ::wstring, or ::std::wstring object, each NUL
// character in it is replaced with "\\0".
// Declared here but defined in gtest.h, so that it has access
// to the definition of the Message class, required by the ARM
// compiler.
template <typename T>
String StreamableToString(const T& streamable);
} // namespace internal
} // namespace testing
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_

61
m4/gtest.m4 Normal file
View File

@ -0,0 +1,61 @@
dnl GTEST_LIB_CHECK([minimum version [,
dnl action if found [,action if not found]]])
dnl
dnl Check for the presence of the Google Test library, optionally at a minimum
dnl version, and indicate a viable version with the HAVE_GTEST flag. It defines
dnl standard variables for substitution including GTEST_CPPFLAGS,
dnl GTEST_CXXFLAGS, GTEST_LDFLAGS, and GTEST_LIBS. It also defines
dnl GTEST_VERSION as the version of Google Test found. Finally, it provides
dnl optional custom action slots in the event GTEST is found or not.
AC_DEFUN([GTEST_LIB_CHECK],
[
dnl Provide a flag to enable or disable Google Test usage.
AC_ARG_ENABLE([gtest],
[AS_HELP_STRING([--enable-gtest],
[Enable tests using the Google C++ Testing Framework.]
[(Default is enabled.)])],
[],
[enable_gtest=check])
AC_ARG_VAR([GTEST_CONFIG],
[The exact path of Google Test's 'gtest-config' script.])
AC_ARG_VAR([GTEST_CPPFLAGS],
[C-like preprocessor flags for Google Test.])
AC_ARG_VAR([GTEST_CXXFLAGS],
[C++ compile flags for Google Test.])
AC_ARG_VAR([GTEST_LDFLAGS],
[Linker path and option flags for Google Test.])
AC_ARG_VAR([GTEST_LIBS],
[Library linking flags for Google Test.])
AC_ARG_VAR([GTEST_VERSION],
[The version of Google Test available.])
HAVE_GTEST="no"
AS_IF([test "x$enable_gtest" != "xno"],
[AC_PATH_PROG([GTEST_CONFIG], [gtest-config])
AS_IF([test -x "$GTEST_CONFIG"],
[AS_IF([test "x$1" != "x"],
[_min_version="--min-version=$1"
AC_MSG_CHECKING([for Google Test at least version >= $1])],
[_min_version="--min-version=0"
AC_MSG_CHECKING([for Google Test])])
AS_IF([$GTEST_CONFIG $_min_version],
[AC_MSG_RESULT([yes])
HAVE_GTEST="yes"],
[AC_MSG_RESULT([no])])])
AS_IF([test "x$HAVE_GTEST" = "xyes"],
[GTEST_CPPFLAGS=$($GTEST_CONFIG --cppflags)
GTEST_CXXFLAGS=$($GTEST_CONFIG --cxxflags)
GTEST_LDFLAGS=$($GTEST_CONFIG --ldflags)
GTEST_LIBS=$($GTEST_CONFIG --libs)
GTEST_VERSION=$($GTEST_CONFIG --version)
AC_DEFINE([HAVE_GTEST],[1],[Defined when Google Test is available.])],
[AS_IF([test "x$enable_gtest" = "xyes"],
[AC_MSG_ERROR([
The Google C++ Testing Framework was explicitly enabled, but a viable version
could not be found on the system.
])])])])
AC_SUBST([HAVE_GTEST])
AM_CONDITIONAL([HAVE_GTEST],[test "x$HAVE_GTEST" = "xyes"])
AS_IF([test "x$HAVE_GTEST" = "xyes"],
[AS_IF([test "x$2" != "x"],[$2],[:])],
[AS_IF([test "x$3" != "x"],[$3],[:])])
])

68
samples/sample1.cc Normal file
View File

@ -0,0 +1,68 @@
// 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.
// A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
#include "sample1.h"
// Returns n! (the factorial of n). For negative n, n! is defined to be 1.
int Factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
// Returns true iff n is a prime number.
bool IsPrime(int n) {
// Trivial case 1: small numbers
if (n <= 1) return false;
// Trivial case 2: even numbers
if (n % 2 == 0) return n == 2;
// Now, we have that n is odd and n >= 3.
// Try to divide n by every odd number i, starting from 3
for (int i = 3; ; i += 2) {
// We only have to try i up to the squre root of n
if (i > n/i) break;
// Now, we have i <= n/i < n.
// If n is divisible by i, n is not prime.
if (n % i == 0) return false;
}
// n has no integer factor in the range (1, n), and thus is prime.
return true;
}

43
samples/sample1.h Normal file
View File

@ -0,0 +1,43 @@
// 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.
// A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
#ifndef GTEST_SAMPLES_SAMPLE1_H_
#define GTEST_SAMPLES_SAMPLE1_H_
// Returns n! (the factorial of n). For negative n, n! is defined to be 1.
int Factorial(int n);
// Returns true iff n is a prime number.
bool IsPrime(int n);
#endif // GTEST_SAMPLES_SAMPLE1_H_

153
samples/sample1_unittest.cc Normal file
View File

@ -0,0 +1,153 @@
// 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.
// A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
// This sample shows how to write a simple unit test for a function,
// using Google C++ testing framework.
//
// Writing a unit test using Google C++ testing framework is easy as 1-2-3:
// Step 1. Include necessary header files such that the stuff your
// test logic needs is declared.
//
// Don't forget gtest.h, which declares the testing framework.
#include <limits.h>
#include "sample1.h"
#include <gtest/gtest.h>
// Step 2. Use the TEST macro to define your tests.
//
// TEST has two parameters: the test case name and the test name.
// After using the macro, you should define your test logic between a
// pair of braces. You can use a bunch of macros to indicate the
// success or failure of a test. EXPECT_TRUE and EXPECT_EQ are
// examples of such macros. For a complete list, see gtest.h.
//
// <TechnicalDetails>
//
// In Google Test, tests are grouped into test cases. This is how we
// keep test code organized. You should put logically related tests
// into the same test case.
//
// The test case name and the test name should both be valid C++
// identifiers. And you should not use underscore (_) in the names.
//
// Google Test guarantees that each test you define is run exactly
// once, but it makes no guarantee on the order the tests are
// executed. Therefore, you should write your tests in such a way
// that their results don't depend on their order.
//
// </TechnicalDetails>
// Tests Factorial().
// Tests factorial of negative numbers.
TEST(FactorialTest, Negative) {
// This test is named "Negative", and belongs to the "FactorialTest"
// test case.
EXPECT_EQ(1, Factorial(-5));
EXPECT_EQ(1, Factorial(-1));
EXPECT_TRUE(Factorial(-10) > 0);
// <TechnicalDetails>
//
// EXPECT_EQ(expected, actual) is the same as
//
// EXPECT_TRUE((expected) == (actual))
//
// except that it will print both the expected value and the actual
// value when the assertion fails. This is very helpful for
// debugging. Therefore in this case EXPECT_EQ is preferred.
//
// On the other hand, EXPECT_TRUE accepts any Boolean expression,
// and is thus more general.
//
// </TechnicalDetails>
}
// Tests factorial of 0.
TEST(FactorialTest, Zero) {
EXPECT_EQ(1, Factorial(0));
}
// Tests factorial of positive numbers.
TEST(FactorialTest, Positive) {
EXPECT_EQ(1, Factorial(1));
EXPECT_EQ(2, Factorial(2));
EXPECT_EQ(6, Factorial(3));
EXPECT_EQ(40320, Factorial(8));
}
// Tests IsPrime()
// Tests negative input.
TEST(IsPrimeTest, Negative) {
// This test belongs to the IsPrimeTest test case.
EXPECT_FALSE(IsPrime(-1));
EXPECT_FALSE(IsPrime(-2));
EXPECT_FALSE(IsPrime(INT_MIN));
}
// Tests some trivial cases.
TEST(IsPrimeTest, Trivial) {
EXPECT_FALSE(IsPrime(0));
EXPECT_FALSE(IsPrime(1));
EXPECT_TRUE(IsPrime(2));
EXPECT_TRUE(IsPrime(3));
}
// Tests positive input.
TEST(IsPrimeTest, Positive) {
EXPECT_FALSE(IsPrime(4));
EXPECT_TRUE(IsPrime(5));
EXPECT_FALSE(IsPrime(6));
EXPECT_TRUE(IsPrime(23));
}
// Step 3. Call RUN_ALL_TESTS() in main().
//
// We do this by linking in src/gtest_main.cc file, which consists of
// a main() function which calls RUN_ALL_TESTS() for us.
//
// This runs all the tests you've defined, prints the result, and
// returns 0 if successful, or 1 otherwise.
//
// Did you notice that we didn't register the tests? The
// RUN_ALL_TESTS() macro magically knows about all the tests we
// defined. Isn't this convenient?

54
samples/sample2.cc Normal file
View File

@ -0,0 +1,54 @@
// 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.
// A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
#include "sample2.h"
// Clones a 0-terminated C string, allocating memory using new.
const char * MyString::CloneCString(const char * c_string) {
if (c_string == NULL) return NULL;
const size_t len = strlen(c_string);
char * const clone = new char[ len + 1 ];
strcpy(clone, c_string);
return clone;
}
// Sets the 0-terminated C string this MyString object
// represents.
void MyString::Set(const char * c_string) {
// Makes sure this works when c_string == c_string_
const char * const temp = MyString::CloneCString(c_string);
delete[] c_string_;
c_string_ = temp;
}

86
samples/sample2.h Normal file
View File

@ -0,0 +1,86 @@
// 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.
// A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
#ifndef GTEST_SAMPLES_SAMPLE2_H_
#define GTEST_SAMPLES_SAMPLE2_H_
#include <string.h>
// A simple string class.
class MyString {
private:
const char * c_string_;
const MyString& operator=(const MyString& rhs);
public:
// Clones a 0-terminated C string, allocating memory using new.
static const char * CloneCString(const char * c_string);
////////////////////////////////////////////////////////////
//
// C'tors
// The default c'tor constructs a NULL string.
MyString() : c_string_(NULL) {}
// Constructs a MyString by cloning a 0-terminated C string.
explicit MyString(const char * c_string) : c_string_(NULL) {
Set(c_string);
}
// Copy c'tor
MyString(const MyString& string) : c_string_(NULL) {
Set(string.c_string_);
}
////////////////////////////////////////////////////////////
//
// D'tor. MyString is intended to be a final class, so the d'tor
// doesn't need to be virtual.
~MyString() { delete[] c_string_; }
// Gets the 0-terminated C string this MyString object represents.
const char * c_string() const { return c_string_; }
size_t Length() const {
return c_string_ == NULL ? 0 : strlen(c_string_);
}
// Sets the 0-terminated C string this MyString object represents.
void Set(const char * c_string);
};
#endif // GTEST_SAMPLES_SAMPLE2_H_

109
samples/sample2_unittest.cc Normal file
View File

@ -0,0 +1,109 @@
// 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.
// A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
// This sample shows how to write a more complex unit test for a class
// that has multiple member functions.
//
// Usually, it's a good idea to have one test for each method in your
// class. You don't have to do that exactly, but it helps to keep
// your tests organized. You may also throw in additional tests as
// needed.
#include "sample2.h"
#include <gtest/gtest.h>
// In this example, we test the MyString class (a simple string).
// Tests the default c'tor.
TEST(MyString, DefaultConstructor) {
const MyString s;
// Asserts that s.c_string() returns NULL.
//
// <TechnicalDetails>
//
// If we write NULL instead of
//
// static_cast<const char *>(NULL)
//
// in this assertion, it will generate a warning on gcc 3.4. The
// reason is that EXPECT_EQ needs to know the types of its
// arguments in order to print them when it fails. Since NULL is
// #defined as 0, the compiler will use the formatter function for
// int to print it. However, gcc thinks that NULL should be used as
// a pointer, not an int, and therefore complains.
//
// The root of the problem is C++'s lack of distinction between the
// integer number 0 and the null pointer constant. Unfortunately,
// we have to live with this fact.
//
// </TechnicalDetails>
EXPECT_STREQ(NULL, s.c_string());
EXPECT_EQ(0, s.Length());
}
const char kHelloString[] = "Hello, world!";
// Tests the c'tor that accepts a C string.
TEST(MyString, ConstructorFromCString) {
const MyString s(kHelloString);
EXPECT_TRUE(strcmp(s.c_string(), kHelloString) == 0);
EXPECT_EQ(sizeof(kHelloString)/sizeof(kHelloString[0]) - 1,
s.Length());
}
// Tests the copy c'tor.
TEST(MyString, CopyConstructor) {
const MyString s1(kHelloString);
const MyString s2 = s1;
EXPECT_TRUE(strcmp(s2.c_string(), kHelloString) == 0);
}
// Tests the Set method.
TEST(MyString, Set) {
MyString s;
s.Set(kHelloString);
EXPECT_TRUE(strcmp(s.c_string(), kHelloString) == 0);
// Set should work when the input pointer is the same as the one
// already in the MyString object.
s.Set(s.c_string());
EXPECT_TRUE(strcmp(s.c_string(), kHelloString) == 0);
// Can we set the MyString to NULL?
s.Set(NULL);
EXPECT_STREQ(NULL, s.c_string());
}

173
samples/sample3-inl.h Normal file
View File

@ -0,0 +1,173 @@
// 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.
// A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
#ifndef GTEST_SAMPLES_SAMPLE3_INL_H_
#define GTEST_SAMPLES_SAMPLE3_INL_H_
#include <stddef.h>
// Queue is a simple queue implemented as a singled-linked list.
//
// The element type must support copy constructor.
template <typename E> // E is the element type
class Queue;
// QueueNode is a node in a Queue, which consists of an element of
// type E and a pointer to the next node.
template <typename E> // E is the element type
class QueueNode {
friend class Queue<E>;
public:
// Gets the element in this node.
const E & element() const { return element_; }
// Gets the next node in the queue.
QueueNode * next() { return next_; }
const QueueNode * next() const { return next_; }
private:
// Creates a node with a given element value. The next pointer is
// set to NULL.
QueueNode(const E & element) : element_(element), next_(NULL) {}
// We disable the default assignment operator and copy c'tor.
const QueueNode & operator = (const QueueNode &);
QueueNode(const QueueNode &);
E element_;
QueueNode * next_;
};
template <typename E> // E is the element type.
class Queue {
public:
// Creates an empty queue.
Queue() : head_(NULL), last_(NULL), size_(0) {}
// D'tor. Clears the queue.
~Queue() { Clear(); }
// Clears the queue.
void Clear() {
if (size_ > 0) {
// 1. Deletes every node.
QueueNode<E> * node = head_;
QueueNode<E> * next = node->next();
for (; ;) {
delete node;
node = next;
if (node == NULL) break;
next = node->next();
}
// 2. Resets the member variables.
head_ = last_ = NULL;
size_ = 0;
}
}
// Gets the number of elements.
size_t Size() const { return size_; }
// Gets the first element of the queue, or NULL if the queue is empty.
QueueNode<E> * Head() { return head_; }
const QueueNode<E> * Head() const { return head_; }
// Gets the last element of the queue, or NULL if the queue is empty.
QueueNode<E> * Last() { return last_; }
const QueueNode<E> * Last() const { return last_; }
// Adds an element to the end of the queue. A copy of the element is
// created using the copy constructor, and then stored in the queue.
// Changes made to the element in the queue doesn't affect the source
// object, and vice versa.
void Enqueue(const E & element) {
QueueNode<E> * new_node = new QueueNode<E>(element);
if (size_ == 0) {
head_ = last_ = new_node;
size_ = 1;
} else {
last_->next_ = new_node;
last_ = new_node;
size_++;
}
}
// Removes the head of the queue and returns it. Returns NULL if
// the queue is empty.
E * Dequeue() {
if (size_ == 0) {
return NULL;
}
const QueueNode<E> * const old_head = head_;
head_ = head_->next_;
size_--;
if (size_ == 0) {
last_ = NULL;
}
E * element = new E(old_head->element());
delete old_head;
return element;
}
// Applies a function/functor on each element of the queue, and
// returns the result in a new queue. The original queue is not
// affected.
template <typename F>
Queue * Map(F function) const {
Queue * new_queue = new Queue();
for (const QueueNode<E> * node = head_; node != NULL; node = node->next_) {
new_queue->Enqueue(function(node->element()));
}
return new_queue;
}
private:
QueueNode<E> * head_; // The first node of the queue.
QueueNode<E> * last_; // The last node of the queue.
size_t size_; // The number of elements in the queue.
// We disallow copying a queue.
Queue(const Queue &);
const Queue & operator = (const Queue &);
};
#endif // GTEST_SAMPLES_SAMPLE3_INL_H_

151
samples/sample3_unittest.cc Normal file
View File

@ -0,0 +1,151 @@
// 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.
// A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
// In this example, we use a more advanced feature of Google Test called
// test fixture.
//
// A test fixture is a place to hold objects and functions shared by
// all tests in a test case. Using a test fixture avoids duplicating
// the test code necessary to initialize and cleanup those common
// objects for each test. It is also useful for defining sub-routines
// that your tests need to invoke a lot.
//
// <TechnicalDetails>
//
// The tests share the test fixture in the sense of code sharing, not
// data sharing. Each test is given its own fresh copy of the
// fixture. You cannot expect the data modified by one test to be
// passed on to another test, which is a bad idea.
//
// The reason for this design is that tests should be independent and
// repeatable. In particular, a test should not fail as the result of
// another test's failure. If one test depends on info produced by
// another test, then the two tests should really be one big test.
//
// The macros for indicating the success/failure of a test
// (EXPECT_TRUE, FAIL, etc) need to know what the current test is
// (when Google Test prints the test result, it tells you which test
// each failure belongs to). Technically, these macros invoke a
// member function of the Test class. Therefore, you cannot use them
// in a global function. That's why you should put test sub-routines
// in a test fixture.
//
// </TechnicalDetails>
#include "sample3-inl.h"
#include <gtest/gtest.h>
// To use a test fixture, derive a class from testing::Test.
class QueueTest : public testing::Test {
protected: // You should make the members protected s.t. they can be
// accessed from sub-classes.
// virtual void SetUp() will be called before each test is run. You
// should define it if you need to initialize the varaibles.
// Otherwise, this can be skipped.
virtual void SetUp() {
q1_.Enqueue(1);
q2_.Enqueue(2);
q2_.Enqueue(3);
}
// virtual void TearDown() will be called after each test is run.
// You should define it if there is cleanup work to do. Otherwise,
// you don't have to provide it.
//
// virtual void TearDown() {
// }
// A helper function that some test uses.
static int Double(int n) {
return 2*n;
}
// A helper function for testing Queue::Map().
void MapTester(const Queue<int> * q) {
// Creates a new queue, where each element is twice as big as the
// corresponding one in q.
const Queue<int> * const new_q = q->Map(Double);
// Verifies that the new queue has the same size as q.
ASSERT_EQ(q->Size(), new_q->Size());
// Verifies the relationship between the elements of the two queues.
for ( const QueueNode<int> * n1 = q->Head(), * n2 = new_q->Head();
n1 != NULL; n1 = n1->next(), n2 = n2->next() ) {
EXPECT_EQ(2 * n1->element(), n2->element());
}
delete new_q;
}
// Declares the variables your tests want to use.
Queue<int> q0_;
Queue<int> q1_;
Queue<int> q2_;
};
// When you have a test fixture, you define a test using TEST_F
// instead of TEST.
// Tests the default c'tor.
TEST_F(QueueTest, DefaultConstructor) {
// You can access data in the test fixture here.
EXPECT_EQ(0, q0_.Size());
}
// Tests Dequeue().
TEST_F(QueueTest, Dequeue) {
int * n = q0_.Dequeue();
EXPECT_TRUE(n == NULL);
n = q1_.Dequeue();
ASSERT_TRUE(n != NULL);
EXPECT_EQ(1, *n);
EXPECT_EQ(0, q1_.Size());
delete n;
n = q2_.Dequeue();
ASSERT_TRUE(n != NULL);
EXPECT_EQ(2, *n);
EXPECT_EQ(1, q2_.Size());
delete n;
}
// Tests the Queue::Map() function.
TEST_F(QueueTest, Map) {
MapTester(&q0_);
MapTester(&q1_);
MapTester(&q2_);
}

46
samples/sample4.cc Normal file
View File

@ -0,0 +1,46 @@
// 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.
// A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
#include <stdio.h>
#include "sample4.h"
// Returns the current counter value, and increments it.
int Counter::Increment() {
return counter_++;
}
// Prints the current counter value to STDOUT.
void Counter::Print() const {
printf("%d", counter_);
}

53
samples/sample4.h Normal file
View File

@ -0,0 +1,53 @@
// 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.
// A sample program demonstrating using Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
#ifndef GTEST_SAMPLES_SAMPLE4_H_
#define GTEST_SAMPLES_SAMPLE4_H_
// A simple monotonic counter.
class Counter {
private:
int counter_;
public:
// Creates a counter that starts at 0.
Counter() : counter_(0) {}
// Returns the current counter value, and increments it.
int Increment();
// Prints the current counter value to STDOUT.
void Print() const;
};
#endif // GTEST_SAMPLES_SAMPLE4_H_

View File

@ -0,0 +1,45 @@
// 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)
#include <gtest/gtest.h>
#include "sample4.h"
// Tests the Increment() method.
TEST(Counter, Increment) {
Counter c;
// EXPECT_EQ() evaluates its arguments exactly once, so they
// can have side effects.
EXPECT_EQ(0, c.Increment());
EXPECT_EQ(1, c.Increment());
EXPECT_EQ(2, c.Increment());
}

199
samples/sample5_unittest.cc Normal file
View File

@ -0,0 +1,199 @@
// 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 sample teaches how to reuse a test fixture in multiple test
// cases by deriving sub-fixtures from it.
//
// When you define a test fixture, you specify the name of the test
// case that will use this fixture. Therefore, a test fixture can
// be used by only one test case.
//
// Sometimes, more than one test cases may want to use the same or
// slightly different test fixtures. For example, you may want to
// make sure that all tests for a GUI library don't leak important
// system resources like fonts and brushes. In Google Test, you do
// this by putting the shared logic in a super (as in "super class")
// test fixture, and then have each test case use a fixture derived
// from this super fixture.
#include <limits.h>
#include <time.h>
#include "sample3-inl.h"
#include <gtest/gtest.h>
#include "sample1.h"
// In this sample, we want to ensure that every test finishes within
// ~5 seconds. If a test takes longer to run, we consider it a
// failure.
//
// We put the code for timing a test in a test fixture called
// "QuickTest". QuickTest is intended to be the super fixture that
// other fixtures derive from, therefore there is no test case with
// the name "QuickTest". This is OK.
//
// Later, we will derive multiple test fixtures from QuickTest.
class QuickTest : public testing::Test {
protected:
// Remember that SetUp() is run immediately before a test starts.
// This is a good place to record the start time.
virtual void SetUp() {
start_time_ = time(NULL);
}
// TearDown() is invoked immediately after a test finishes. Here we
// check if the test was too slow.
virtual void TearDown() {
// Gets the time when the test finishes
const time_t end_time = time(NULL);
// Asserts that the test took no more than ~5 seconds. Did you
// know that you can use assertions in SetUp() and TearDown() as
// well?
EXPECT_TRUE(end_time - start_time_ <= 5) << "The test took too long.";
}
// The UTC time (in seconds) when the test starts
time_t start_time_;
};
// We derive a fixture named IntegerFunctionTest from the QuickTest
// fixture. All tests using this fixture will be automatically
// required to be quick.
class IntegerFunctionTest : public QuickTest {
// We don't need any more logic than already in the QuickTest fixture.
// Therefore the body is empty.
};
// Now we can write tests in the IntegerFunctionTest test case.
// Tests Factorial()
TEST_F(IntegerFunctionTest, Factorial) {
// Tests factorial of negative numbers.
EXPECT_EQ(1, Factorial(-5));
EXPECT_EQ(1, Factorial(-1));
EXPECT_TRUE(Factorial(-10) > 0);
// Tests factorial of 0.
EXPECT_EQ(1, Factorial(0));
// Tests factorial of positive numbers.
EXPECT_EQ(1, Factorial(1));
EXPECT_EQ(2, Factorial(2));
EXPECT_EQ(6, Factorial(3));
EXPECT_EQ(40320, Factorial(8));
}
// Tests IsPrime()
TEST_F(IntegerFunctionTest, IsPrime) {
// Tests negative input.
EXPECT_TRUE(!IsPrime(-1));
EXPECT_TRUE(!IsPrime(-2));
EXPECT_TRUE(!IsPrime(INT_MIN));
// Tests some trivial cases.
EXPECT_TRUE(!IsPrime(0));
EXPECT_TRUE(!IsPrime(1));
EXPECT_TRUE(IsPrime(2));
EXPECT_TRUE(IsPrime(3));
// Tests positive input.
EXPECT_TRUE(!IsPrime(4));
EXPECT_TRUE(IsPrime(5));
EXPECT_TRUE(!IsPrime(6));
EXPECT_TRUE(IsPrime(23));
}
// The next test case (named "QueueTest") also needs to be quick, so
// we derive another fixture from QuickTest.
//
// The QueueTest test fixture has some logic and shared objects in
// addition to what's in QuickTest already. We define the additional
// stuff inside the body of the test fixture, as usual.
class QueueTest : public QuickTest {
protected:
virtual void SetUp() {
// First, we need to set up the super fixture (QuickTest).
QuickTest::SetUp();
// Second, some additional setup for this fixture.
q1_.Enqueue(1);
q2_.Enqueue(2);
q2_.Enqueue(3);
}
// By default, TearDown() inherits the behavior of
// QuickTest::TearDown(). As we have no additional cleaning work
// for QueueTest, we omit it here.
//
// virtual void TearDown() {
// QuickTest::TearDown();
// }
Queue<int> q0_;
Queue<int> q1_;
Queue<int> q2_;
};
// Now, let's write tests using the QueueTest fixture.
// Tests the default constructor.
TEST_F(QueueTest, DefaultConstructor) {
EXPECT_EQ(0, q0_.Size());
}
// Tests Dequeue().
TEST_F(QueueTest, Dequeue) {
int * n = q0_.Dequeue();
EXPECT_TRUE(n == NULL);
n = q1_.Dequeue();
EXPECT_TRUE(n != NULL);
EXPECT_EQ(1, *n);
EXPECT_EQ(0, q1_.Size());
delete n;
n = q2_.Dequeue();
EXPECT_TRUE(n != NULL);
EXPECT_EQ(2, *n);
EXPECT_EQ(1, q2_.Size());
delete n;
}
// If necessary, you can derive further test fixtures from a derived
// fixture itself. For example, you can derive another fixture from
// QueueTest. Google Test imposes no limit on how deep the hierarchy
// can be. In practice, however, you probably don't want it to be too
// deep as to be confusing.

733
scripts/gen_gtest_pred_impl.py Executable file
View File

@ -0,0 +1,733 @@
#!/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()

199
scripts/gtest-config.in Executable file
View File

@ -0,0 +1,199 @@
#!/bin/sh
# These variables are automatically filled in by the configure script.
prefix="@prefix@"
exec_prefix="@exec_prefix@"
libdir="@libdir@"
includedir="@includedir@"
name="@PACKAGE_TARNAME@"
version="@PACKAGE_VERSION@"
gtest_ldflags="-L${libdir}"
gtest_libs="-l${name}"
gtest_cppflags="-I${includedir}"
gtest_cxxflags=""
show_usage()
{
cat <<EOF
Usage: gtest-config [OPTIONS...]
EOF
}
show_help()
{
show_usage
cat <<EOF
The \`gtest-config' script provides access to the necessary compile and linking
flags to connect with Google C++ Testing framework. The installation queries
may only be issued one at a time, and may not be issued with any other types of
queries. The version queries and compiler flag queries may be combined as
desired but not mixed. Different version queries are always combined with "and"
logical semantics, and only the last of any particular query is used and all
previous ones ignored. All versions must be specified as a sequence of numbers
separated by periods. Compiler flag queries output the union of the sets of
flags when combined.
Examples:
gtest-config --min-version=1.0 || echo "Insufficient Google Test version."
gcc \$(gtest-config --cppflags --cxxflags) -o foo.o -c foo.cpp
gcc \$(gtest-config --ldflags --libs) -o foo foo.o
Help:
--usage brief usage information
--help display this help message
Installation Queries:
--prefix installation prefix
--exec-prefix executable installation prefix
--libdir library installation directory
--includedir header file installation directory
--version the version of the INC installation
Version Queries:
--min-version=VERSION return 0 if the version is at least VERSION
--exact-version=VERSION return 0 if the version is exactly VERSION
--max-version=VERSION return 0 if the version is at most VERSION
Compilation Flag Queries:
--cppflags compile flags specific to the C-like preprocessors
--cxxflags compile flags appropriate for C++ programs
--ldflags linker flags
--libs libraries for linking
EOF
}
# This function bounds our version with a min and a max. It uses some clever
# POSIX-compliant variable expansion to portably do all the work in the shell
# and avoid any dependency on a particular "sed" implementation. Notable is
# that it will only ever compare the first 3 components of versions. Further
# components will be cleanly stripped off. All versions must be unadorned, so
# "v1.0" will *not* work. The minimum version must be in $1, and the max in
# $2.
check_versions()
{
major_version=${version%%.*}
minor_version="0"
point_version="0"
if test "${version#*.}" != "${version}"; then
minor_version=${version#*.}
minor_version=${minor_version%%.*}
fi
if test "${version#*.*.}" != "${version}"; then
point_version=${version#*.*.}
point_version=${point_version%%.*}
fi
min_version="$1"
min_major_version=${min_version%%.*}
min_minor_version="0"
min_point_version="0"
if test "${min_version#*.}" != "${min_version}"; then
min_minor_version=${min_version#*.}
min_minor_version=${min_minor_version%%.*}
fi
if test "${min_version#*.*.}" != "${min_version}"; then
min_point_version=${min_version#*.*.}
min_point_version=${min_point_version%%.*}
fi
max_version="$2"
max_major_version=${max_version%%.*}
max_minor_version="0"
max_point_version="0"
if test "${max_version#*.}" != "${max_version}"; then
max_minor_version=${max_version#*.}
max_minor_version=${max_minor_version%%.*}
fi
if test "${max_version#*.*.}" != "${max_version}"; then
max_point_version=${max_version#*.*.}
max_point_version=${max_point_version%%.*}
fi
test $(($major_version)) -lt $(($min_major_version)) && exit 1
if test $(($major_version)) -eq $(($min_major_version)); then
test $(($minor_version)) -lt $(($min_minor_version)) && exit 1
if test $(($minor_version)) -eq $(($min_minor_version)); then
test $(($point_version)) -lt $(($min_point_version)) && exit 1
fi
fi
test $(($major_version)) -gt $(($max_major_version)) && exit 1
if test $(($major_version)) -eq $(($max_major_version)); then
test $(($minor_version)) -gt $(($max_minor_version)) && exit 1
if test $(($minor_version)) -eq $(($max_minor_version)); then
test $(($point_version)) -gt $(($max_point_version)) && exit 1
fi
fi
exit 0
}
# Show the usage line when no arguments are specified.
if test $# -eq 0; then
show_usage
exit 1
fi
while test $# -gt 0; do
case $1 in
--usage) show_usage; exit 0;;
--help) show_help; exit 0;;
--prefix) echo $prefix; exit 0;;
--exec-prefix) echo $exec_prefix; exit 0;;
--libdir) echo $libdir; exit 0;;
--includedir) echo $includedir; exit 0;;
--version) echo $version; exit 0;;
--min-version=*)
do_check_versions=yes
min_version=${1#--min-version=}
;;
--max-version=*)
do_check_versions=yes
max_version=${1#--max-version=}
;;
--exact-version=*)
do_check_versions=yes
exact_version=${1#--exact-version=}
;;
--cppflags) echo_cppflags=yes;;
--cxxflags) echo_cxxflags=yes;;
--ldflags) echo_ldflags=yes;;
--libs) echo_libs=yes;;
# Everything else is an error
*) show_usage; exit 1;;
esac
shift
done
# Do a version check if requested.
if test "$do_check_versions" = "yes"; then
# Make sure we didn't receive a bad combination of parameters.
test "$echo_cppflags" = "yes" && show_usage && exit 1
test "$echo_cxxflags" = "yes" && show_usage && exit 1
test "$echo_ldflags" = "yes" && show_usage && exit 1
test "$echo_libs" = "yes" && show_usage && exit 1
if test "$exact_version" != ""; then
check_versions $exact_version $exact_version
# unreachable
else
check_versions ${min_version:-0.0.0} ${max_version:-9999.9999.9999}
# unreachable
fi
fi
# Do the output in the correct order so that these can be used in-line of
# a compiler invocation.
output=""
test "$echo_cppflags" = "yes" && output="$output $gtest_cppflags"
test "$echo_cxxflags" = "yes" && output="$output $gtest_cxxflags"
test "$echo_ldflags" = "yes" && output="$output $gtest_ldflags"
test "$echo_libs" = "yes" && output="$output $gtest_libs"
echo $output
exit 0

751
src/gtest-death-test.cc Normal file
View File

@ -0,0 +1,751 @@
// 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

208
src/gtest-filepath.cc Normal file
View File

@ -0,0 +1,208 @@
// 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
const char kPathSeparator = '\\';
const char kPathSeparatorString[] = "\\";
const char kCurrentDirectoryString[] = ".\\";
#else
const char kPathSeparator = '/';
const char kPathSeparatorString[] = "/";
const char kCurrentDirectoryString[] = "./";
#endif // GTEST_OS_WINDOWS
// Returns a copy of the FilePath with the case-insensitive extension removed.
// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
// FilePath("dir/file"). If a case-insensitive extension is not
// found, returns a copy of the original FilePath.
FilePath FilePath::RemoveExtension(const char* extension) const {
String dot_extension(String::Format(".%s", extension));
if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) {
return FilePath(String(pathname_.c_str(), pathname_.GetLength() - 4));
}
return *this;
}
// Returns a copy of the FilePath with the directory part removed.
// Example: FilePath("path/to/file").RemoveDirectoryName() returns
// FilePath("file"). If there is no directory part ("just_a_file"), it returns
// the FilePath unmodified. If there is no file part ("just_a_dir/") it
// returns an empty FilePath ("").
// On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath FilePath::RemoveDirectoryName() const {
const char* const last_sep = strrchr(c_str(), kPathSeparator);
return last_sep ? FilePath(String(last_sep + 1)) : *this;
}
// RemoveFileName returns the directory path with the filename removed.
// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
// On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath FilePath::RemoveFileName() const {
const char* const last_sep = strrchr(c_str(), kPathSeparator);
return FilePath(last_sep ? String(c_str(), last_sep + 1 - c_str())
: String(kCurrentDirectoryString));
}
// Helper functions for naming files in a directory for xml output.
// Given directory = "dir", base_name = "test", number = 0,
// extension = "xml", returns "dir/test.xml". If number is greater
// than zero (e.g., 12), returns "dir/test_12.xml".
// On Windows platform, uses \ as the separator rather than /.
FilePath FilePath::MakeFileName(const FilePath& directory,
const FilePath& base_name,
int number,
const char* extension) {
FilePath dir(directory.RemoveTrailingPathSeparator());
if (number == 0) {
return FilePath(String::Format("%s%c%s.%s", dir.c_str(), kPathSeparator,
base_name.c_str(), extension));
}
return FilePath(String::Format("%s%c%s_%d.%s", dir.c_str(), kPathSeparator,
base_name.c_str(), number, extension));
}
// Returns true if pathname describes something findable in the file-system,
// either a file, directory, or whatever.
bool FilePath::FileOrDirectoryExists() const {
#ifdef GTEST_OS_WINDOWS
struct _stat file_stat = {};
return _stat(pathname_.c_str(), &file_stat) == 0;
#else
struct stat file_stat = {};
return stat(pathname_.c_str(), &file_stat) == 0;
#endif // GTEST_OS_WINDOWS
}
// Returns true if pathname describes a directory in the file-system
// that exists.
bool FilePath::DirectoryExists() const {
bool result = false;
#ifdef _WIN32
FilePath removed_sep(this->RemoveTrailingPathSeparator());
struct _stat file_stat = {};
result = _stat(removed_sep.c_str(), &file_stat) == 0 &&
(_S_IFDIR & file_stat.st_mode) != 0;
#else
struct stat file_stat = {};
result = stat(pathname_.c_str(), &file_stat) == 0 &&
S_ISDIR(file_stat.st_mode);
#endif // _WIN32
return result;
}
// Returns a pathname for a file that does not currently exist. The pathname
// will be directory/base_name.extension or
// directory/base_name_<number>.extension if directory/base_name.extension
// already exists. The number will be incremented until a pathname is found
// that does not already exist.
// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
// There could be a race condition if two or more processes are calling this
// function at the same time -- they could both pick the same filename.
FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
const FilePath& base_name,
const char* extension) {
FilePath full_pathname;
int number = 0;
do {
full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
} while (full_pathname.FileOrDirectoryExists());
return full_pathname;
}
// Returns true if FilePath ends with a path separator, which indicates that
// it is intended to represent a directory. Returns false otherwise.
// This does NOT check that a directory (or file) actually exists.
bool FilePath::IsDirectory() const {
return pathname_.EndsWith(kPathSeparatorString);
}
// Create directories so that path exists. Returns true if successful or if
// the directories already exist; returns false if unable to create directories
// for any reason.
bool FilePath::CreateDirectoriesRecursively() const {
if (!this->IsDirectory()) {
return false;
}
if (pathname_.GetLength() == 0 || this->DirectoryExists()) {
return true;
}
const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
return parent.CreateDirectoriesRecursively() && this->CreateFolder();
}
// Create the directory so that path exists. Returns true if successful or
// if the directory already exists; returns false if unable to create the
// directory for any reason, including if the parent directory does not
// exist. Not named "CreateDirectory" because that's a macro on Windows.
bool FilePath::CreateFolder() const {
#ifdef _WIN32
int result = _mkdir(pathname_.c_str());
#else
int result = mkdir(pathname_.c_str(), 0777);
#endif // _WIN32
if (result == -1) {
return this->DirectoryExists(); // An error is OK if the directory exists.
}
return true; // No error.
}
// If input name has a trailing separator character, remove it and return the
// name, otherwise return the name string unmodified.
// On Windows platform, uses \ as the separator, other platforms use /.
FilePath FilePath::RemoveTrailingPathSeparator() const {
return pathname_.EndsWith(kPathSeparatorString)
? FilePath(String(pathname_.c_str(), pathname_.GetLength() - 1))
: *this;
}
} // namespace internal
} // namespace testing

1118
src/gtest-internal-inl.h Normal file

File diff suppressed because it is too large Load Diff

292
src/gtest-port.cc Normal file
View File

@ -0,0 +1,292 @@
// 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.
//
// Author: wan@google.com (Zhanyong Wan)
#include <gtest/internal/gtest-port.h>
#include <limits.h>
#ifdef GTEST_HAS_DEATH_TEST
#include <regex.h>
#endif // GTEST_HAS_DEATH_TEST
#include <stdlib.h>
#include <stdio.h>
#include <gtest/gtest-spi.h>
#include <gtest/gtest-message.h>
#include <gtest/internal/gtest-string.h>
namespace testing {
namespace internal {
#ifdef GTEST_HAS_DEATH_TEST
// Implements RE. Currently only needed for death tests.
RE::~RE() {
regfree(&regex_);
free(const_cast<char*>(pattern_));
}
// Returns true iff str contains regular expression re.
bool RE::PartialMatch(const char* str, const RE& re) {
if (!re.is_valid_) return false;
regmatch_t match;
return regexec(&re.regex_, str, 1, &match, 0) == 0;
}
// Initializes an RE from its string representation.
void RE::Init(const char* regex) {
pattern_ = strdup(regex);
is_valid_ = regcomp(&regex_, regex, REG_EXTENDED) == 0;
EXPECT_TRUE(is_valid_)
<< "Regular expression \"" << regex
<< "\" is not a valid POSIX Extended regular expression.";
}
#endif // GTEST_HAS_DEATH_TEST
// Logs a message at the given severity level.
void GTestLog(GTestLogSeverity severity, const char* file,
int line, const char* msg) {
const char* const marker =
severity == GTEST_INFO ? "[ INFO ]" :
severity == GTEST_WARNING ? "[WARNING]" :
severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
fprintf(stderr, "\n%s %s:%d: %s\n", marker, file, line, msg);
if (severity == GTEST_FATAL) {
abort();
}
}
#ifdef GTEST_HAS_DEATH_TEST
// Defines the stderr capturer.
class CapturedStderr {
public:
// The ctor redirects stderr to a temporary file.
CapturedStderr() {
uncaptured_fd_ = dup(STDERR_FILENO);
char name_template[] = "captured_stderr.XXXXXX";
const int captured_fd = mkstemp(name_template);
filename_ = name_template;
fflush(NULL);
dup2(captured_fd, STDERR_FILENO);
close(captured_fd);
}
~CapturedStderr() {
remove(filename_.c_str());
}
// Stops redirecting stderr.
void StopCapture() {
// Restores the original stream.
fflush(NULL);
dup2(uncaptured_fd_, STDERR_FILENO);
close(uncaptured_fd_);
uncaptured_fd_ = -1;
}
// Returns the name of the temporary file holding the stderr output.
// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
// can use it here.
::std::string filename() const { return filename_; }
private:
int uncaptured_fd_;
::std::string filename_;
};
static CapturedStderr* g_captured_stderr = NULL;
// Returns the size (in bytes) of a file.
static size_t GetFileSize(FILE * file) {
fseek(file, 0, SEEK_END);
return static_cast<size_t>(ftell(file));
}
// Reads the entire content of a file as a string.
// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can
// use it here.
static ::std::string ReadEntireFile(FILE * file) {
const size_t file_size = GetFileSize(file);
char* const buffer = new char[file_size];
size_t bytes_last_read = 0; // # of bytes read in the last fread()
size_t bytes_read = 0; // # of bytes read so far
fseek(file, 0, SEEK_SET);
// Keeps reading the file until we cannot read further or the
// pre-determined file size is reached.
do {
bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
bytes_read += bytes_last_read;
} while (bytes_last_read > 0 && bytes_read < file_size);
const ::std::string content(buffer, buffer+bytes_read);
delete[] buffer;
return content;
}
// Starts capturing stderr.
void CaptureStderr() {
if (g_captured_stderr != NULL) {
GTEST_LOG(FATAL, "Only one stderr capturer can exist at one time.");
}
g_captured_stderr = new CapturedStderr;
}
// Stops capturing stderr and returns the captured string.
// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can
// use it here.
::std::string GetCapturedStderr() {
g_captured_stderr->StopCapture();
FILE* const file = fopen(g_captured_stderr->filename().c_str(), "r");
const ::std::string content = ReadEntireFile(file);
fclose(file);
delete g_captured_stderr;
g_captured_stderr = NULL;
return content;
}
// A copy of all command line arguments. Set by InitGoogleTest().
::std::vector<String> g_argvs;
// Returns the command line as a vector of strings.
const ::std::vector<String>& GetArgvs() { return g_argvs; }
#endif // GTEST_HAS_DEATH_TEST
// Returns the name of the environment variable corresponding to the
// given flag. For example, FlagToEnvVar("foo") will return
// "GTEST_FOO" in the open-source version.
static String FlagToEnvVar(const char* flag) {
const String full_flag = (Message() << GTEST_FLAG_PREFIX << flag).GetString();
Message env_var;
for (int i = 0; i != full_flag.GetLength(); i++) {
env_var << static_cast<char>(toupper(full_flag.c_str()[i]));
}
return env_var.GetString();
}
// Reads and returns the Boolean environment variable corresponding to
// the given flag; if it's not set, returns default_value.
//
// The value is considered true iff it's not "0".
bool BoolFromGTestEnv(const char* flag, bool default_value) {
const String env_var = FlagToEnvVar(flag);
const char* const string_value = GetEnv(env_var.c_str());
return string_value == NULL ?
default_value : strcmp(string_value, "0") != 0;
}
// Parses 'str' for a 32-bit signed integer. If successful, writes
// the result to *value and returns true; otherwise leaves *value
// unchanged and returns false.
bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
// Parses the environment variable as a decimal integer.
char* end = NULL;
const long long_value = strtol(str, &end, 10); // NOLINT
// Has strtol() consumed all characters in the string?
if (*end != '\0') {
// No - an invalid character was encountered.
Message msg;
msg << "WARNING: " << src_text
<< " is expected to be a 32-bit integer, but actually"
<< " has value \"" << str << "\".\n";
printf("%s", msg.GetString().c_str());
fflush(stdout);
return false;
}
// Is the parsed value in the range of an Int32?
const Int32 result = static_cast<Int32>(long_value);
if (long_value == LONG_MAX || long_value == LONG_MIN ||
// The parsed value overflows as a long. (strtol() returns
// LONG_MAX or LONG_MIN when the input overflows.)
result != long_value
// The parsed value overflows as an Int32.
) {
Message msg;
msg << "WARNING: " << src_text
<< " is expected to be a 32-bit integer, but actually"
<< " has value " << str << ", which overflows.\n";
printf("%s", msg.GetString().c_str());
fflush(stdout);
return false;
}
*value = result;
return true;
}
// Reads and returns a 32-bit integer stored in the environment
// variable corresponding to the given flag; if it isn't set or
// doesn't represent a valid 32-bit integer, returns default_value.
Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
const String env_var = FlagToEnvVar(flag);
const char* const string_value = GetEnv(env_var.c_str());
if (string_value == NULL) {
// The environment variable is not set.
return default_value;
}
Int32 result = default_value;
if (!ParseInt32(Message() << "Environment variable " << env_var,
string_value, &result)) {
printf("The default value %s is used.\n",
(Message() << default_value).GetString().c_str());
fflush(stdout);
return default_value;
}
return result;
}
// Reads and returns the string environment variable corresponding to
// the given flag; if it's not set, returns default_value.
const char* StringFromGTestEnv(const char* flag, const char* default_value) {
const String env_var = FlagToEnvVar(flag);
const char* const value = GetEnv(env_var.c_str());
return value == NULL ? default_value : value;
}
} // namespace internal
} // namespace testing

3545
src/gtest.cc Normal file

File diff suppressed because it is too large Load Diff

39
src/gtest_main.cc Normal file
View File

@ -0,0 +1,39 @@
// 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.
#include <iostream>
#include <gtest/gtest.h>
int main(int argc, char **argv) {
std::cout << "Running main() from gtest_main.cc\n";
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -0,0 +1,862 @@
// 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)
//
// Tests for death tests.
#include <gtest/gtest-death-test.h>
#include <gtest/gtest.h>
#ifdef GTEST_HAS_DEATH_TEST
#include <gtest/gtest-spi.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 "src/gtest-internal-inl.h"
#undef GTEST_IMPLEMENTATION
using testing::internal::DeathTest;
using testing::internal::DeathTestFactory;
namespace testing {
namespace internal {
// A helper class whose objects replace the death test factory for a
// single UnitTest object during their lifetimes.
class ReplaceDeathTestFactory {
public:
ReplaceDeathTestFactory(UnitTest* parent, DeathTestFactory* new_factory)
: parent_impl_(parent->impl()) {
old_factory_ = parent_impl_->death_test_factory_.release();
parent_impl_->death_test_factory_.reset(new_factory);
}
~ReplaceDeathTestFactory() {
parent_impl_->death_test_factory_.release();
parent_impl_->death_test_factory_.reset(old_factory_);
}
private:
// Prevents copying ReplaceDeathTestFactory objects.
ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
void operator=(const ReplaceDeathTestFactory&);
UnitTestImpl* parent_impl_;
DeathTestFactory* old_factory_;
};
} // namespace internal
} // namespace testing
// Tests that death tests work.
class TestForDeathTest : public testing::Test {
protected:
// A static member function that's expected to die.
static void StaticMemberFunction() {
GTEST_LOG(FATAL, "death inside StaticMemberFunction().");
}
// A method of the test fixture that may die.
void MemberFunction() {
if (should_die_) {
GTEST_LOG(FATAL, "death inside MemberFunction().");
}
}
// True iff MemberFunction() should die.
bool should_die_;
};
// A class with a member function that may die.
class MayDie {
public:
explicit MayDie(bool should_die) : should_die_(should_die) {}
// A member function that may die.
void MemberFunction() const {
if (should_die_) {
GTEST_LOG(FATAL, "death inside MayDie::MemberFunction().");
}
}
private:
// True iff MemberFunction() should die.
bool should_die_;
};
// A global function that's expected to die.
void GlobalFunction() {
GTEST_LOG(FATAL, "death inside GlobalFunction().");
}
// A non-void function that's expected to die.
int NonVoidFunction() {
GTEST_LOG(FATAL, "death inside NonVoidFunction().");
return 1;
}
// A unary function that may die.
void DieIf(bool should_die) {
if (should_die) {
GTEST_LOG(FATAL, "death inside DieIf().");
}
}
// A binary function that may die.
bool DieIfLessThan(int x, int y) {
if (x < y) {
GTEST_LOG(FATAL, "death inside DieIfLessThan().");
}
return true;
}
// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
void DeathTestSubroutine() {
EXPECT_DEATH(GlobalFunction(), "death.*GlobalFunction");
ASSERT_DEATH(GlobalFunction(), "death.*GlobalFunction");
}
// Death in dbg, not opt.
int DieInDebugElse12(int* sideeffect) {
if (sideeffect) *sideeffect = 12;
#ifndef NDEBUG
GTEST_LOG(FATAL, "debug death inside DieInDebugElse12()");
#endif // NDEBUG
return 12;
}
// Returns the exit status of a process that calls exit(2) with a
// given exit code. This is a helper function for the
// ExitStatusPredicateTest test suite.
static int NormalExitStatus(int exit_code) {
pid_t child_pid = fork();
if (child_pid == 0) {
exit(exit_code);
}
int status;
waitpid(child_pid, &status, 0);
return status;
}
// Returns the exit status of a process that raises a given signal.
// If the signal does not cause the process to die, then it returns
// instead the exit status of a process that exits normally with exit
// code 1. This is a helper function for the ExitStatusPredicateTest
// test suite.
static int KilledExitStatus(int signum) {
pid_t child_pid = fork();
if (child_pid == 0) {
raise(signum);
exit(1);
}
int status;
waitpid(child_pid, &status, 0);
return status;
}
// Tests the ExitedWithCode predicate.
TEST(ExitStatusPredicateTest, ExitedWithCode) {
const int status0 = NormalExitStatus(0);
const int status1 = NormalExitStatus(1);
const int status42 = NormalExitStatus(42);
const testing::ExitedWithCode pred0(0);
const testing::ExitedWithCode pred1(1);
const testing::ExitedWithCode pred42(42);
EXPECT_PRED1(pred0, status0);
EXPECT_PRED1(pred1, status1);
EXPECT_PRED1(pred42, status42);
EXPECT_FALSE(pred0(status1));
EXPECT_FALSE(pred42(status0));
EXPECT_FALSE(pred1(status42));
}
// Tests the KilledBySignal predicate.
TEST(ExitStatusPredicateTest, KilledBySignal) {
const int status_segv = KilledExitStatus(SIGSEGV);
const int status_kill = KilledExitStatus(SIGKILL);
const testing::KilledBySignal pred_segv(SIGSEGV);
const testing::KilledBySignal pred_kill(SIGKILL);
EXPECT_PRED1(pred_segv, status_segv);
EXPECT_PRED1(pred_kill, status_kill);
EXPECT_FALSE(pred_segv(status_kill));
EXPECT_FALSE(pred_kill(status_segv));
}
// Tests that the death test macros expand to code which may or may not
// be followed by operator<<, and that in either case the complete text
// comprises only a single C++ statement.
TEST_F(TestForDeathTest, SingleStatement) {
if (false)
// This would fail if executed; this is a compilation test only
ASSERT_DEATH(return, "");
if (true)
EXPECT_DEATH(exit(1), "");
else
// This empty "else" branch is meant to ensure that EXPECT_DEATH
// doesn't expand into an "if" statement without an "else"
;
if (false)
ASSERT_DEATH(return, "") << "did not die";
if (false)
;
else
EXPECT_DEATH(exit(1), "") << 1 << 2 << 3;
}
void DieWithEmbeddedNul() {
fprintf(stderr, "Hello%cworld.\n", '\0');
abort();
}
// Tests that EXPECT_DEATH and ASSERT_DEATH work when the error
// message has a NUL character in it.
TEST_F(TestForDeathTest, DISABLED_EmbeddedNulInMessage) {
// TODO(wan@google.com): <regex.h> doesn't support matching strings
// with embedded NUL characters - find a way to workaround it.
EXPECT_DEATH(DieWithEmbeddedNul(), "w.*ld");
ASSERT_DEATH(DieWithEmbeddedNul(), "w.*ld");
}
// Tests that death test macros expand to code which interacts well with switch
// statements.
TEST_F(TestForDeathTest, SwitchStatement) {
switch (0)
default:
ASSERT_DEATH(exit(1), "") << "exit in default switch handler";
switch (0)
case 0:
EXPECT_DEATH(exit(1), "") << "exit in switch case";
}
// Tests that a static member function can be used in a death test.
TEST_F(TestForDeathTest, StaticMemberFunction) {
ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
}
// Tests that a method of the test fixture can be used in a death test.
TEST_F(TestForDeathTest, MemberFunction) {
should_die_ = true;
EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
}
// Repeats a representative sample of death tests in the "threadsafe" style:
TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
testing::GTEST_FLAG(death_test_style) = "threadsafe";
ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
}
TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
testing::GTEST_FLAG(death_test_style) = "threadsafe";
should_die_ = true;
EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
}
TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {
testing::GTEST_FLAG(death_test_style) = "threadsafe";
for (int i = 0; i < 3; ++i)
EXPECT_EXIT(exit(i), testing::ExitedWithCode(i), "") << ": i = " << i;
}
TEST_F(TestForDeathTest, MixedStyles) {
testing::GTEST_FLAG(death_test_style) = "threadsafe";
EXPECT_DEATH(exit(1), "");
testing::GTEST_FLAG(death_test_style) = "fast";
EXPECT_DEATH(exit(1), "");
}
namespace {
bool pthread_flag;
void SetPthreadFlag() {
pthread_flag = true;
}
} // namespace
TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
testing::GTEST_FLAG(death_test_style) = "threadsafe";
pthread_flag = false;
ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, NULL, NULL));
ASSERT_DEATH(exit(1), "");
ASSERT_FALSE(pthread_flag);
}
// Tests that a method of another class can be used in a death test.
TEST_F(TestForDeathTest, MethodOfAnotherClass) {
const MayDie x(true);
ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction");
}
// Tests that a global function can be used in a death test.
TEST_F(TestForDeathTest, GlobalFunction) {
EXPECT_DEATH(GlobalFunction(), "GlobalFunction");
}
// Tests that any value convertible to an RE works as a second
// argument to EXPECT_DEATH.
TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
static const char regex_c_str[] = "GlobalFunction";
EXPECT_DEATH(GlobalFunction(), regex_c_str);
const testing::internal::RE regex(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex);
#if GTEST_HAS_GLOBAL_STRING
const string regex_str(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex_str);
#endif // GTEST_HAS_GLOBAL_STRING
#if GTEST_HAS_STD_STRING
const ::std::string regex_std_str(regex_c_str);
EXPECT_DEATH(GlobalFunction(), regex_std_str);
#endif // GTEST_HAS_STD_STRING
}
// Tests that a non-void function can be used in a death test.
TEST_F(TestForDeathTest, NonVoidFunction) {
ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction");
}
// Tests that functions that take parameter(s) can be used in a death test.
TEST_F(TestForDeathTest, FunctionWithParameter) {
EXPECT_DEATH(DieIf(true), "DieIf\\(\\)");
EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan");
}
// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
TEST_F(TestForDeathTest, OutsideFixture) {
DeathTestSubroutine();
}
// Tests that death tests can be done inside a loop.
TEST_F(TestForDeathTest, InsideLoop) {
for (int i = 0; i < 5; i++) {
EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i;
}
}
// Tests that a compound statement can be used in a death test.
TEST_F(TestForDeathTest, CompoundStatement) {
EXPECT_DEATH({ // NOLINT
const int x = 2;
const int y = x + 1;
DieIfLessThan(x, y);
},
"DieIfLessThan");
}
// Tests that code that doesn't die causes a death test to fail.
TEST_F(TestForDeathTest, DoesNotDie) {
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"),
"failed to die");
}
// Tests that a death test fails when the error message isn't expected.
TEST_F(TestForDeathTest, ErrorMessageMismatch) {
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message.";
}, "died but not with expected error");
}
// On exit, *aborted will be true iff the EXPECT_DEATH() statement
// aborted the function.
void ExpectDeathTestHelper(bool* aborted) {
*aborted = true;
EXPECT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
*aborted = false;
}
// Tests that EXPECT_DEATH doesn't abort the test on failure.
TEST_F(TestForDeathTest, EXPECT_DEATH) {
bool aborted = true;
EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted),
"failed to die");
EXPECT_FALSE(aborted);
}
// Tests that ASSERT_DEATH does abort the test on failure.
TEST_F(TestForDeathTest, ASSERT_DEATH) {
static bool aborted;
EXPECT_FATAL_FAILURE({ // NOLINT
aborted = true;
ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
aborted = false;
}, "failed to die");
EXPECT_TRUE(aborted);
}
// Tests that EXPECT_DEATH evaluates the arguments exactly once.
TEST_F(TestForDeathTest, SingleEvaluation) {
int x = 3;
EXPECT_DEATH(DieIf((++x) == 4), "DieIf");
const char* regex = "DieIf";
const char* regex_save = regex;
EXPECT_DEATH(DieIfLessThan(3, 4), regex++);
EXPECT_EQ(regex_save + 1, regex);
}
// Tests that run-away death tests are reported as failures.
TEST_F(TestForDeathTest, Runaway) {
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast<void>(0), "Foo"),
"failed to die.");
EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"),
"illegal return in test statement.");
}
// Tests that EXPECT_DEBUG_DEATH works as expected,
// that is, in debug mode, it:
// 1. Asserts on death.
// 2. Has no side effect.
//
// And in opt mode, it:
// 1. Has side effects but does not assert.
TEST_F(TestForDeathTest, TestExpectDebugDeath) {
int sideeffect = 0;
EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect),
"death.*DieInDebugElse12");
#ifdef NDEBUG
// Checks that the assignment occurs in opt mode (sideeffect).
EXPECT_EQ(12, sideeffect);
#else
// Checks that the assignment does not occur in dbg mode (no sideeffect).
EXPECT_EQ(0, sideeffect);
#endif
}
// Tests that EXPECT_DEBUG_DEATH works as expected,
// that is, in debug mode, it:
// 1. Asserts on death.
// 2. Has no side effect.
//
// And in opt mode, it:
// 1. Has side effects and returns the expected value (12).
TEST_F(TestForDeathTest, TestExpectDebugDeathM) {
int sideeffect = 0;
EXPECT_DEBUG_DEATH({ // NOLINT
// Tests that the return value is 12 in opt mode.
EXPECT_EQ(12, DieInDebugElse12(&sideeffect));
// Tests that the side effect occurrs in opt mode.
EXPECT_EQ(12, sideeffect);
}, "death.*DieInDebugElse12") << "In ExpectDebugDeathM";
#ifdef NDEBUG
// Checks that the assignment occurs in opt mode (sideeffect).
EXPECT_EQ(12, sideeffect);
#else
// Checks that the assignment does not occur in dbg mode (no sideeffect).
EXPECT_EQ(0, sideeffect);
#endif
}
// Tests that ASSERT_DEBUG_DEATH works as expected
// In debug mode:
// 1. Asserts on debug death.
// 2. Has no side effect.
//
// In opt mode:
// 1. Has side effects and returns the expected value (12).
TEST_F(TestForDeathTest, TestAssertDebugDeathM) {
int sideeffect = 0;
ASSERT_DEBUG_DEATH({ // NOLINT
// Tests that the return value is 12 in opt mode.
EXPECT_EQ(12, DieInDebugElse12(&sideeffect));
// Tests that the side effect occurred in opt mode.
EXPECT_EQ(12, sideeffect);
}, "death.*DieInDebugElse12") << "In AssertDebugDeathM";
#ifdef NDEBUG
// Checks that the assignment occurs in opt mode (sideeffect).
EXPECT_EQ(12, sideeffect);
#else
// Checks that the assignment does not occur in dbg mode (no sideeffect).
EXPECT_EQ(0, sideeffect);
#endif
}
#ifndef NDEBUG
void ExpectDebugDeathHelper(bool* aborted) {
*aborted = true;
EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail.";
*aborted = false;
}
// Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
// the function.
TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
bool aborted = true;
EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), "");
EXPECT_FALSE(aborted);
}
void AssertDebugDeathHelper(bool* aborted) {
*aborted = true;
ASSERT_DEBUG_DEATH(return, "") << "This is expected to fail.";
*aborted = false;
}
// Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on
// failure.
TEST_F(TestForDeathTest, AssertDebugDeathAborts) {
static bool aborted;
aborted = false;
EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
EXPECT_TRUE(aborted);
}
#endif // _NDEBUG
// Tests the *_EXIT family of macros, using a variety of predicates.
TEST_F(TestForDeathTest, ExitMacros) {
EXPECT_EXIT(exit(1), testing::ExitedWithCode(1), "");
ASSERT_EXIT(exit(42), testing::ExitedWithCode(42), "");
EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
<< "This failure is expected.";
}, "This failure is expected.");
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_EXIT(exit(0), testing::KilledBySignal(SIGSEGV), "")
<< "This failure is expected, too.";
}, "This failure is expected, too.");
}
TEST_F(TestForDeathTest, InvalidStyle) {
testing::GTEST_FLAG(death_test_style) = "rococo";
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_DEATH(exit(0), "") << "This failure is expected.";
}, "This failure is expected.");
}
// A DeathTestFactory that returns MockDeathTests.
class MockDeathTestFactory : public DeathTestFactory {
public:
MockDeathTestFactory();
virtual bool Create(const char* statement,
const ::testing::internal::RE* regex,
const char* file, int line, DeathTest** test);
// Sets the parameters for subsequent calls to Create.
void SetParameters(bool create, DeathTest::TestRole role,
int status, bool passed);
// Accessors.
int AssumeRoleCalls() const { return assume_role_calls_; }
int WaitCalls() const { return wait_calls_; }
int PassedCalls() const { return passed_args_.size(); }
bool PassedArgument(int n) const { return passed_args_[n]; }
int AbortCalls() const { return abort_args_.size(); }
DeathTest::AbortReason AbortArgument(int n) const {
return abort_args_[n];
}
bool TestDeleted() const { return test_deleted_; }
private:
friend class MockDeathTest;
// If true, Create will return a MockDeathTest; otherwise it returns
// NULL.
bool create_;
// The value a MockDeathTest will return from its AssumeRole method.
DeathTest::TestRole role_;
// The value a MockDeathTest will return from its Wait method.
int status_;
// The value a MockDeathTest will return from its Passed method.
bool passed_;
// Number of times AssumeRole was called.
int assume_role_calls_;
// Number of times Wait was called.
int wait_calls_;
// The arguments to the calls to Passed since the last call to
// SetParameters.
std::vector<bool> passed_args_;
// The arguments to the calls to Abort since the last call to
// SetParameters.
std::vector<DeathTest::AbortReason> abort_args_;
// True if the last MockDeathTest returned by Create has been
// deleted.
bool test_deleted_;
};
// A DeathTest implementation useful in testing. It returns values set
// at its creation from its various inherited DeathTest methods, and
// reports calls to those methods to its parent MockDeathTestFactory
// object.
class MockDeathTest : public DeathTest {
public:
MockDeathTest(MockDeathTestFactory *parent,
TestRole role, int status, bool passed) :
parent_(parent), role_(role), status_(status), passed_(passed) {
}
virtual ~MockDeathTest() {
parent_->test_deleted_ = true;
}
virtual TestRole AssumeRole() {
++parent_->assume_role_calls_;
return role_;
}
virtual int Wait() {
++parent_->wait_calls_;
return status_;
}
virtual bool Passed(bool exit_status_ok) {
parent_->passed_args_.push_back(exit_status_ok);
return passed_;
}
virtual void Abort(AbortReason reason) {
parent_->abort_args_.push_back(reason);
}
private:
MockDeathTestFactory* const parent_;
const TestRole role_;
const int status_;
const bool passed_;
};
// MockDeathTestFactory constructor.
MockDeathTestFactory::MockDeathTestFactory()
: create_(true),
role_(DeathTest::OVERSEE_TEST),
status_(0),
passed_(true),
assume_role_calls_(0),
wait_calls_(0),
passed_args_(),
abort_args_() {
}
// Sets the parameters for subsequent calls to Create.
void MockDeathTestFactory::SetParameters(bool create,
DeathTest::TestRole role,
int status, bool passed) {
create_ = create;
role_ = role;
status_ = status;
passed_ = passed;
assume_role_calls_ = 0;
wait_calls_ = 0;
passed_args_.clear();
abort_args_.clear();
}
// Sets test to NULL (if create_ is false) or to the address of a new
// MockDeathTest object with parameters taken from the last call
// to SetParameters (if create_ is true). Always returns true.
bool MockDeathTestFactory::Create(const char* statement,
const ::testing::internal::RE* regex,
const char* file, int line,
DeathTest** test) {
test_deleted_ = false;
if (create_) {
*test = new MockDeathTest(this, role_, status_, passed_);
} else {
*test = NULL;
}
return true;
}
// A test fixture for testing the logic of the GTEST_DEATH_TEST macro.
// It installs a MockDeathTestFactory that is used for the duration
// of the test case.
class MacroLogicDeathTest : public testing::Test {
protected:
static testing::internal::ReplaceDeathTestFactory* replacer_;
static MockDeathTestFactory* factory_;
static void SetUpTestCase() {
factory_ = new MockDeathTestFactory;
replacer_ = new testing::internal::ReplaceDeathTestFactory(
testing::UnitTest::GetInstance(), factory_);
}
static void TearDownTestCase() {
delete replacer_;
replacer_ = NULL;
delete factory_;
factory_ = NULL;
}
// Runs a death test that breaks the rules by returning. Such a death
// test cannot be run directly from a test routine that uses a
// MockDeathTest, or the remainder of the routine will not be executed.
static void RunReturningDeathTest(bool* flag) {
ASSERT_DEATH({ // NOLINT
*flag = true;
return;
}, "");
}
};
testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_
= NULL;
MockDeathTestFactory* MacroLogicDeathTest::factory_ = NULL;
// Test that nothing happens when the factory doesn't return a DeathTest:
TEST_F(MacroLogicDeathTest, NothingHappens) {
bool flag = false;
factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true);
EXPECT_DEATH(flag = true, "");
EXPECT_FALSE(flag);
EXPECT_EQ(0, factory_->AssumeRoleCalls());
EXPECT_EQ(0, factory_->WaitCalls());
EXPECT_EQ(0, factory_->PassedCalls());
EXPECT_EQ(0, factory_->AbortCalls());
EXPECT_FALSE(factory_->TestDeleted());
}
// Test that the parent process doesn't run the death test code,
// and that the Passed method returns false when the (simulated)
// child process exits with status 0:
TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {
bool flag = false;
factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true);
EXPECT_DEATH(flag = true, "");
EXPECT_FALSE(flag);
EXPECT_EQ(1, factory_->AssumeRoleCalls());
EXPECT_EQ(1, factory_->WaitCalls());
ASSERT_EQ(1, factory_->PassedCalls());
EXPECT_FALSE(factory_->PassedArgument(0));
EXPECT_EQ(0, factory_->AbortCalls());
EXPECT_TRUE(factory_->TestDeleted());
}
// Tests that the Passed method was given the argument "true" when
// the (simulated) child process exits with status 1:
TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {
bool flag = false;
factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true);
EXPECT_DEATH(flag = true, "");
EXPECT_FALSE(flag);
EXPECT_EQ(1, factory_->AssumeRoleCalls());
EXPECT_EQ(1, factory_->WaitCalls());
ASSERT_EQ(1, factory_->PassedCalls());
EXPECT_TRUE(factory_->PassedArgument(0));
EXPECT_EQ(0, factory_->AbortCalls());
EXPECT_TRUE(factory_->TestDeleted());
}
// Tests that the (simulated) child process executes the death test
// code, and is aborted with the correct AbortReason if it
// executes a return statement.
TEST_F(MacroLogicDeathTest, ChildPerformsReturn) {
bool flag = false;
factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
RunReturningDeathTest(&flag);
EXPECT_TRUE(flag);
EXPECT_EQ(1, factory_->AssumeRoleCalls());
EXPECT_EQ(0, factory_->WaitCalls());
EXPECT_EQ(0, factory_->PassedCalls());
EXPECT_EQ(1, factory_->AbortCalls());
EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
factory_->AbortArgument(0));
EXPECT_TRUE(factory_->TestDeleted());
}
// Tests that the (simulated) child process is aborted with the
// correct AbortReason if it does not die.
TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
bool flag = false;
factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
EXPECT_DEATH(flag = true, "");
EXPECT_TRUE(flag);
EXPECT_EQ(1, factory_->AssumeRoleCalls());
EXPECT_EQ(0, factory_->WaitCalls());
EXPECT_EQ(0, factory_->PassedCalls());
// This time there are two calls to Abort: one since the test didn't
// die, and another from the ReturnSentinel when it's destroyed. The
// sentinel normally isn't destroyed if a test doesn't die, since
// exit(2) is called in that case by ForkingDeathTest, but not by
// our MockDeathTest.
ASSERT_EQ(2, factory_->AbortCalls());
EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
factory_->AbortArgument(0));
EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
factory_->AbortArgument(1));
EXPECT_TRUE(factory_->TestDeleted());
}
// Returns the number of successful parts in the current test.
static size_t GetSuccessfulTestPartCount() {
return testing::UnitTest::GetInstance()->impl()->current_test_result()->
successful_part_count();
}
// Tests that a successful death test does not register a successful
// test part.
TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
EXPECT_DEATH(exit(1), "");
EXPECT_EQ(0u, GetSuccessfulTestPartCount());
}
TEST(StreamingAssertionsDeathTest, DeathTest) {
EXPECT_DEATH(exit(1), "") << "unexpected failure";
ASSERT_DEATH(exit(1), "") << "unexpected failure";
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_DEATH(exit(0), "") << "expected failure";
}, "expected failure");
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_DEATH(exit(0), "") << "expected failure";
}, "expected failure");
}
#endif // GTEST_HAS_DEATH_TEST
// Tests that a test case whose name ends with "DeathTest" works fine
// on Windows.
TEST(NotADeathTest, Test) {
SUCCEED();
}

369
test/gtest-filepath_test.cc Normal file
View File

@ -0,0 +1,369 @@
// 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)
//
// Google Test filepath utilities
//
// This file tests classes and functions used internally by
// Google Test. They are subject to change without notice.
//
// This file is #included from gtest_unittest.cc, to avoid changing
// build or make-files for some existing Google Test clients. Do not
// #include this file anywhere else!
#include <gtest/internal/gtest-filepath.h>
#include <gtest/gtest.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 "src/gtest-internal-inl.h"
#undef GTEST_IMPLEMENTATION
#ifdef GTEST_OS_WINDOWS
#include <direct.h>
#define PATH_SEP "\\"
#else
#define PATH_SEP "/"
#endif // GTEST_OS_WINDOWS
namespace testing {
namespace internal {
namespace {
// FilePath's functions used by UnitTestOptions::GetOutputFile.
// RemoveDirectoryName "" -> ""
TEST(RemoveDirectoryNameTest, WhenEmptyName) {
EXPECT_STREQ("", FilePath("").RemoveDirectoryName().c_str());
}
// RemoveDirectoryName "afile" -> "afile"
TEST(RemoveDirectoryNameTest, ButNoDirectory) {
EXPECT_STREQ("afile",
FilePath("afile").RemoveDirectoryName().c_str());
}
// RemoveDirectoryName "/afile" -> "afile"
TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) {
EXPECT_STREQ("afile",
FilePath(PATH_SEP "afile").RemoveDirectoryName().c_str());
}
// RemoveDirectoryName "adir/" -> ""
TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) {
EXPECT_STREQ("",
FilePath("adir" PATH_SEP).RemoveDirectoryName().c_str());
}
// RemoveDirectoryName "adir/afile" -> "afile"
TEST(RemoveDirectoryNameTest, ShouldGiveFileName) {
EXPECT_STREQ("afile",
FilePath("adir" PATH_SEP "afile").RemoveDirectoryName().c_str());
}
// RemoveDirectoryName "adir/subdir/afile" -> "afile"
TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) {
EXPECT_STREQ("afile",
FilePath("adir" PATH_SEP "subdir" PATH_SEP "afile")
.RemoveDirectoryName().c_str());
}
// RemoveFileName "" -> "./"
TEST(RemoveFileNameTest, EmptyName) {
EXPECT_STREQ("." PATH_SEP,
FilePath("").RemoveFileName().c_str());
}
// RemoveFileName "adir/" -> "adir/"
TEST(RemoveFileNameTest, ButNoFile) {
EXPECT_STREQ("adir" PATH_SEP,
FilePath("adir" PATH_SEP).RemoveFileName().c_str());
}
// RemoveFileName "adir/afile" -> "adir/"
TEST(RemoveFileNameTest, GivesDirName) {
EXPECT_STREQ("adir" PATH_SEP,
FilePath("adir" PATH_SEP "afile")
.RemoveFileName().c_str());
}
// RemoveFileName "adir/subdir/afile" -> "adir/subdir/"
TEST(RemoveFileNameTest, GivesDirAndSubDirName) {
EXPECT_STREQ("adir" PATH_SEP "subdir" PATH_SEP,
FilePath("adir" PATH_SEP "subdir" PATH_SEP "afile")
.RemoveFileName().c_str());
}
// RemoveFileName "/afile" -> "/"
TEST(RemoveFileNameTest, GivesRootDir) {
EXPECT_STREQ(PATH_SEP,
FilePath(PATH_SEP "afile").RemoveFileName().c_str());
}
TEST(MakeFileNameTest, GenerateWhenNumberIsZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"),
0, "xml");
EXPECT_STREQ("foo" PATH_SEP "bar.xml", actual.c_str());
}
TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"),
12, "xml");
EXPECT_STREQ("foo" PATH_SEP "bar_12.xml", actual.c_str());
}
TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo" PATH_SEP),
FilePath("bar"), 0, "xml");
EXPECT_STREQ("foo" PATH_SEP "bar.xml", actual.c_str());
}
TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) {
FilePath actual = FilePath::MakeFileName(FilePath("foo" PATH_SEP),
FilePath("bar"), 12, "xml");
EXPECT_STREQ("foo" PATH_SEP "bar_12.xml", actual.c_str());
}
// RemoveTrailingPathSeparator "" -> ""
TEST(RemoveTrailingPathSeparatorTest, EmptyString) {
EXPECT_STREQ("",
FilePath("").RemoveTrailingPathSeparator().c_str());
}
// RemoveTrailingPathSeparator "foo" -> "foo"
TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) {
EXPECT_STREQ("foo",
FilePath("foo").RemoveTrailingPathSeparator().c_str());
}
// RemoveTrailingPathSeparator "foo/" -> "foo"
TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) {
EXPECT_STREQ("foo",
FilePath("foo" PATH_SEP).RemoveTrailingPathSeparator().c_str());
}
// RemoveTrailingPathSeparator "foo/bar/" -> "foo/bar/"
TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) {
EXPECT_STREQ("foo" PATH_SEP "bar",
FilePath("foo" PATH_SEP "bar" PATH_SEP).RemoveTrailingPathSeparator()
.c_str());
}
// RemoveTrailingPathSeparator "foo/bar" -> "foo/bar"
TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) {
EXPECT_STREQ("foo" PATH_SEP "bar",
FilePath("foo" PATH_SEP "bar").RemoveTrailingPathSeparator().c_str());
}
class DirectoryCreationTest : public Test {
protected:
virtual void SetUp() {
testdata_path_.Set(FilePath(String::Format("%s%s%s",
TempDir().c_str(), GetCurrentExecutableName().c_str(),
"_directory_creation" PATH_SEP "test" PATH_SEP)));
testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator());
unique_file0_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"),
0, "txt"));
unique_file1_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"),
1, "txt"));
remove(testdata_file_.c_str());
remove(unique_file0_.c_str());
remove(unique_file1_.c_str());
#ifdef GTEST_OS_WINDOWS
_rmdir(testdata_path_.c_str());
#else
rmdir(testdata_path_.c_str());
#endif // GTEST_OS_WINDOWS
}
virtual void TearDown() {
remove(testdata_file_.c_str());
remove(unique_file0_.c_str());
remove(unique_file1_.c_str());
#ifdef GTEST_OS_WINDOWS
_rmdir(testdata_path_.c_str());
#else
rmdir(testdata_path_.c_str());
#endif // GTEST_OS_WINDOWS
}
String TempDir() const {
#ifdef _WIN32_WCE
return String("\\temp\\");
#elif defined(GTEST_OS_WINDOWS)
// MSVC 8 deprecates getenv(), so we want to suppress warning 4996
// (deprecated function) there.
#pragma warning(push) // Saves the current warning state.
#pragma warning(disable:4996) // Temporarily disables warning 4996.
const char* temp_dir = getenv("TEMP");
#pragma warning(pop) // Restores the warning state.
if (temp_dir == NULL || temp_dir[0] == '\0')
return String("\\temp\\");
else if (String(temp_dir).EndsWith("\\"))
return String(temp_dir);
else
return String::Format("%s\\", temp_dir);
#else
return String("/tmp/");
#endif
}
void CreateTextFile(const char* filename) {
#ifdef GTEST_OS_WINDOWS
// MSVC 8 deprecates fopen(), so we want to suppress warning 4996
// (deprecated function) there.#pragma warning(push)
#pragma warning(push) // Saves the current warning state.
#pragma warning(disable:4996) // Temporarily disables warning 4996.
FILE* f = fopen(filename, "w");
#pragma warning(pop) // Restores the warning state.
#else // We are on Linux or Mac OS.
FILE* f = fopen(filename, "w");
#endif // GTEST_OS_WINDOWS
fprintf(f, "text\n");
fclose(f);
}
// Strings representing a directory and a file, with identical paths
// except for the trailing separator character that distinquishes
// a directory named 'test' from a file named 'test'. Example names:
FilePath testdata_path_; // "/tmp/directory_creation/test/"
FilePath testdata_file_; // "/tmp/directory_creation/test"
FilePath unique_file0_; // "/tmp/directory_creation/test/unique.txt"
FilePath unique_file1_; // "/tmp/directory_creation/test/unique_1.txt"
};
TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) {
EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.c_str();
EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());
EXPECT_TRUE(testdata_path_.DirectoryExists());
}
TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) {
EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.c_str();
EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());
// Call 'create' again... should still succeed.
EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());
}
TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {
FilePath file_path(FilePath::GenerateUniqueFileName(testdata_path_,
FilePath("unique"), "txt"));
EXPECT_STREQ(unique_file0_.c_str(), file_path.c_str());
EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file not there
testdata_path_.CreateDirectoriesRecursively();
EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file still not there
CreateTextFile(file_path.c_str());
EXPECT_TRUE(file_path.FileOrDirectoryExists());
FilePath file_path2(FilePath::GenerateUniqueFileName(testdata_path_,
FilePath("unique"), "txt"));
EXPECT_STREQ(unique_file1_.c_str(), file_path2.c_str());
EXPECT_FALSE(file_path2.FileOrDirectoryExists()); // file not there
CreateTextFile(file_path2.c_str());
EXPECT_TRUE(file_path2.FileOrDirectoryExists());
}
TEST_F(DirectoryCreationTest, CreateDirectoriesFail) {
// force a failure by putting a file where we will try to create a directory.
CreateTextFile(testdata_file_.c_str());
EXPECT_TRUE(testdata_file_.FileOrDirectoryExists());
EXPECT_FALSE(testdata_file_.DirectoryExists());
EXPECT_FALSE(testdata_file_.CreateDirectoriesRecursively());
}
TEST(NoDirectoryCreationTest, CreateNoDirectoriesForDefaultXmlFile) {
const FilePath test_detail_xml("test_detail.xml");
EXPECT_FALSE(test_detail_xml.CreateDirectoriesRecursively());
}
TEST(FilePathTest, DefaultConstructor) {
FilePath fp;
EXPECT_STREQ("", fp.c_str());
}
TEST(FilePathTest, CharAndCopyConstructors) {
const FilePath fp("spicy");
EXPECT_STREQ("spicy", fp.c_str());
const FilePath fp_copy(fp);
EXPECT_STREQ("spicy", fp_copy.c_str());
}
TEST(FilePathTest, StringConstructor) {
const FilePath fp(String("cider"));
EXPECT_STREQ("cider", fp.c_str());
}
TEST(FilePathTest, Set) {
const FilePath apple("apple");
FilePath mac("mac");
mac.Set(apple); // Implement Set() since overloading operator= is forbidden.
EXPECT_STREQ("apple", mac.c_str());
EXPECT_STREQ("apple", apple.c_str());
}
TEST(FilePathTest, ToString) {
const FilePath file("drink");
String str(file.ToString());
EXPECT_STREQ("drink", str.c_str());
}
TEST(FilePathTest, RemoveExtension) {
EXPECT_STREQ("app", FilePath("app.exe").RemoveExtension("exe").c_str());
EXPECT_STREQ("APP", FilePath("APP.EXE").RemoveExtension("exe").c_str());
}
TEST(FilePathTest, RemoveExtensionWhenThereIsNoExtension) {
EXPECT_STREQ("app", FilePath("app").RemoveExtension("exe").c_str());
}
TEST(FilePathTest, IsDirectory) {
EXPECT_FALSE(FilePath("cola").IsDirectory());
EXPECT_TRUE(FilePath("koala" PATH_SEP).IsDirectory());
}
} // namespace
} // namespace internal
} // namespace testing
#undef PATH_SEP

157
test/gtest-message_test.cc Normal file
View File

@ -0,0 +1,157 @@
// 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)
//
// Tests for the Message class.
#include <gtest/gtest-message.h>
#include <gtest/gtest.h>
namespace {
using ::testing::Message;
using ::testing::internal::StrStream;
// A helper function that turns a Message into a C string.
const char* ToCString(const Message& msg) {
static testing::internal::String result;
result = msg.GetString();
return result.c_str();
}
// Tests the testing::Message class
// Tests the default constructor.
TEST(MessageTest, DefaultConstructor) {
const Message msg;
EXPECT_STREQ("", ToCString(msg));
}
// Tests the copy constructor.
TEST(MessageTest, CopyConstructor) {
const Message msg1("Hello");
const Message msg2(msg1);
EXPECT_STREQ("Hello", ToCString(msg2));
}
// Tests constructing a Message from a C-string.
TEST(MessageTest, ConstructsFromCString) {
Message msg("Hello");
EXPECT_STREQ("Hello", ToCString(msg));
}
// Tests streaming a non-char pointer.
TEST(MessageTest, StreamsPointer) {
int n = 0;
int* p = &n;
EXPECT_STRNE("(null)", ToCString(Message() << p));
}
// Tests streaming a NULL non-char pointer.
TEST(MessageTest, StreamsNullPointer) {
int* p = NULL;
EXPECT_STREQ("(null)", ToCString(Message() << p));
}
// Tests streaming a C string.
TEST(MessageTest, StreamsCString) {
EXPECT_STREQ("Foo", ToCString(Message() << "Foo"));
}
// Tests streaming a NULL C string.
TEST(MessageTest, StreamsNullCString) {
char* p = NULL;
EXPECT_STREQ("(null)", ToCString(Message() << p));
}
#if GTEST_HAS_STD_STRING
// Tests streaming std::string.
//
// As std::string has problem in MSVC when exception is disabled, we only
// test this where std::string can be used.
TEST(MessageTest, StreamsString) {
const ::std::string str("Hello");
EXPECT_STREQ("Hello", ToCString(Message() << str));
}
// Tests that we can output strings containing embedded NULs.
TEST(MessageTest, StreamsStringWithEmbeddedNUL) {
const char char_array_with_nul[] =
"Here's a NUL\0 and some more string";
const ::std::string string_with_nul(char_array_with_nul,
sizeof(char_array_with_nul) - 1);
EXPECT_STREQ("Here's a NUL\\0 and some more string",
ToCString(Message() << string_with_nul));
}
#endif // GTEST_HAS_STD_STRING
// Tests streaming a NUL char.
TEST(MessageTest, StreamsNULChar) {
EXPECT_STREQ("\\0", ToCString(Message() << '\0'));
}
// Tests streaming int.
TEST(MessageTest, StreamsInt) {
EXPECT_STREQ("123", ToCString(Message() << 123));
}
// Tests that basic IO manipulators (endl, ends, and flush) can be
// streamed to Message.
TEST(MessageTest, StreamsBasicIoManip) {
EXPECT_STREQ("Line 1.\nA NUL char \\0 in line 2.",
ToCString(Message() << "Line 1." << std::endl
<< "A NUL char " << std::ends << std::flush
<< " in line 2."));
}
// Tests Message::GetString()
TEST(MessageTest, GetString) {
Message msg;
msg << 1 << " lamb";
EXPECT_STREQ("1 lamb", msg.GetString().c_str());
}
// Tests streaming a Message object to an ostream.
TEST(MessageTest, StreamsToOStream) {
Message msg("Hello");
StrStream ss;
ss << msg;
EXPECT_STREQ("Hello", testing::internal::StrStreamToString(&ss).c_str());
}
// Tests that a Message object doesn't take up too much stack space.
TEST(MessageTest, DoesNotTakeUpMuchStackSpace) {
EXPECT_LE(sizeof(Message), 16U);
}
} // namespace

122
test/gtest-options_test.cc Normal file
View File

@ -0,0 +1,122 @@
// 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)
//
// Google Test UnitTestOptions tests
//
// This file tests classes and functions used internally by
// Google Test. They are subject to change without notice.
//
// This file is #included from gtest.cc, to avoid changing build or
// make-files on Windows and other platforms. Do not #include this file
// anywhere else!
#include <gtest/gtest.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 "src/gtest-internal-inl.h"
#undef GTEST_IMPLEMENTATION
namespace testing {
namespace internal {
namespace {
// Testing UnitTestOptions::GetOutputFormat/GetOutputFile.
TEST(XmlOutputTest, GetOutputFormatDefault) {
GTEST_FLAG(output) = "";
EXPECT_STREQ("", UnitTestOptions::GetOutputFormat().c_str());
}
TEST(XmlOutputTest, GetOutputFormat) {
GTEST_FLAG(output) = "xml:filename";
EXPECT_STREQ("xml", UnitTestOptions::GetOutputFormat().c_str());
}
TEST(XmlOutputTest, GetOutputFileDefault) {
GTEST_FLAG(output) = "";
EXPECT_STREQ("test_detail.xml",
UnitTestOptions::GetOutputFile().c_str());
}
TEST(XmlOutputTest, GetOutputFileSingleFile) {
GTEST_FLAG(output) = "xml:filename.abc";
EXPECT_STREQ("filename.abc",
UnitTestOptions::GetOutputFile().c_str());
}
TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) {
#ifdef GTEST_OS_WINDOWS
GTEST_FLAG(output) = "xml:pathname\\";
const String& output_file = UnitTestOptions::GetOutputFile();
EXPECT_TRUE(_strcmpi(output_file.c_str(),
"pathname\\gtest-options_test.xml") == 0 ||
_strcmpi(output_file.c_str(),
"pathname\\gtest-options-ex_test.xml") == 0)
<< " output_file = " << output_file;
#else
GTEST_FLAG(output) = "xml:pathname/";
const String& output_file = UnitTestOptions::GetOutputFile();
// TODO(wan@google.com): libtool causes the test binary file to be
// named lt-gtest-options_test. Therefore the output file may be
// named .../lt-gtest-options_test.xml. We should remove this
// hard-coded logic when Chandler Carruth's libtool replacement is
// ready.
EXPECT_TRUE(output_file == "pathname/gtest-options_test.xml" ||
output_file == "pathname/lt-gtest-options_test.xml")
<< " output_file = " << output_file;
#endif
}
TEST(OutputFileHelpersTest, GetCurrentExecutableName) {
const FilePath executable = GetCurrentExecutableName();
const char* const exe_str = executable.c_str();
#if defined(_WIN32_WCE) || defined(GTEST_OS_WINDOWS)
ASSERT_TRUE(_strcmpi("gtest-options_test", exe_str) == 0 ||
_strcmpi("gtest-options-ex_test", exe_str) == 0)
<< "GetCurrentExecutableName() returns " << exe_str;
#else
// TODO(wan@google.com): remove the hard-coded "lt-" prefix when
// Chandler Carruth's libtool replacement is ready.
EXPECT_TRUE(String(exe_str) == "gtest-options_test" ||
String(exe_str) == "lt-gtest-options_test")
<< "GetCurrentExecutableName() returns " << exe_str;
#endif
}
} // namespace
} // namespace internal
} // namespace testing

View File

@ -0,0 +1,178 @@
#!/usr/bin/env python
#
# 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.
"""Unit test for Google Test's break-on-failure mode.
A user can ask Google Test to seg-fault when an assertion fails, using
either the GTEST_BREAK_ON_FAILURE environment variable or the
--gtest_break_on_failure flag. This script tests such functionality
by invoking gtest_break_on_failure_unittest_ (a program written with
Google Test) with different environments and command line flags.
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import gtest_test_utils
import os
import signal
import sys
import unittest
# Constants.
# The environment variable for enabling/disabling the break-on-failure mode.
BREAK_ON_FAILURE_ENV_VAR = 'GTEST_BREAK_ON_FAILURE'
# The command line flag for enabling/disabling the break-on-failure mode.
BREAK_ON_FAILURE_FLAG = 'gtest_break_on_failure'
# Path to the gtest_break_on_failure_unittest_ program.
EXE_PATH = os.path.join(gtest_test_utils.GetBuildDir(),
'gtest_break_on_failure_unittest_');
# Utilities.
def SetEnvVar(env_var, value):
"""Sets an environment variable to a given value; unsets it when the
given value is None.
"""
if value is not None:
os.environ[env_var] = value
elif env_var in os.environ:
del os.environ[env_var]
def Run(command):
"""Runs a command; returns 1 if it has a segmentation fault, or 0 otherwise.
"""
return os.system(command) == signal.SIGSEGV
# The unit test.
class GTestBreakOnFailureUnitTest(unittest.TestCase):
"""Tests using the GTEST_BREAK_ON_FAILURE environment variable or
the --gtest_break_on_failure flag to turn assertion failures into
segmentation faults.
"""
def RunAndVerify(self, env_var_value, flag_value, expect_seg_fault):
"""Runs gtest_break_on_failure_unittest_ and verifies that it does
(or does not) have a seg-fault.
Args:
env_var_value: value of the GTEST_BREAK_ON_FAILURE environment
variable; None if the variable should be unset.
flag_value: value of the --gtest_break_on_failure flag;
None if the flag should not be present.
expect_seg_fault: 1 if the program is expected to generate a seg-fault;
0 otherwise.
"""
SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, env_var_value)
if env_var_value is None:
env_var_value_msg = ' is not set'
else:
env_var_value_msg = '=' + env_var_value
if flag_value is None:
flag = ''
elif flag_value == '0':
flag = ' --%s=0' % BREAK_ON_FAILURE_FLAG
else:
flag = ' --%s' % BREAK_ON_FAILURE_FLAG
command = EXE_PATH + flag
if expect_seg_fault:
should_or_not = 'should'
else:
should_or_not = 'should not'
has_seg_fault = Run(command)
SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, None)
msg = ('when %s%s, an assertion failure in "%s" %s cause a seg-fault.' %
(BREAK_ON_FAILURE_ENV_VAR, env_var_value_msg, command, should_or_not))
self.assert_(has_seg_fault == expect_seg_fault, msg)
def testDefaultBehavior(self):
"""Tests the behavior of the default mode."""
self.RunAndVerify(env_var_value=None,
flag_value=None,
expect_seg_fault=0)
def testEnvVar(self):
"""Tests using the GTEST_BREAK_ON_FAILURE environment variable."""
self.RunAndVerify(env_var_value='0',
flag_value=None,
expect_seg_fault=0)
self.RunAndVerify(env_var_value='1',
flag_value=None,
expect_seg_fault=1)
def testFlag(self):
"""Tests using the --gtest_break_on_failure flag."""
self.RunAndVerify(env_var_value=None,
flag_value='0',
expect_seg_fault=0)
self.RunAndVerify(env_var_value=None,
flag_value='1',
expect_seg_fault=1)
def testFlagOverridesEnvVar(self):
"""Tests that the flag overrides the environment variable."""
self.RunAndVerify(env_var_value='0',
flag_value='0',
expect_seg_fault=0)
self.RunAndVerify(env_var_value='0',
flag_value='1',
expect_seg_fault=1)
self.RunAndVerify(env_var_value='1',
flag_value='0',
expect_seg_fault=0)
self.RunAndVerify(env_var_value='1',
flag_value='1',
expect_seg_fault=1)
if __name__ == '__main__':
gtest_test_utils.Main()

View File

@ -0,0 +1,59 @@
// 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.
//
// Author: wan@google.com (Zhanyong Wan)
// Unit test for Google Test's break-on-failure mode.
//
// A user can ask Google Test to seg-fault when an assertion fails, using
// either the GTEST_BREAK_ON_FAILURE environment variable or the
// --gtest_break_on_failure flag. This file is used for testing such
// functionality.
//
// This program will be invoked from a Python unit test. It is
// expected to fail. Don't run it directly.
#include <gtest/gtest.h>
namespace {
// A test that's expected to fail.
TEST(Foo, Bar) {
EXPECT_EQ(2, 3);
}
} // namespace
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

123
test/gtest_color_test.py Executable file
View File

@ -0,0 +1,123 @@
#!/usr/bin/env python
#
# 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.
"""Verifies that Google Test correctly determines whether to use colors."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import gtest_test_utils
import os
import sys
import unittest
COLOR_ENV_VAR = 'GTEST_COLOR'
COLOR_FLAG = 'gtest_color'
COMMAND = os.path.join(gtest_test_utils.GetBuildDir(),
'gtest_color_test_')
def SetEnvVar(env_var, value):
"""Sets the env variable to 'value'; unsets it when 'value' is None."""
if value is not None:
os.environ[env_var] = value
elif env_var in os.environ:
del os.environ[env_var]
def UsesColor(term, color_env_var, color_flag):
"""Runs gtest_color_test_ and returns its exit code."""
SetEnvVar('TERM', term)
SetEnvVar(COLOR_ENV_VAR, color_env_var)
cmd = COMMAND
if color_flag is not None:
cmd += ' --%s=%s' % (COLOR_FLAG, color_flag)
return os.system(cmd)
class GTestColorTest(unittest.TestCase):
def testNoEnvVarNoFlag(self):
"""Tests the case when there's neither GTEST_COLOR nor --gtest_color."""
self.assert_(not UsesColor('dumb', None, None))
self.assert_(not UsesColor('emacs', None, None))
self.assert_(not UsesColor('xterm-mono', None, None))
self.assert_(not UsesColor('unknown', None, None))
self.assert_(not UsesColor(None, None, None))
self.assert_(UsesColor('cygwin', None, None))
self.assert_(UsesColor('xterm', None, None))
self.assert_(UsesColor('xterm-color', None, None))
def testFlagOnly(self):
"""Tests the case when there's --gtest_color but not GTEST_COLOR."""
self.assert_(not UsesColor('dumb', None, 'no'))
self.assert_(not UsesColor('xterm-color', None, 'no'))
self.assert_(not UsesColor('emacs', None, 'auto'))
self.assert_(UsesColor('xterm', None, 'auto'))
self.assert_(UsesColor('dumb', None, 'yes'))
self.assert_(UsesColor('xterm', None, 'yes'))
def testEnvVarOnly(self):
"""Tests the case when there's GTEST_COLOR but not --gtest_color."""
self.assert_(not UsesColor('dumb', 'no', None))
self.assert_(not UsesColor('xterm-color', 'no', None))
self.assert_(not UsesColor('dumb', 'auto', None))
self.assert_(UsesColor('xterm-color', 'auto', None))
self.assert_(UsesColor('dumb', 'yes', None))
self.assert_(UsesColor('xterm-color', 'yes', None))
def testEnvVarAndFlag(self):
"""Tests the case when there are both GTEST_COLOR and --gtest_color."""
self.assert_(not UsesColor('xterm-color', 'no', 'no'))
self.assert_(UsesColor('dumb', 'no', 'yes'))
self.assert_(UsesColor('xterm-color', 'no', 'auto'))
def testAliasesOfYesAndNo(self):
"""Tests using aliases in specifying --gtest_color."""
self.assert_(UsesColor('dumb', None, 'true'))
self.assert_(UsesColor('dumb', None, 'YES'))
self.assert_(UsesColor('dumb', None, 'T'))
self.assert_(UsesColor('dumb', None, '1'))
self.assert_(not UsesColor('xterm', None, 'f'))
self.assert_(not UsesColor('xterm', None, 'false'))
self.assert_(not UsesColor('xterm', None, '0'))
self.assert_(not UsesColor('xterm', None, 'unknown'))
if __name__ == '__main__':
gtest_test_utils.Main()

68
test/gtest_color_test_.cc Normal file
View File

@ -0,0 +1,68 @@
// 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.
//
// Author: wan@google.com (Zhanyong Wan)
// A helper program for testing how Google Test determines whether to use
// colors in the output. It prints "YES" and returns 1 if Google Test
// decides to use colors, and prints "NO" and returns 0 otherwise.
#include <stdio.h>
#include <gtest/gtest.h>
namespace testing {
namespace internal {
bool ShouldUseColor(bool stdout_is_tty);
} // namespace internal
} // namespace testing
using testing::internal::ShouldUseColor;
// The purpose of this is to ensure that the UnitTest singleton is
// created before main() is entered, and thus that ShouldUseColor()
// works the same way as in a real Google-Test-based test. We don't actual
// run the TEST itself.
TEST(GTestColorTest, Dummy) {
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
if (ShouldUseColor(true)) {
// Google Test decides to use colors in the output (assuming it
// goes to a TTY).
printf("YES\n");
return 1;
} else {
// Google Test decides not to use colors in the output.
printf("NO\n");
return 0;
}
}

134
test/gtest_env_var_test.py Executable file
View File

@ -0,0 +1,134 @@
#!/usr/bin/env python
#
# 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.
"""Verifies that Google Test correctly parses environment variables."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import gtest_test_utils
import os
import sys
import unittest
IS_WINDOWS = os.name == 'nt'
IS_LINUX = os.name == 'posix'
if IS_WINDOWS:
BUILD_DIRS = [
'build.dbg\\',
'build.opt\\',
'build.dbg8\\',
'build.opt8\\',
]
COMMAND = 'gtest_env_var_test_.exe'
if IS_LINUX:
COMMAND = os.path.join(gtest_test_utils.GetBuildDir(),
'gtest_env_var_test_')
def AssertEq(expected, actual):
if expected != actual:
print 'Expected: %s' % (expected,)
print ' Actual: %s' % (actual,)
raise AssertionError
def SetEnvVar(env_var, value):
"""Sets the env variable to 'value'; unsets it when 'value' is None."""
if value is not None:
os.environ[env_var] = value
elif env_var in os.environ:
del os.environ[env_var]
def GetFlag(command, flag):
"""Runs gtest_env_var_test_ and returns its output."""
cmd = command
if flag is not None:
cmd += ' %s' % (flag,)
stdin, stdout = os.popen2(cmd, 'b')
stdin.close()
line = stdout.readline()
stdout.close()
return line
def TestFlag(command, flag, test_val, default_val):
"""Verifies that the given flag is affected by the corresponding env var."""
env_var = 'GTEST_' + flag.upper()
SetEnvVar(env_var, test_val)
AssertEq(test_val, GetFlag(command, flag))
SetEnvVar(env_var, None)
AssertEq(default_val, GetFlag(command, flag))
def TestEnvVarAffectsFlag(command):
"""An environment variable should affect the corresponding flag."""
TestFlag(command, 'break_on_failure', '1', '0')
TestFlag(command, 'color', 'yes', 'auto')
TestFlag(command, 'filter', 'FooTest.Bar', '*')
TestFlag(command, 'output', 'tmp/foo.xml', '')
TestFlag(command, 'repeat', '999', '1')
if IS_WINDOWS:
TestFlag(command, 'catch_exceptions', '1', '0')
if IS_LINUX:
TestFlag(command, 'stack_trace_depth', '0', '100')
TestFlag(command, 'death_test_style', 'thread-safe', 'fast')
if IS_WINDOWS:
def main():
for build_dir in BUILD_DIRS:
command = build_dir + COMMAND
print 'Testing with %s . . .' % (command,)
TestEnvVarAffectsFlag(command)
return 0
if __name__ == '__main__':
main()
if IS_LINUX:
class GTestEnvVarTest(unittest.TestCase):
def testEnvVarAffectsFlag(self):
TestEnvVarAffectsFlag(COMMAND)
if __name__ == '__main__':
gtest_test_utils.Main()

111
test/gtest_env_var_test_.cc Normal file
View File

@ -0,0 +1,111 @@
// 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.
//
// Author: wan@google.com (Zhanyong Wan)
// A helper program for testing that Google Test parses the environment
// variables correctly.
#include <gtest/gtest.h>
#include <iostream>
#define GTEST_IMPLEMENTATION
#include "src/gtest-internal-inl.h"
#undef GTEST_IMPLEMENTATION
using ::std::cout;
namespace testing {
// The purpose of this is to make the test more realistic by ensuring
// that the UnitTest singleton is created before main() is entered.
// We don't actual run the TEST itself.
TEST(GTestEnvVarTest, Dummy) {
}
void PrintFlag(const char* flag) {
if (strcmp(flag, "break_on_failure") == 0) {
cout << GTEST_FLAG(break_on_failure);
return;
}
if (strcmp(flag, "catch_exceptions") == 0) {
cout << GTEST_FLAG(catch_exceptions);
return;
}
if (strcmp(flag, "color") == 0) {
cout << GTEST_FLAG(color);
return;
}
if (strcmp(flag, "death_test_style") == 0) {
cout << GTEST_FLAG(death_test_style);
return;
}
if (strcmp(flag, "filter") == 0) {
cout << GTEST_FLAG(filter);
return;
}
if (strcmp(flag, "output") == 0) {
cout << GTEST_FLAG(output);
return;
}
if (strcmp(flag, "repeat") == 0) {
cout << GTEST_FLAG(repeat);
return;
}
if (strcmp(flag, "stack_trace_depth") == 0) {
cout << GTEST_FLAG(stack_trace_depth);
return;
}
cout << "Invalid flag name " << flag
<< ". Valid names are break_on_failure, color, filter, etc.\n";
exit(1);
}
} // namespace testing
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
if (argc != 2) {
cout << "Usage: gtest_env_var_test_ NAME_OF_FLAG\n";
return 1;
}
testing::PrintFlag(argv[1]);
return 0;
}

View File

@ -0,0 +1,186 @@
// Copyright 2007, 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)
//
// Tests using global test environments.
#include <stdlib.h>
#include <stdio.h>
#include <gtest/gtest.h>
namespace testing {
GTEST_DECLARE_string(filter);
}
namespace {
enum FailureType {
NO_FAILURE, NON_FATAL_FAILURE, FATAL_FAILURE
};
// For testing using global test environments.
class MyEnvironment : public testing::Environment {
public:
MyEnvironment() { Reset(); }
// Depending on the value of failure_in_set_up_, SetUp() will
// generate a non-fatal failure, generate a fatal failure, or
// succeed.
virtual void SetUp() {
set_up_was_run_ = true;
switch (failure_in_set_up_) {
case NON_FATAL_FAILURE:
ADD_FAILURE() << "Expected non-fatal failure in global set-up.";
break;
case FATAL_FAILURE:
FAIL() << "Expected fatal failure in global set-up.";
break;
default:
break;
}
}
// Generates a non-fatal failure.
virtual void TearDown() {
tear_down_was_run_ = true;
ADD_FAILURE() << "Expected non-fatal failure in global tear-down.";
}
// Resets the state of the environment s.t. it can be reused.
void Reset() {
failure_in_set_up_ = NO_FAILURE;
set_up_was_run_ = false;
tear_down_was_run_ = false;
}
// We call this function to set the type of failure SetUp() should
// generate.
void set_failure_in_set_up(FailureType type) {
failure_in_set_up_ = type;
}
// Was SetUp() run?
bool set_up_was_run() const { return set_up_was_run_; }
// Was TearDown() run?
bool tear_down_was_run() const { return tear_down_was_run_; }
private:
FailureType failure_in_set_up_;
bool set_up_was_run_;
bool tear_down_was_run_;
};
// Was the TEST run?
bool test_was_run;
// The sole purpose of this TEST is to enable us to check whether it
// was run.
TEST(FooTest, Bar) {
test_was_run = true;
}
// Prints the message and aborts the program if condition is false.
void Check(bool condition, const char* msg) {
if (!condition) {
printf("FAILED: %s\n", msg);
abort();
}
}
// Runs the tests. Return true iff successful.
//
// The 'failure' parameter specifies the type of failure that should
// be generated by the global set-up.
int RunAllTests(MyEnvironment* env, FailureType failure) {
env->Reset();
env->set_failure_in_set_up(failure);
test_was_run = false;
return RUN_ALL_TESTS();
}
} // namespace
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
// Registers a global test environment, and verifies that the
// registration function returns its argument.
MyEnvironment* const env = new MyEnvironment;
Check(testing::AddGlobalTestEnvironment(env) == env,
"AddGlobalTestEnvironment() should return its argument.");
// Verifies that RUN_ALL_TESTS() runs the tests when the global
// set-up is successful.
Check(RunAllTests(env, NO_FAILURE) != 0,
"RUN_ALL_TESTS() should return non-zero, as the global tear-down "
"should generate a failure.");
Check(test_was_run,
"The tests should run, as the global set-up should generate no "
"failure");
Check(env->tear_down_was_run(),
"The global tear-down should run, as the global set-up was run.");
// Verifies that RUN_ALL_TESTS() runs the tests when the global
// set-up generates no fatal failure.
Check(RunAllTests(env, NON_FATAL_FAILURE) != 0,
"RUN_ALL_TESTS() should return non-zero, as both the global set-up "
"and the global tear-down should generate a non-fatal failure.");
Check(test_was_run,
"The tests should run, as the global set-up should generate no "
"fatal failure.");
Check(env->tear_down_was_run(),
"The global tear-down should run, as the global set-up was run.");
// Verifies that RUN_ALL_TESTS() runs no test when the global set-up
// generates a fatal failure.
Check(RunAllTests(env, FATAL_FAILURE) != 0,
"RUN_ALL_TESTS() should return non-zero, as the global set-up "
"should generate a fatal failure.");
Check(!test_was_run,
"The tests should not run, as the global set-up should generate "
"a fatal failure.");
Check(env->tear_down_was_run(),
"The global tear-down should run, as the global set-up was run.");
// Verifies that RUN_ALL_TESTS() doesn't do global set-up or
// tear-down when there is no test to run.
testing::GTEST_FLAG(filter) = "-*";
Check(RunAllTests(env, NO_FAILURE) == 0,
"RUN_ALL_TESTS() should return zero, as there is no test to run.");
Check(!env->set_up_was_run(),
"The global set-up should not run, as there is no test to run.");
Check(!env->tear_down_was_run(),
"The global tear-down should not run, "
"as the global set-up was not run.");
printf("PASS\n");
return 0;
}

315
test/gtest_filter_unittest.py Executable file
View File

@ -0,0 +1,315 @@
#!/usr/bin/env python
#
# 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.
"""Unit test for Google Test test filters.
A user can specify which test(s) in a Google Test program to run via either
the GTEST_FILTER environment variable or the --gtest_filter flag.
This script tests such functionality by invoking
gtest_filter_unittest_ (a program written with Google Test) with different
environments and command line flags.
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import gtest_test_utils
import os
import re
import sys
import unittest
# Constants.
# The environment variable for specifying the test filters.
FILTER_ENV_VAR = 'GTEST_FILTER'
# The command line flag for specifying the test filters.
FILTER_FLAG = 'gtest_filter'
# Command to run the gtest_filter_unittest_ program.
COMMAND = os.path.join(gtest_test_utils.GetBuildDir(),
'gtest_filter_unittest_')
# Regex for parsing test case names from Google Test's output.
TEST_CASE_REGEX = re.compile(r'^\[\-+\] \d+ test.* from (\w+)')
# Regex for parsing test names from Google Test's output.
TEST_REGEX = re.compile(r'^\[\s*RUN\s*\].*\.(\w+)')
# Full names of all tests in gtest_filter_unittests_.
ALL_TESTS = [
'FooTest.Abc',
'FooTest.Xyz',
'BarTest.Test1',
'BarTest.Test2',
'BarTest.Test3',
'BazTest.Test1',
'BazTest.TestA',
'BazTest.TestB',
]
# Utilities.
def SetEnvVar(env_var, value):
"""Sets the env variable to 'value'; unsets it when 'value' is None."""
if value is not None:
os.environ[env_var] = value
elif env_var in os.environ:
del os.environ[env_var]
def Run(command):
"""Runs a Google Test program and returns a list of full names of the
tests that were run.
"""
stdout_file = os.popen(command, 'r')
tests_run = []
test_case = ''
test = ''
for line in stdout_file:
match = TEST_CASE_REGEX.match(line)
if match is not None:
test_case = match.group(1)
else:
match = TEST_REGEX.match(line)
if match is not None:
test = match.group(1)
tests_run += [test_case + '.' + test]
stdout_file.close()
return tests_run
# The unit test.
class GTestFilterUnitTest(unittest.TestCase):
"""Tests using the GTEST_FILTER environment variable or the
--gtest_filter flag to filter tests.
"""
# Utilities.
def AssertSetEqual(self, lhs, rhs):
"""Asserts that two sets are equal."""
for elem in lhs:
self.assert_(elem in rhs, '%s in %s' % (elem, rhs))
for elem in rhs:
self.assert_(elem in lhs, '%s in %s' % (elem, lhs))
def RunAndVerify(self, gtest_filter, tests_to_run):
"""Runs gtest_flag_unittest_ with the given filter, and verifies
that the right set of tests were run.
"""
# First, tests using GTEST_FILTER.
SetEnvVar(FILTER_ENV_VAR, gtest_filter)
tests_run = Run(COMMAND)
SetEnvVar(FILTER_ENV_VAR, None)
self.AssertSetEqual(tests_run, tests_to_run)
# Next, tests using --gtest_filter.
if gtest_filter is None:
command = COMMAND
else:
command = '%s --%s=%s' % (COMMAND, FILTER_FLAG, gtest_filter)
tests_run = Run(command)
self.AssertSetEqual(tests_run, tests_to_run)
def testDefaultBehavior(self):
"""Tests the behavior of not specifying the filter."""
self.RunAndVerify(None, ALL_TESTS)
def testEmptyFilter(self):
"""Tests an empty filter."""
self.RunAndVerify('', [])
def testBadFilter(self):
"""Tests a filter that matches nothing."""
self.RunAndVerify('BadFilter', [])
def testFullName(self):
"""Tests filtering by full name."""
self.RunAndVerify('FooTest.Xyz', ['FooTest.Xyz'])
def testUniversalFilters(self):
"""Tests filters that match everything."""
self.RunAndVerify('*', ALL_TESTS)
self.RunAndVerify('*.*', ALL_TESTS)
def testFilterByTestCase(self):
"""Tests filtering by test case name."""
self.RunAndVerify('FooTest.*', ['FooTest.Abc', 'FooTest.Xyz'])
def testFilterByTest(self):
"""Tests filtering by test name."""
self.RunAndVerify('*.Test1', ['BarTest.Test1', 'BazTest.Test1'])
def testWildcardInTestCaseName(self):
"""Tests using wildcard in the test case name."""
self.RunAndVerify('*a*.*', [
'BarTest.Test1',
'BarTest.Test2',
'BarTest.Test3',
'BazTest.Test1',
'BazTest.TestA',
'BazTest.TestB',
])
def testWildcardInTestName(self):
"""Tests using wildcard in the test name."""
self.RunAndVerify('*.*A*', ['FooTest.Abc', 'BazTest.TestA'])
def testFilterWithoutDot(self):
"""Tests a filter that has no '.' in it."""
self.RunAndVerify('*z*', [
'FooTest.Xyz',
'BazTest.Test1',
'BazTest.TestA',
'BazTest.TestB',
])
def testTwoPatterns(self):
"""Tests filters that consist of two patterns."""
self.RunAndVerify('Foo*.*:*A*', [
'FooTest.Abc',
'FooTest.Xyz',
'BazTest.TestA',
])
# An empty pattern + a non-empty one
self.RunAndVerify(':*A*', ['FooTest.Abc', 'BazTest.TestA'])
def testThreePatterns(self):
"""Tests filters that consist of three patterns."""
self.RunAndVerify('*oo*:*A*:*1', [
'FooTest.Abc',
'FooTest.Xyz',
'BarTest.Test1',
'BazTest.Test1',
'BazTest.TestA',
])
# The 2nd pattern is empty.
self.RunAndVerify('*oo*::*1', [
'FooTest.Abc',
'FooTest.Xyz',
'BarTest.Test1',
'BazTest.Test1',
])
# The last 2 patterns are empty.
self.RunAndVerify('*oo*::', [
'FooTest.Abc',
'FooTest.Xyz',
])
def testNegativeFilters(self):
self.RunAndVerify('*-FooTest.Abc', [
'FooTest.Xyz',
'BarTest.Test1',
'BarTest.Test2',
'BarTest.Test3',
'BazTest.Test1',
'BazTest.TestA',
'BazTest.TestB',
])
self.RunAndVerify('*-FooTest.Abc:BazTest.*', [
'FooTest.Xyz',
'BarTest.Test1',
'BarTest.Test2',
'BarTest.Test3',
])
self.RunAndVerify('BarTest.*-BarTest.Test1', [
'BarTest.Test2',
'BarTest.Test3',
])
# Tests without leading '*'.
self.RunAndVerify('-FooTest.Abc:FooTest.Xyz', [
'BarTest.Test1',
'BarTest.Test2',
'BarTest.Test3',
'BazTest.Test1',
'BazTest.TestA',
'BazTest.TestB',
])
def testFlagOverridesEnvVar(self):
"""Tests that the --gtest_filter flag overrides the GTEST_FILTER
environment variable."""
SetEnvVar(FILTER_ENV_VAR, 'Foo*')
command = '%s --%s=%s' % (COMMAND, FILTER_FLAG, '*1')
tests_run = Run(command)
SetEnvVar(FILTER_ENV_VAR, None)
self.AssertSetEqual(tests_run, ['BarTest.Test1', 'BazTest.Test1'])
if __name__ == '__main__':
gtest_test_utils.Main()

View File

@ -0,0 +1,90 @@
// 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)
// Unit test for Google Test test filters.
//
// A user can specify which test(s) in a Google Test program to run via
// either the GTEST_FILTER environment variable or the --gtest_filter
// flag. This is used for testing such functionality.
//
// The program will be invoked from a Python unit test. Don't run it
// directly.
#include <gtest/gtest.h>
namespace {
// Test case FooTest.
class FooTest : public testing::Test {
};
TEST_F(FooTest, Abc) {
}
TEST_F(FooTest, Xyz) {
FAIL() << "Expected failure.";
}
// Test case BarTest.
TEST(BarTest, Test1) {
}
TEST(BarTest, Test2) {
}
TEST(BarTest, Test3) {
}
// Test case BazTest.
TEST(BazTest, Test1) {
FAIL() << "Expected failure.";
}
TEST(BazTest, TestA) {
}
TEST(BazTest, TestB) {
}
} // namespace
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

165
test/gtest_list_tests_unittest.py Executable file
View File

@ -0,0 +1,165 @@
#!/usr/bin/env python
#
# 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.
"""Unit test for Google Test's --gtest_list_tests flag.
A user can ask Google Test to list all tests by specifying the
--gtest_list_tests flag. This script tests such functionality
by invoking gtest_list_tests_unittest_ (a program written with
Google Test) the command line flags.
"""
__author__ = 'phanna@google.com (Patrick Hanna)'
import gtest_test_utils
import os
import re
import sys
import unittest
# Constants.
# The command line flag for enabling/disabling listing all tests.
LIST_TESTS_FLAG = 'gtest_list_tests'
# Path to the gtest_list_tests_unittest_ program.
EXE_PATH = os.path.join(gtest_test_utils.GetBuildDir(),
'gtest_list_tests_unittest_');
# The expected output when running gtest_list_tests_unittest_ with
# --gtest_list_tests
EXPECTED_OUTPUT = """FooDeathTest.
Test1
Foo.
Bar1
Bar2
Bar3
Abc.
Xyz
Def
FooBar.
Baz
FooTest.
Test1
Test2
Test3
"""
# Utilities.
def Run(command):
"""Runs a command and returns the list of tests printed.
"""
stdout_file = os.popen(command, "r")
output = stdout_file.read()
stdout_file.close()
return output
# The unit test.
class GTestListTestsUnitTest(unittest.TestCase):
"""Tests using the --gtest_list_tests flag to list all tests.
"""
def RunAndVerify(self, flag_value, expected_output, other_flag):
"""Runs gtest_list_tests_unittest_ and verifies that it prints
the correct tests.
Args:
flag_value: value of the --gtest_list_tests flag;
None if the flag should not be present.
expected_output: the expected output after running command;
other_flag: a different flag to be passed to command
along with gtest_list_tests;
None if the flag should not be present.
"""
if flag_value is None:
flag = ''
flag_expression = "not set"
elif flag_value == '0':
flag = ' --%s=0' % LIST_TESTS_FLAG
flag_expression = "0"
else:
flag = ' --%s' % LIST_TESTS_FLAG
flag_expression = "1"
command = EXE_PATH + flag
if other_flag is not None:
command += " " + other_flag
output = Run(command)
msg = ('when %s is %s, the output of "%s" is "%s".' %
(LIST_TESTS_FLAG, flag_expression, command, output))
if expected_output is not None:
self.assert_(output == expected_output, msg)
else:
self.assert_(output != EXPECTED_OUTPUT, msg)
def testDefaultBehavior(self):
"""Tests the behavior of the default mode."""
self.RunAndVerify(flag_value=None,
expected_output=None,
other_flag=None)
def testFlag(self):
"""Tests using the --gtest_list_tests flag."""
self.RunAndVerify(flag_value='0',
expected_output=None,
other_flag=None)
self.RunAndVerify(flag_value='1',
expected_output=EXPECTED_OUTPUT,
other_flag=None)
def testOverrideOtherFlags(self):
"""Tests that --gtest_list_tests overrides all other flags."""
self.RunAndVerify(flag_value="1",
expected_output=EXPECTED_OUTPUT,
other_flag="--gtest_filter=*")
self.RunAndVerify(flag_value="1",
expected_output=EXPECTED_OUTPUT,
other_flag="--gtest_break_on_failure")
if __name__ == '__main__':
gtest_test_utils.Main()

View File

@ -0,0 +1,87 @@
// 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.
//
// Author: phanna@google.com (Patrick Hanna)
// Unit test for Google Test's --gtest_list_tests flag.
//
// A user can ask Google Test to list all tests that will run
// so that when using a filter, a user will know what
// tests to look for. The tests will not be run after listing.
//
// This program will be invoked from a Python unit test.
// Don't run it directly.
#include <gtest/gtest.h>
namespace {
// Several different test cases and tests that will be listed.
TEST(Foo, Bar1) {
}
TEST(Foo, Bar2) {
}
TEST(Foo, Bar3) {
}
TEST(Abc, Xyz) {
}
TEST(Abc, Def) {
}
TEST(FooBar, Baz) {
}
class FooTest : public testing::Test {
};
TEST_F(FooTest, Test1) {
}
TEST_F(FooTest, Test2) {
}
TEST_F(FooTest, Test3) {
}
TEST(FooDeathTest, Test1) {
}
} // namespace
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -0,0 +1,45 @@
// 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.
//
// Author: wan@google.com (Zhanyong Wan)
#include <gtest/gtest.h>
// Tests that we don't have to define main() when we link to
// gtest_main instead of gtest.
namespace {
TEST(GTestMainTest, ShouldSucceed) {
}
} // namespace
// We are using the main() function defined in src/gtest_main.cc, so
// we don't define it here.

115
test/gtest_nc.cc Normal file
View File

@ -0,0 +1,115 @@
// Copyright 2007, 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 is the input to a negative-compilation test for Google
// Test. Code here is NOT supposed to compile. Its purpose is to
// verify that certain incorrect usages of the Google Test API are
// indeed rejected by the compiler.
//
// We still need to write the negative-compilation test itself, which
// will be tightly coupled with the build environment.
//
// TODO(wan@google.com): finish the negative-compilation test.
#ifdef TEST_CANNOT_IGNORE_RUN_ALL_TESTS_RESULT
// Tests that the result of RUN_ALL_TESTS() cannot be ignored.
#include <gtest/gtest.h>
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
RUN_ALL_TESTS(); // This line shouldn't compile.
}
#elif defined(TEST_USER_CANNOT_INCLUDE_GTEST_INTERNAL_INL_H)
// Tests that a user cannot include gtest-internal-inl.h in his code.
#include "src/gtest-internal-inl.h"
#elif defined(TEST_CATCHES_DECLARING_SETUP_IN_TEST_FIXTURE_WITH_TYPO)
// Tests that the compiler catches the typo when a user declares a
// Setup() method in a test fixture.
#include <gtest/gtest.h>
class MyTest : public testing::Test {
protected:
void Setup() {}
};
#elif defined(TEST_CATCHES_CALLING_SETUP_IN_TEST_WITH_TYPO)
// Tests that the compiler catches the typo when a user calls Setup()
// from a test fixture.
#include <gtest/gtest.h>
class MyTest : public testing::Test {
protected:
virtual void SetUp() {
testing::Test::Setup(); // Tries to call SetUp() in the parent class.
}
};
#elif defined(TEST_CATCHES_DECLARING_SETUP_IN_ENVIRONMENT_WITH_TYPO)
// Tests that the compiler catches the typo when a user declares a
// Setup() method in a subclass of Environment.
#include <gtest/gtest.h>
class MyEnvironment : public testing::Environment {
public:
void Setup() {}
};
#elif defined(TEST_CATCHES_CALLING_SETUP_IN_ENVIRONMENT_WITH_TYPO)
// Tests that the compiler catches the typo when a user calls Setup()
// in an Environment.
#include <gtest/gtest.h>
class MyEnvironment : public testing::Environment {
protected:
virtual void SetUp() {
// Tries to call SetUp() in the parent class.
testing::Environment::Setup();
}
};
#else
// A sanity test. This should compile.
#include <gtest/gtest.h>
int main() {
return RUN_ALL_TESTS();
}
#endif

77
test/gtest_nc_test.py Executable file
View File

@ -0,0 +1,77 @@
#!/usr/bin/env python
#
# Copyright 2007, 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.
"""Negative compilation test for Google Test."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import sys
import unittest
class GTestNCTest(unittest.TestCase):
"""Negative compilation test for Google Test."""
def testCompilerError(self):
"""Verifies that erroneous code leads to expected compiler
messages."""
# Defines a list of test specs, where each element is a tuple
# (test name, list of regexes for matching the compiler errors).
test_specs = [
('CANNOT_IGNORE_RUN_ALL_TESTS_RESULT',
[r'ignoring return value']),
('USER_CANNOT_INCLUDE_GTEST_INTERNAL_INL_H',
[r'must not be included except by Google Test itself']),
('CATCHES_DECLARING_SETUP_IN_TEST_FIXTURE_WITH_TYPO',
[r'Setup_should_be_spelled_SetUp']),
('CATCHES_CALLING_SETUP_IN_TEST_WITH_TYPO',
[r'Setup_should_be_spelled_SetUp']),
('CATCHES_DECLARING_SETUP_IN_ENVIRONMENT_WITH_TYPO',
[r'Setup_should_be_spelled_SetUp']),
('CATCHES_CALLING_SETUP_IN_ENVIRONMENT_WITH_TYPO',
[r'Setup_should_be_spelled_SetUp']),
('SANITY',
None)
]
# TODO(wan@google.com): verify that the test specs are satisfied.
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,54 @@
// 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.
// Tests that a Google Test program that has no test defined can run
// successfully.
//
// Author: wan@google.com (Zhanyong Wan)
#include <gtest/gtest.h>
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
// An ad-hoc assertion outside of all tests.
//
// This serves two purposes:
//
// 1. It verifies that an ad-hoc assertion can be executed even if
// no test is defined.
// 2. We had a bug where the XML output won't be generated if an
// assertion is executed before RUN_ALL_TESTS() is called, even
// though --gtest_output=xml is specified. This makes sure the
// bug is fixed and doesn't regress.
EXPECT_EQ(1, 1);
return RUN_ALL_TESTS();
}

183
test/gtest_output_test.py Executable file
View File

@ -0,0 +1,183 @@
#!/usr/bin/env python
#
# 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.
"""Tests the text output of Google C++ Testing Framework.
SYNOPSIS
gtest_output_test.py --gengolden
gtest_output_test.py
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import gtest_test_utils
import os
import re
import string
import sys
import unittest
# The flag for generating the golden file
GENGOLDEN_FLAG = '--gengolden'
IS_WINDOWS = os.name == 'nt'
if IS_WINDOWS:
PROGRAM = r'..\build.dbg8\gtest_output_test_.exe'
GOLDEN_NAME = 'gtest_output_test_golden_win.txt'
else:
PROGRAM = 'gtest_output_test_'
GOLDEN_NAME = 'gtest_output_test_golden_lin.txt'
COMMAND = os.path.join(gtest_test_utils.GetBuildDir(),
PROGRAM) + ' --gtest_color=yes'
GOLDEN_PATH = os.path.join(gtest_test_utils.GetSourceDir(),
GOLDEN_NAME)
def ToUnixLineEnding(s):
"""Changes all Windows/Mac line endings in s to UNIX line endings."""
return s.replace('\r\n', '\n').replace('\r', '\n')
def RemoveLocations(output):
"""Removes all file location info from a Google Test program's output.
Args:
output: the output of a Google Test program.
Returns:
output with all file location info (in the form of
'DIRECTORY/FILE_NAME:LINE_NUMBER: ') replaced by
'FILE_NAME:#: '.
"""
return re.sub(r'.*[/\\](.+)\:\d+\: ', r'\1:#: ', output)
def RemoveStackTraces(output):
"""Removes all stack traces from a Google Test program's output."""
# *? means "find the shortest string that matches".
return re.sub(r'Stack trace:(.|\n)*?\n\n',
'Stack trace: (omitted)\n\n', output)
def NormalizeOutput(output):
"""Normalizes output (the output of gtest_output_test_.exe)."""
output = ToUnixLineEnding(output)
output = RemoveLocations(output)
output = RemoveStackTraces(output)
return output
def IterShellCommandOutput(cmd, stdin_string=None):
"""Runs a command in a sub-process, and iterates the lines in its STDOUT.
Args:
cmd: The shell command.
stdin_string: The string to be fed to the STDIN of the sub-process;
If None, the sub-process will inherit the STDIN
from the parent process.
"""
# Spawns cmd in a sub-process, and gets its standard I/O file objects.
stdin_file, stdout_file = os.popen2(cmd, 'b')
# If the caller didn't specify a string for STDIN, gets it from the
# parent process.
if stdin_string is None:
stdin_string = sys.stdin.read()
# Feeds the STDIN string to the sub-process.
stdin_file.write(stdin_string)
stdin_file.close()
while True:
line = stdout_file.readline()
if not line: # EOF
stdout_file.close()
break
yield line
def GetShellCommandOutput(cmd, stdin_string=None):
"""Runs a command in a sub-process, and returns its STDOUT in a string.
Args:
cmd: The shell command.
stdin_string: The string to be fed to the STDIN of the sub-process;
If None, the sub-process will inherit the STDIN
from the parent process.
"""
lines = list(IterShellCommandOutput(cmd, stdin_string))
return string.join(lines, '')
def GetCommandOutput(cmd):
"""Runs a command and returns its output with all file location
info stripped off.
Args:
cmd: the shell command.
"""
# Disables exception pop-ups on Windows.
os.environ['GUNIT_CATCH_EXCEPTIONS'] = '1'
return NormalizeOutput(GetShellCommandOutput(cmd, ''))
class GTestOutputTest(unittest.TestCase):
def testOutput(self):
output = GetCommandOutput(COMMAND)
golden_file = open(GOLDEN_PATH, 'rb')
golden = golden_file.read()
golden_file.close()
self.assertEquals(golden, output)
if __name__ == '__main__':
if sys.argv[1:] == [GENGOLDEN_FLAG]:
output = GetCommandOutput(COMMAND)
golden_file = open(GOLDEN_PATH, 'wb')
golden_file.write(output)
golden_file.close()
else:
gtest_test_utils.Main()

755
test/gtest_output_test_.cc Normal file
View File

@ -0,0 +1,755 @@
// 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.
//
// A unit test for Google Test itself. This verifies that the basic
// constructs of Google Test work.
//
// Author: wan@google.com (Zhanyong Wan)
#include <gtest/gtest-spi.h>
#include <gtest/gtest.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 "src/gtest-internal-inl.h"
#undef GTEST_IMPLEMENTATION
#include <stdlib.h>
#ifdef GTEST_OS_LINUX
#include <string.h>
#include <signal.h>
#include <pthread.h>
#include <string>
#include <vector>
#endif // GTEST_OS_LINUX
// Tests catching fatal failures.
// A subroutine used by the following test.
void TestEq1(int x) {
ASSERT_EQ(1, x);
}
// This function calls a test subroutine, catches the fatal failure it
// generates, and then returns early.
void TryTestSubroutine() {
// Calls a subrountine that yields a fatal failure.
TestEq1(2);
// Catches the fatal failure and aborts the test.
//
// The testing::Test:: prefix is necessary when calling
// HasFatalFailure() outside of a TEST, TEST_F, or test fixture.
if (testing::Test::HasFatalFailure()) return;
// If we get here, something is wrong.
FAIL() << "This should never be reached.";
}
// Tests catching a fatal failure in a subroutine.
TEST(FatalFailureTest, FatalFailureInSubroutine) {
printf("(expecting a failure that x should be 1)\n");
TryTestSubroutine();
}
// Tests catching a fatal failure in a nested subroutine.
TEST(FatalFailureTest, FatalFailureInNestedSubroutine) {
printf("(expecting a failure that x should be 1)\n");
// Calls a subrountine that yields a fatal failure.
TryTestSubroutine();
// Catches the fatal failure and aborts the test.
//
// When calling HasFatalFailure() inside a TEST, TEST_F, or test
// fixture, the testing::Test:: prefix is not needed.
if (HasFatalFailure()) return;
// If we get here, something is wrong.
FAIL() << "This should never be reached.";
}
// Tests HasFatalFailure() after a failed EXPECT check.
TEST(FatalFailureTest, NonfatalFailureInSubroutine) {
printf("(expecting a failure on false)\n");
EXPECT_TRUE(false); // Generates a nonfatal failure
ASSERT_FALSE(HasFatalFailure()); // This should succeed.
}
// Tests interleaving user logging and Google Test assertions.
TEST(LoggingTest, InterleavingLoggingAndAssertions) {
static const int a[4] = {
3, 9, 2, 6
};
printf("(expecting 2 failures on (3) >= (a[i]))\n");
for (int i = 0; i < static_cast<int>(sizeof(a)/sizeof(*a)); i++) {
printf("i == %d\n", i);
EXPECT_GE(3, a[i]);
}
}
// Tests the SCOPED_TRACE macro.
// A helper function for testing SCOPED_TRACE.
void SubWithoutTrace(int n) {
EXPECT_EQ(1, n);
ASSERT_EQ(2, n);
}
// Another helper function for testing SCOPED_TRACE.
void SubWithTrace(int n) {
SCOPED_TRACE(testing::Message() << "n = " << n);
SubWithoutTrace(n);
}
// Tests that SCOPED_TRACE() obeys lexical scopes.
TEST(SCOPED_TRACETest, ObeysScopes) {
printf("(expected to fail)\n");
// There should be no trace before SCOPED_TRACE() is invoked.
ADD_FAILURE() << "This failure is expected, and shouldn't have a trace.";
{
SCOPED_TRACE("Expected trace");
// After SCOPED_TRACE(), a failure in the current scope should contain
// the trace.
ADD_FAILURE() << "This failure is expected, and should have a trace.";
}
// Once the control leaves the scope of the SCOPED_TRACE(), there
// should be no trace again.
ADD_FAILURE() << "This failure is expected, and shouldn't have a trace.";
}
// Tests that SCOPED_TRACE works inside a loop.
TEST(SCOPED_TRACETest, WorksInLoop) {
printf("(expected to fail)\n");
for (int i = 1; i <= 2; i++) {
SCOPED_TRACE(testing::Message() << "i = " << i);
SubWithoutTrace(i);
}
}
// Tests that SCOPED_TRACE works in a subroutine.
TEST(SCOPED_TRACETest, WorksInSubroutine) {
printf("(expected to fail)\n");
SubWithTrace(1);
SubWithTrace(2);
}
// Tests that SCOPED_TRACE can be nested.
TEST(SCOPED_TRACETest, CanBeNested) {
printf("(expected to fail)\n");
SCOPED_TRACE(""); // A trace without a message.
SubWithTrace(2);
}
// Tests that multiple SCOPED_TRACEs can be used in the same scope.
TEST(SCOPED_TRACETest, CanBeRepeated) {
printf("(expected to fail)\n");
SCOPED_TRACE("A");
ADD_FAILURE()
<< "This failure is expected, and should contain trace point A.";
SCOPED_TRACE("B");
ADD_FAILURE()
<< "This failure is expected, and should contain trace point A and B.";
{
SCOPED_TRACE("C");
ADD_FAILURE() << "This failure is expected, and should contain "
<< "trace point A, B, and C.";
}
SCOPED_TRACE("D");
ADD_FAILURE() << "This failure is expected, and should contain "
<< "trace point A, B, and D.";
}
// Tests using assertions outside of TEST and TEST_F.
//
// This function creates two failures intentionally.
void AdHocTest() {
printf("The non-test part of the code is expected to have 2 failures.\n\n");
EXPECT_TRUE(false);
EXPECT_EQ(2, 3);
}
// Runs all TESTs, all TEST_Fs, and the ad hoc test.
int RunAllTests() {
AdHocTest();
return RUN_ALL_TESTS();
}
// Tests non-fatal failures in the fixture constructor.
class NonFatalFailureInFixtureConstructorTest : public testing::Test {
protected:
NonFatalFailureInFixtureConstructorTest() {
printf("(expecting 5 failures)\n");
ADD_FAILURE() << "Expected failure #1, in the test fixture c'tor.";
}
~NonFatalFailureInFixtureConstructorTest() {
ADD_FAILURE() << "Expected failure #5, in the test fixture d'tor.";
}
virtual void SetUp() {
ADD_FAILURE() << "Expected failure #2, in SetUp().";
}
virtual void TearDown() {
ADD_FAILURE() << "Expected failure #4, in TearDown.";
}
};
TEST_F(NonFatalFailureInFixtureConstructorTest, FailureInConstructor) {
ADD_FAILURE() << "Expected failure #3, in the test body.";
}
// Tests fatal failures in the fixture constructor.
class FatalFailureInFixtureConstructorTest : public testing::Test {
protected:
FatalFailureInFixtureConstructorTest() {
printf("(expecting 2 failures)\n");
Init();
}
~FatalFailureInFixtureConstructorTest() {
ADD_FAILURE() << "Expected failure #2, in the test fixture d'tor.";
}
virtual void SetUp() {
ADD_FAILURE() << "UNEXPECTED failure in SetUp(). "
<< "We should never get here, as the test fixture c'tor "
<< "had a fatal failure.";
}
virtual void TearDown() {
ADD_FAILURE() << "UNEXPECTED failure in TearDown(). "
<< "We should never get here, as the test fixture c'tor "
<< "had a fatal failure.";
}
private:
void Init() {
FAIL() << "Expected failure #1, in the test fixture c'tor.";
}
};
TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) {
ADD_FAILURE() << "UNEXPECTED failure in the test body. "
<< "We should never get here, as the test fixture c'tor "
<< "had a fatal failure.";
}
// Tests non-fatal failures in SetUp().
class NonFatalFailureInSetUpTest : public testing::Test {
protected:
virtual ~NonFatalFailureInSetUpTest() {
Deinit();
}
virtual void SetUp() {
printf("(expecting 4 failures)\n");
ADD_FAILURE() << "Expected failure #1, in SetUp().";
}
virtual void TearDown() {
FAIL() << "Expected failure #3, in TearDown().";
}
private:
void Deinit() {
FAIL() << "Expected failure #4, in the test fixture d'tor.";
}
};
TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) {
FAIL() << "Expected failure #2, in the test function.";
}
// Tests fatal failures in SetUp().
class FatalFailureInSetUpTest : public testing::Test {
protected:
virtual ~FatalFailureInSetUpTest() {
Deinit();
}
virtual void SetUp() {
printf("(expecting 3 failures)\n");
FAIL() << "Expected failure #1, in SetUp().";
}
virtual void TearDown() {
FAIL() << "Expected failure #2, in TearDown().";
}
private:
void Deinit() {
FAIL() << "Expected failure #3, in the test fixture d'tor.";
}
};
TEST_F(FatalFailureInSetUpTest, FailureInSetUp) {
FAIL() << "UNEXPECTED failure in the test function. "
<< "We should never get here, as SetUp() failed.";
}
#ifdef GTEST_OS_WINDOWS
// This group of tests verifies that Google Test handles SEH and C++
// exceptions correctly.
// A function that throws an SEH exception.
static void ThrowSEH() {
int* p = NULL;
*p = 0; // Raises an access violation.
}
// Tests exceptions thrown in the test fixture constructor.
class ExceptionInFixtureCtorTest : public testing::Test {
protected:
ExceptionInFixtureCtorTest() {
printf("(expecting a failure on thrown exception "
"in the test fixture's constructor)\n");
ThrowSEH();
}
virtual ~ExceptionInFixtureCtorTest() {
Deinit();
}
virtual void SetUp() {
FAIL() << "UNEXPECTED failure in SetUp(). "
<< "We should never get here, as the test fixture c'tor threw.";
}
virtual void TearDown() {
FAIL() << "UNEXPECTED failure in TearDown(). "
<< "We should never get here, as the test fixture c'tor threw.";
}
private:
void Deinit() {
FAIL() << "UNEXPECTED failure in the d'tor. "
<< "We should never get here, as the test fixture c'tor threw.";
}
};
TEST_F(ExceptionInFixtureCtorTest, ExceptionInFixtureCtor) {
FAIL() << "UNEXPECTED failure in the test function. "
<< "We should never get here, as the test fixture c'tor threw.";
}
// Tests exceptions thrown in SetUp().
class ExceptionInSetUpTest : public testing::Test {
protected:
virtual ~ExceptionInSetUpTest() {
Deinit();
}
virtual void SetUp() {
printf("(expecting 3 failures)\n");
ThrowSEH();
}
virtual void TearDown() {
FAIL() << "Expected failure #2, in TearDown().";
}
private:
void Deinit() {
FAIL() << "Expected failure #3, in the test fixture d'tor.";
}
};
TEST_F(ExceptionInSetUpTest, ExceptionInSetUp) {
FAIL() << "UNEXPECTED failure in the test function. "
<< "We should never get here, as SetUp() threw.";
}
// Tests that TearDown() and the test fixture d'tor are always called,
// even when the test function throws an exception.
class ExceptionInTestFunctionTest : public testing::Test {
protected:
virtual ~ExceptionInTestFunctionTest() {
Deinit();
}
virtual void TearDown() {
FAIL() << "Expected failure #2, in TearDown().";
}
private:
void Deinit() {
FAIL() << "Expected failure #3, in the test fixture d'tor.";
}
};
// Tests that the test fixture d'tor is always called, even when the
// test function throws an SEH exception.
TEST_F(ExceptionInTestFunctionTest, SEH) {
printf("(expecting 3 failures)\n");
ThrowSEH();
}
#if GTEST_HAS_EXCEPTIONS
// Tests that the test fixture d'tor is always called, even when the
// test function throws a C++ exception. We do this only when
// GTEST_HAS_EXCEPTIONS is non-zero, i.e. C++ exceptions are enabled.
TEST_F(ExceptionInTestFunctionTest, CppException) {
throw 1;
}
// Tests exceptions thrown in TearDown().
class ExceptionInTearDownTest : public testing::Test {
protected:
virtual ~ExceptionInTearDownTest() {
Deinit();
}
virtual void TearDown() {
throw 1;
}
private:
void Deinit() {
FAIL() << "Expected failure #2, in the test fixture d'tor.";
}
};
TEST_F(ExceptionInTearDownTest, ExceptionInTearDown) {
printf("(expecting 2 failures)\n");
}
#endif // GTEST_HAS_EXCEPTIONS
#endif // GTEST_OS_WINDOWS
// The MixedUpTestCaseTest test case verifies that Google Test will fail a
// test if it uses a different fixture class than what other tests in
// the same test case use. It deliberately contains two fixture
// classes with the same name but defined in different namespaces.
// The MixedUpTestCaseWithSameTestNameTest test case verifies that
// when the user defines two tests with the same test case name AND
// same test name (but in different namespaces), the second test will
// fail.
namespace foo {
class MixedUpTestCaseTest : public testing::Test {
};
TEST_F(MixedUpTestCaseTest, FirstTestFromNamespaceFoo) {}
TEST_F(MixedUpTestCaseTest, SecondTestFromNamespaceFoo) {}
class MixedUpTestCaseWithSameTestNameTest : public testing::Test {
};
TEST_F(MixedUpTestCaseWithSameTestNameTest,
TheSecondTestWithThisNameShouldFail) {}
} // namespace foo
namespace bar {
class MixedUpTestCaseTest : public testing::Test {
};
// The following two tests are expected to fail. We rely on the
// golden file to check that Google Test generates the right error message.
TEST_F(MixedUpTestCaseTest, ThisShouldFail) {}
TEST_F(MixedUpTestCaseTest, ThisShouldFailToo) {}
class MixedUpTestCaseWithSameTestNameTest : public testing::Test {
};
// Expected to fail. We rely on the golden file to check that Google Test
// generates the right error message.
TEST_F(MixedUpTestCaseWithSameTestNameTest,
TheSecondTestWithThisNameShouldFail) {}
} // namespace bar
// The following two test cases verify that Google Test catches the user
// error of mixing TEST and TEST_F in the same test case. The first
// test case checks the scenario where TEST_F appears before TEST, and
// the second one checks where TEST appears before TEST_F.
class TEST_F_before_TEST_in_same_test_case : public testing::Test {
};
TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {}
// Expected to fail. We rely on the golden file to check that Google Test
// generates the right error message.
TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {}
class TEST_before_TEST_F_in_same_test_case : public testing::Test {
};
TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {}
// Expected to fail. We rely on the golden file to check that Google Test
// generates the right error message.
TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) {
}
// Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE().
int global_integer = 0;
// Tests that EXPECT_NONFATAL_FAILURE() can reference global variables.
TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) {
global_integer = 0;
EXPECT_NONFATAL_FAILURE({
EXPECT_EQ(1, global_integer) << "Expected non-fatal failure.";
}, "Expected non-fatal failure.");
}
// Tests that EXPECT_NONFATAL_FAILURE() can reference local variables
// (static or not).
TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) {
int m = 0;
static int n;
n = 1;
EXPECT_NONFATAL_FAILURE({
EXPECT_EQ(m, n) << "Expected non-fatal failure.";
}, "Expected non-fatal failure.");
}
// Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly
// one non-fatal failure and no fatal failure.
TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) {
EXPECT_NONFATAL_FAILURE({
ADD_FAILURE() << "Expected non-fatal failure.";
}, "Expected non-fatal failure.");
}
// Tests that EXPECT_NONFATAL_FAILURE() fails when there is no
// non-fatal failure.
TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) {
printf("(expecting a failure)\n");
EXPECT_NONFATAL_FAILURE({
}, "");
}
// Tests that EXPECT_NONFATAL_FAILURE() fails when there are two
// non-fatal failures.
TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) {
printf("(expecting a failure)\n");
EXPECT_NONFATAL_FAILURE({
ADD_FAILURE() << "Expected non-fatal failure 1.";
ADD_FAILURE() << "Expected non-fatal failure 2.";
}, "");
}
// Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal
// failure.
TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) {
printf("(expecting a failure)\n");
EXPECT_NONFATAL_FAILURE({
FAIL() << "Expected fatal failure.";
}, "");
}
// Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
// tested returns.
TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
printf("(expecting a failure)\n");
EXPECT_NONFATAL_FAILURE({
return;
}, "");
}
#if GTEST_HAS_EXCEPTIONS
// Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
// tested throws.
TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
printf("(expecting a failure)\n");
try {
EXPECT_NONFATAL_FAILURE({
throw 0;
}, "");
} catch(int) { // NOLINT
}
}
#endif // GTEST_HAS_EXCEPTIONS
// Tests that EXPECT_FATAL_FAILURE() can reference global variables.
TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
global_integer = 0;
EXPECT_FATAL_FAILURE({
ASSERT_EQ(1, global_integer) << "Expected fatal failure.";
}, "Expected fatal failure.");
}
// Tests that EXPECT_FATAL_FAILURE() can reference local static
// variables.
TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) {
static int n;
n = 1;
EXPECT_FATAL_FAILURE({
ASSERT_EQ(0, n) << "Expected fatal failure.";
}, "Expected fatal failure.");
}
// Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly
// one fatal failure and no non-fatal failure.
TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) {
EXPECT_FATAL_FAILURE({
FAIL() << "Expected fatal failure.";
}, "Expected fatal failure.");
}
// Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal
// failure.
TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) {
printf("(expecting a failure)\n");
EXPECT_FATAL_FAILURE({
}, "");
}
// A helper for generating a fatal failure.
void FatalFailure() {
FAIL() << "Expected fatal failure.";
}
// Tests that EXPECT_FATAL_FAILURE() fails when there are two
// fatal failures.
TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) {
printf("(expecting a failure)\n");
EXPECT_FATAL_FAILURE({
FatalFailure();
FatalFailure();
}, "");
}
// Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal
// failure.
TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) {
printf("(expecting a failure)\n");
EXPECT_FATAL_FAILURE({
ADD_FAILURE() << "Expected non-fatal failure.";
}, "");
}
// Tests that EXPECT_FATAL_FAILURE() fails when the statement being
// tested returns.
TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
printf("(expecting a failure)\n");
EXPECT_FATAL_FAILURE({
return;
}, "");
}
#if GTEST_HAS_EXCEPTIONS
// Tests that EXPECT_FATAL_FAILURE() fails when the statement being
// tested throws.
TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) {
printf("(expecting a failure)\n");
try {
EXPECT_FATAL_FAILURE({
throw 0;
}, "");
} catch(int) { // NOLINT
}
}
#endif // GTEST_HAS_EXCEPTIONS
// Two test environments for testing testing::AddGlobalTestEnvironment().
class FooEnvironment : public testing::Environment {
public:
virtual void SetUp() {
printf("%s", "FooEnvironment::SetUp() called.\n");
}
virtual void TearDown() {
printf("%s", "FooEnvironment::TearDown() called.\n");
FAIL() << "Expected fatal failure.";
}
};
class BarEnvironment : public testing::Environment {
public:
virtual void SetUp() {
printf("%s", "BarEnvironment::SetUp() called.\n");
}
virtual void TearDown() {
printf("%s", "BarEnvironment::TearDown() called.\n");
ADD_FAILURE() << "Expected non-fatal failure.";
}
};
// The main function.
//
// The idea is to use Google Test to run all the tests we have defined (some
// of them are intended to fail), and then compare the test results
// with the "golden" file.
int main(int argc, char **argv) {
// We just run the tests, knowing some of them are intended to fail.
// We will use a separate Python script to compare the output of
// this program with the golden file.
testing::InitGoogleTest(&argc, argv);
#ifdef GTEST_HAS_DEATH_TEST
if (testing::internal::GTEST_FLAG(internal_run_death_test) != "") {
// Skip the usual output capturing if we're running as the child
// process of an threadsafe-style death test.
freopen("/dev/null", "w", stdout);
return RUN_ALL_TESTS();
}
#endif // GTEST_HAS_DEATH_TEST
// Registers two global test environments.
// The golden file verifies that they are set up in the order they
// are registered, and torn down in the reverse order.
testing::AddGlobalTestEnvironment(new FooEnvironment);
testing::AddGlobalTestEnvironment(new BarEnvironment);
return RunAllTests();
}

View File

@ -0,0 +1,383 @@
The non-test part of the code is expected to have 2 failures.
gtest_output_test_.cc:#: Failure
Value of: false
Actual: false
Expected: true
gtest_output_test_.cc:#: Failure
Value of: 3
Expected: 2
[==========] Running 37 tests from 13 test cases.
[----------] Global test environment set-up.
FooEnvironment::SetUp() called.
BarEnvironment::SetUp() called.
[----------] 3 tests from FatalFailureTest
[ RUN ] FatalFailureTest.FatalFailureInSubroutine
(expecting a failure that x should be 1)
gtest_output_test_.cc:#: Failure
Value of: x
Actual: 2
Expected: 1
[ FAILED ] FatalFailureTest.FatalFailureInSubroutine
[ RUN ] FatalFailureTest.FatalFailureInNestedSubroutine
(expecting a failure that x should be 1)
gtest_output_test_.cc:#: Failure
Value of: x
Actual: 2
Expected: 1
[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine
[ RUN ] FatalFailureTest.NonfatalFailureInSubroutine
(expecting a failure on false)
gtest_output_test_.cc:#: Failure
Value of: false
Actual: false
Expected: true
[ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine
[----------] 1 test from LoggingTest
[ RUN ] LoggingTest.InterleavingLoggingAndAssertions
(expecting 2 failures on (3) >= (a[i]))
i == 0
i == 1
gtest_output_test_.cc:#: Failure
Expected: (3) >= (a[i]), actual: 3 vs 9
i == 2
i == 3
gtest_output_test_.cc:#: Failure
Expected: (3) >= (a[i]), actual: 3 vs 6
[ FAILED ] LoggingTest.InterleavingLoggingAndAssertions
[----------] 5 tests from SCOPED_TRACETest
[ RUN ] SCOPED_TRACETest.ObeysScopes
(expected to fail)
gtest_output_test_.cc:#: Failure
Failed
This failure is expected, and shouldn't have a trace.
gtest_output_test_.cc:#: Failure
Failed
This failure is expected, and should have a trace.
Google Test trace:
gtest_output_test_.cc:#: Expected trace
gtest_output_test_.cc:#: Failure
Failed
This failure is expected, and shouldn't have a trace.
[ FAILED ] SCOPED_TRACETest.ObeysScopes
[ RUN ] SCOPED_TRACETest.WorksInLoop
(expected to fail)
gtest_output_test_.cc:#: Failure
Value of: n
Actual: 1
Expected: 2
Google Test trace:
gtest_output_test_.cc:#: i = 1
gtest_output_test_.cc:#: Failure
Value of: n
Actual: 2
Expected: 1
Google Test trace:
gtest_output_test_.cc:#: i = 2
[ FAILED ] SCOPED_TRACETest.WorksInLoop
[ RUN ] SCOPED_TRACETest.WorksInSubroutine
(expected to fail)
gtest_output_test_.cc:#: Failure
Value of: n
Actual: 1
Expected: 2
Google Test trace:
gtest_output_test_.cc:#: n = 1
gtest_output_test_.cc:#: Failure
Value of: n
Actual: 2
Expected: 1
Google Test trace:
gtest_output_test_.cc:#: n = 2
[ FAILED ] SCOPED_TRACETest.WorksInSubroutine
[ RUN ] SCOPED_TRACETest.CanBeNested
(expected to fail)
gtest_output_test_.cc:#: Failure
Value of: n
Actual: 2
Expected: 1
Google Test trace:
gtest_output_test_.cc:#: n = 2
gtest_output_test_.cc:#:
[ FAILED ] SCOPED_TRACETest.CanBeNested
[ RUN ] SCOPED_TRACETest.CanBeRepeated
(expected to fail)
gtest_output_test_.cc:#: Failure
Failed
This failure is expected, and should contain trace point A.
Google Test trace:
gtest_output_test_.cc:#: A
gtest_output_test_.cc:#: Failure
Failed
This failure is expected, and should contain trace point A and B.
Google Test trace:
gtest_output_test_.cc:#: B
gtest_output_test_.cc:#: A
gtest_output_test_.cc:#: Failure
Failed
This failure is expected, and should contain trace point A, B, and C.
Google Test trace:
gtest_output_test_.cc:#: C
gtest_output_test_.cc:#: B
gtest_output_test_.cc:#: A
gtest_output_test_.cc:#: Failure
Failed
This failure is expected, and should contain trace point A, B, and D.
Google Test trace:
gtest_output_test_.cc:#: D
gtest_output_test_.cc:#: B
gtest_output_test_.cc:#: A
[ FAILED ] SCOPED_TRACETest.CanBeRepeated
[----------] 1 test from NonFatalFailureInFixtureConstructorTest
[ RUN ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor
(expecting 5 failures)
gtest_output_test_.cc:#: Failure
Failed
Expected failure #1, in the test fixture c'tor.
gtest_output_test_.cc:#: Failure
Failed
Expected failure #2, in SetUp().
gtest_output_test_.cc:#: Failure
Failed
Expected failure #3, in the test body.
gtest_output_test_.cc:#: Failure
Failed
Expected failure #4, in TearDown.
gtest_output_test_.cc:#: Failure
Failed
Expected failure #5, in the test fixture d'tor.
[ FAILED ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor
[----------] 1 test from FatalFailureInFixtureConstructorTest
[ RUN ] FatalFailureInFixtureConstructorTest.FailureInConstructor
(expecting 2 failures)
gtest_output_test_.cc:#: Failure
Failed
Expected failure #1, in the test fixture c'tor.
gtest_output_test_.cc:#: Failure
Failed
Expected failure #2, in the test fixture d'tor.
[ FAILED ] FatalFailureInFixtureConstructorTest.FailureInConstructor
[----------] 1 test from NonFatalFailureInSetUpTest
[ RUN ] NonFatalFailureInSetUpTest.FailureInSetUp
(expecting 4 failures)
gtest_output_test_.cc:#: Failure
Failed
Expected failure #1, in SetUp().
gtest_output_test_.cc:#: Failure
Failed
Expected failure #2, in the test function.
gtest_output_test_.cc:#: Failure
Failed
Expected failure #3, in TearDown().
gtest_output_test_.cc:#: Failure
Failed
Expected failure #4, in the test fixture d'tor.
[ FAILED ] NonFatalFailureInSetUpTest.FailureInSetUp
[----------] 1 test from FatalFailureInSetUpTest
[ RUN ] FatalFailureInSetUpTest.FailureInSetUp
(expecting 3 failures)
gtest_output_test_.cc:#: Failure
Failed
Expected failure #1, in SetUp().
gtest_output_test_.cc:#: Failure
Failed
Expected failure #2, in TearDown().
gtest_output_test_.cc:#: Failure
Failed
Expected failure #3, in the test fixture d'tor.
[ FAILED ] FatalFailureInSetUpTest.FailureInSetUp
[----------] 4 tests from MixedUpTestCaseTest
[ RUN ] MixedUpTestCaseTest.FirstTestFromNamespaceFoo
[ OK ] MixedUpTestCaseTest.FirstTestFromNamespaceFoo
[ RUN ] MixedUpTestCaseTest.SecondTestFromNamespaceFoo
[ OK ] MixedUpTestCaseTest.SecondTestFromNamespaceFoo
[ RUN ] MixedUpTestCaseTest.ThisShouldFail
gtest.cc:#: Failure
Failed
All tests in the same test case must use the same test fixture
class. However, in test case MixedUpTestCaseTest,
you defined test FirstTestFromNamespaceFoo and test ThisShouldFail
using two different test fixture classes. This can happen if
the two classes are from different namespaces or translation
units and have the same name. You should probably rename one
of the classes to put the tests into different test cases.
[ FAILED ] MixedUpTestCaseTest.ThisShouldFail
[ RUN ] MixedUpTestCaseTest.ThisShouldFailToo
gtest.cc:#: Failure
Failed
All tests in the same test case must use the same test fixture
class. However, in test case MixedUpTestCaseTest,
you defined test FirstTestFromNamespaceFoo and test ThisShouldFailToo
using two different test fixture classes. This can happen if
the two classes are from different namespaces or translation
units and have the same name. You should probably rename one
of the classes to put the tests into different test cases.
[ FAILED ] MixedUpTestCaseTest.ThisShouldFailToo
[----------] 2 tests from MixedUpTestCaseWithSameTestNameTest
[ RUN ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail
[ OK ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail
[ RUN ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail
gtest.cc:#: Failure
Failed
All tests in the same test case must use the same test fixture
class. However, in test case MixedUpTestCaseWithSameTestNameTest,
you defined test TheSecondTestWithThisNameShouldFail and test TheSecondTestWithThisNameShouldFail
using two different test fixture classes. This can happen if
the two classes are from different namespaces or translation
units and have the same name. You should probably rename one
of the classes to put the tests into different test cases.
[ FAILED ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail
[----------] 2 tests from TEST_F_before_TEST_in_same_test_case
[ RUN ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTEST_F
[ OK ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTEST_F
[ RUN ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail
gtest.cc:#: Failure
Failed
All tests in the same test case must use the same test fixture
class, so mixing TEST_F and TEST in the same test case is
illegal. In test case TEST_F_before_TEST_in_same_test_case,
test DefinedUsingTEST_F is defined using TEST_F but
test DefinedUsingTESTAndShouldFail is defined using TEST. You probably
want to change the TEST to TEST_F or move it to another test
case.
[ FAILED ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail
[----------] 2 tests from TEST_before_TEST_F_in_same_test_case
[ RUN ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST
[ OK ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST
[ RUN ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail
gtest.cc:#: Failure
Failed
All tests in the same test case must use the same test fixture
class, so mixing TEST_F and TEST in the same test case is
illegal. In test case TEST_before_TEST_F_in_same_test_case,
test DefinedUsingTEST_FAndShouldFail is defined using TEST_F but
test DefinedUsingTEST is defined using TEST. You probably
want to change the TEST to TEST_F or move it to another test
case.
[ FAILED ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail
[----------] 7 tests from ExpectNonfatalFailureTest
[ RUN ] ExpectNonfatalFailureTest.CanReferenceGlobalVariables
[ OK ] ExpectNonfatalFailureTest.CanReferenceGlobalVariables
[ RUN ] ExpectNonfatalFailureTest.CanReferenceLocalVariables
[ OK ] ExpectNonfatalFailureTest.CanReferenceLocalVariables
[ RUN ] ExpectNonfatalFailureTest.SucceedsWhenThereIsOneNonfatalFailure
[ OK ] ExpectNonfatalFailureTest.SucceedsWhenThereIsOneNonfatalFailure
[ RUN ] ExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure
(expecting a failure)
gtest.cc:#: Failure
Expected: 1 non-fatal failure
Actual: 0 failures
[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure
[ RUN ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures
(expecting a failure)
gtest.cc:#: Failure
Expected: 1 non-fatal failure
Actual: 2 failures
gtest_output_test_.cc:#: Non-fatal failure:
Failed
Expected non-fatal failure 1.
gtest_output_test_.cc:#: Non-fatal failure:
Failed
Expected non-fatal failure 2.
[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures
[ RUN ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure
(expecting a failure)
gtest.cc:#: Failure
Expected: 1 non-fatal failure
Actual:
gtest_output_test_.cc:#: Fatal failure:
Failed
Expected fatal failure.
[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure
[ RUN ] ExpectNonfatalFailureTest.FailsWhenStatementReturns
(expecting a failure)
gtest.cc:#: Failure
Expected: 1 non-fatal failure
Actual: 0 failures
[ FAILED ] ExpectNonfatalFailureTest.FailsWhenStatementReturns
[----------] 7 tests from ExpectFatalFailureTest
[ RUN ] ExpectFatalFailureTest.CanReferenceGlobalVariables
[ OK ] ExpectFatalFailureTest.CanReferenceGlobalVariables
[ RUN ] ExpectFatalFailureTest.CanReferenceLocalStaticVariables
[ OK ] ExpectFatalFailureTest.CanReferenceLocalStaticVariables
[ RUN ] ExpectFatalFailureTest.SucceedsWhenThereIsOneFatalFailure
[ OK ] ExpectFatalFailureTest.SucceedsWhenThereIsOneFatalFailure
[ RUN ] ExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure
(expecting a failure)
gtest.cc:#: Failure
Expected: 1 fatal failure
Actual: 0 failures
[ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure
[ RUN ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures
(expecting a failure)
gtest.cc:#: Failure
Expected: 1 fatal failure
Actual: 2 failures
gtest_output_test_.cc:#: Fatal failure:
Failed
Expected fatal failure.
gtest_output_test_.cc:#: Fatal failure:
Failed
Expected fatal failure.
[ FAILED ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures
[ RUN ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure
(expecting a failure)
gtest.cc:#: Failure
Expected: 1 fatal failure
Actual:
gtest_output_test_.cc:#: Non-fatal failure:
Failed
Expected non-fatal failure.
[ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure
[ RUN ] ExpectFatalFailureTest.FailsWhenStatementReturns
(expecting a failure)
gtest.cc:#: Failure
Expected: 1 fatal failure
Actual: 0 failures
[ FAILED ] ExpectFatalFailureTest.FailsWhenStatementReturns
[----------] Global test environment tear-down
BarEnvironment::TearDown() called.
gtest_output_test_.cc:#: Failure
Failed
Expected non-fatal failure.
FooEnvironment::TearDown() called.
gtest_output_test_.cc:#: Failure
Failed
Expected fatal failure.
[==========] 37 tests from 13 test cases ran.
[ PASSED ] 11 tests.
[ FAILED ] 26 tests, listed below:
[ FAILED ] FatalFailureTest.FatalFailureInSubroutine
[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine
[ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine
[ FAILED ] LoggingTest.InterleavingLoggingAndAssertions
[ FAILED ] SCOPED_TRACETest.ObeysScopes
[ FAILED ] SCOPED_TRACETest.WorksInLoop
[ FAILED ] SCOPED_TRACETest.WorksInSubroutine
[ FAILED ] SCOPED_TRACETest.CanBeNested
[ FAILED ] SCOPED_TRACETest.CanBeRepeated
[ FAILED ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor
[ FAILED ] FatalFailureInFixtureConstructorTest.FailureInConstructor
[ FAILED ] NonFatalFailureInSetUpTest.FailureInSetUp
[ FAILED ] FatalFailureInSetUpTest.FailureInSetUp
[ FAILED ] MixedUpTestCaseTest.ThisShouldFail
[ FAILED ] MixedUpTestCaseTest.ThisShouldFailToo
[ FAILED ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail
[ FAILED ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail
[ FAILED ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail
[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure
[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures
[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure
[ FAILED ] ExpectNonfatalFailureTest.FailsWhenStatementReturns
[ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure
[ FAILED ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures
[ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure
[ FAILED ] ExpectFatalFailureTest.FailsWhenStatementReturns
26 FAILED TESTS

View File

@ -0,0 +1,415 @@
The non-test part of the code is expected to have 2 failures.
gtest_output_test_.cc:#: Failure
Value of: false
Actual: false
Expected: true
gtest_output_test_.cc:#: Failure
Value of: 3
Expected: 2
[==========] Running 40 tests from 16 test cases.
[----------] Global test environment set-up.
FooEnvironment::SetUp() called.
BarEnvironment::SetUp() called.
[----------] 3 tests from FatalFailureTest
[ RUN ] FatalFailureTest.FatalFailureInSubroutine
(expecting a failure that x should be 1)
gtest_output_test_.cc:#: Failure
Value of: x
Actual: 2
Expected: 1
[ FAILED ] FatalFailureTest.FatalFailureInSubroutine
[ RUN ] FatalFailureTest.FatalFailureInNestedSubroutine
(expecting a failure that x should be 1)
gtest_output_test_.cc:#: Failure
Value of: x
Actual: 2
Expected: 1
[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine
[ RUN ] FatalFailureTest.NonfatalFailureInSubroutine
(expecting a failure on false)
gtest_output_test_.cc:#: Failure
Value of: false
Actual: false
Expected: true
[ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine
[----------] 1 test from LoggingTest
[ RUN ] LoggingTest.InterleavingLoggingAndAssertions
(expecting 2 failures on (3) >= (a[i]))
i == 0
i == 1
gtest_output_test_.cc:#: Failure
Expected: (3) >= (a[i]), actual: 3 vs 9
i == 2
i == 3
gtest_output_test_.cc:#: Failure
Expected: (3) >= (a[i]), actual: 3 vs 6
[ FAILED ] LoggingTest.InterleavingLoggingAndAssertions
[----------] 5 tests from SCOPED_TRACETest
[ RUN ] SCOPED_TRACETest.ObeysScopes
(expected to fail)
gtest_output_test_.cc:#: Failure
Failed
This failure is expected, and shouldn't have a trace.
gtest_output_test_.cc:#: Failure
Failed
This failure is expected, and should have a trace.
gUnit trace:
gtest_output_test_.cc:#: Expected trace
gtest_output_test_.cc:#: Failure
Failed
This failure is expected, and shouldn't have a trace.
[ FAILED ] SCOPED_TRACETest.ObeysScopes
[ RUN ] SCOPED_TRACETest.WorksInLoop
(expected to fail)
gtest_output_test_.cc:#: Failure
Value of: n
Actual: 1
Expected: 2
gUnit trace:
gtest_output_test_.cc:#: i = 1
gtest_output_test_.cc:#: Failure
Value of: n
Actual: 2
Expected: 1
gUnit trace:
gtest_output_test_.cc:#: i = 2
[ FAILED ] SCOPED_TRACETest.WorksInLoop
[ RUN ] SCOPED_TRACETest.WorksInSubroutine
(expected to fail)
gtest_output_test_.cc:#: Failure
Value of: n
Actual: 1
Expected: 2
gUnit trace:
gtest_output_test_.cc:#: n = 1
gtest_output_test_.cc:#: Failure
Value of: n
Actual: 2
Expected: 1
gUnit trace:
gtest_output_test_.cc:#: n = 2
[ FAILED ] SCOPED_TRACETest.WorksInSubroutine
[ RUN ] SCOPED_TRACETest.CanBeNested
(expected to fail)
gtest_output_test_.cc:#: Failure
Value of: n
Actual: 2
Expected: 1
gUnit trace:
gtest_output_test_.cc:#: n = 2
gtest_output_test_.cc:#:
[ FAILED ] SCOPED_TRACETest.CanBeNested
[ RUN ] SCOPED_TRACETest.CanBeRepeated
(expected to fail)
gtest_output_test_.cc:#: Failure
Failed
This failure is expected, and should contain trace point A.
gUnit trace:
gtest_output_test_.cc:#: A
gtest_output_test_.cc:#: Failure
Failed
This failure is expected, and should contain trace point A and B.
gUnit trace:
gtest_output_test_.cc:#: B
gtest_output_test_.cc:#: A
gtest_output_test_.cc:#: Failure
Failed
This failure is expected, and should contain trace point A, B, and C.
gUnit trace:
gtest_output_test_.cc:#: C
gtest_output_test_.cc:#: B
gtest_output_test_.cc:#: A
gtest_output_test_.cc:#: Failure
Failed
This failure is expected, and should contain trace point A, B, and D.
gUnit trace:
gtest_output_test_.cc:#: D
gtest_output_test_.cc:#: B
gtest_output_test_.cc:#: A
[ FAILED ] SCOPED_TRACETest.CanBeRepeated
[----------] 1 test from NonFatalFailureInFixtureConstructorTest
[ RUN ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor
(expecting 5 failures)
gtest_output_test_.cc:#: Failure
Failed
Expected failure #1, in the test fixture c'tor.
gtest_output_test_.cc:#: Failure
Failed
Expected failure #2, in SetUp().
gtest_output_test_.cc:#: Failure
Failed
Expected failure #3, in the test body.
gtest_output_test_.cc:#: Failure
Failed
Expected failure #4, in TearDown.
gtest_output_test_.cc:#: Failure
Failed
Expected failure #5, in the test fixture d'tor.
[ FAILED ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor
[----------] 1 test from FatalFailureInFixtureConstructorTest
[ RUN ] FatalFailureInFixtureConstructorTest.FailureInConstructor
(expecting 2 failures)
gtest_output_test_.cc:#: Failure
Failed
Expected failure #1, in the test fixture c'tor.
gtest_output_test_.cc:#: Failure
Failed
Expected failure #2, in the test fixture d'tor.
[ FAILED ] FatalFailureInFixtureConstructorTest.FailureInConstructor
[----------] 1 test from NonFatalFailureInSetUpTest
[ RUN ] NonFatalFailureInSetUpTest.FailureInSetUp
(expecting 4 failures)
gtest_output_test_.cc:#: Failure
Failed
Expected failure #1, in SetUp().
gtest_output_test_.cc:#: Failure
Failed
Expected failure #2, in the test function.
gtest_output_test_.cc:#: Failure
Failed
Expected failure #3, in TearDown().
gtest_output_test_.cc:#: Failure
Failed
Expected failure #4, in the test fixture d'tor.
[ FAILED ] NonFatalFailureInSetUpTest.FailureInSetUp
[----------] 1 test from FatalFailureInSetUpTest
[ RUN ] FatalFailureInSetUpTest.FailureInSetUp
(expecting 3 failures)
gtest_output_test_.cc:#: Failure
Failed
Expected failure #1, in SetUp().
gtest_output_test_.cc:#: Failure
Failed
Expected failure #2, in TearDown().
gtest_output_test_.cc:#: Failure
Failed
Expected failure #3, in the test fixture d'tor.
[ FAILED ] FatalFailureInSetUpTest.FailureInSetUp
[----------] 1 test from ExceptionInFixtureCtorTest
[ RUN ] ExceptionInFixtureCtorTest.ExceptionInFixtureCtor
(expecting a failure on thrown exception in the test fixture's constructor)
unknown file: Failure
Exception thrown with code 0xc0000005 in the test fixture's constructor.
[----------] 1 test from ExceptionInSetUpTest
[ RUN ] ExceptionInSetUpTest.ExceptionInSetUp
(expecting 3 failures)
unknown file: Failure
Exception thrown with code 0xc0000005 in SetUp().
gtest_output_test_.cc:#: Failure
Failed
Expected failure #2, in TearDown().
gtest_output_test_.cc:#: Failure
Failed
Expected failure #3, in the test fixture d'tor.
[ FAILED ] ExceptionInSetUpTest.ExceptionInSetUp
[----------] 1 test from ExceptionInTestFunctionTest
[ RUN ] ExceptionInTestFunctionTest.SEH
(expecting 3 failures)
unknown file: Failure
Exception thrown with code 0xc0000005 in the test body.
gtest_output_test_.cc:#: Failure
Failed
Expected failure #2, in TearDown().
gtest_output_test_.cc:#: Failure
Failed
Expected failure #3, in the test fixture d'tor.
[ FAILED ] ExceptionInTestFunctionTest.SEH
[----------] 4 tests from MixedUpTestCaseTest
[ RUN ] MixedUpTestCaseTest.FirstTestFromNamespaceFoo
[ OK ] MixedUpTestCaseTest.FirstTestFromNamespaceFoo
[ RUN ] MixedUpTestCaseTest.SecondTestFromNamespaceFoo
[ OK ] MixedUpTestCaseTest.SecondTestFromNamespaceFoo
[ RUN ] MixedUpTestCaseTest.ThisShouldFail
gtest.cc:#: Failure
Failed
All tests in the same test case must use the same test fixture
class. However, in test case MixedUpTestCaseTest,
you defined test FirstTestFromNamespaceFoo and test ThisShouldFail
using two different test fixture classes. This can happen if
the two classes are from different namespaces or translation
units and have the same name. You should probably rename one
of the classes to put the tests into different test cases.
[ FAILED ] MixedUpTestCaseTest.ThisShouldFail
[ RUN ] MixedUpTestCaseTest.ThisShouldFailToo
gtest.cc:#: Failure
Failed
All tests in the same test case must use the same test fixture
class. However, in test case MixedUpTestCaseTest,
you defined test FirstTestFromNamespaceFoo and test ThisShouldFailToo
using two different test fixture classes. This can happen if
the two classes are from different namespaces or translation
units and have the same name. You should probably rename one
of the classes to put the tests into different test cases.
[ FAILED ] MixedUpTestCaseTest.ThisShouldFailToo
[----------] 2 tests from MixedUpTestCaseWithSameTestNameTest
[ RUN ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail
[ OK ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail
[ RUN ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail
gtest.cc:#: Failure
Failed
All tests in the same test case must use the same test fixture
class. However, in test case MixedUpTestCaseWithSameTestNameTest,
you defined test TheSecondTestWithThisNameShouldFail and test TheSecondTestWithThisNameShouldFail
using two different test fixture classes. This can happen if
the two classes are from different namespaces or translation
units and have the same name. You should probably rename one
of the classes to put the tests into different test cases.
[ FAILED ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail
[----------] 2 tests from TEST_F_before_TEST_in_same_test_case
[ RUN ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTEST_F
[ OK ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTEST_F
[ RUN ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail
gtest.cc:#: Failure
Failed
All tests in the same test case must use the same test fixture
class, so mixing TEST_F and TEST in the same test case is
illegal. In test case TEST_F_before_TEST_in_same_test_case,
test DefinedUsingTEST_F is defined using TEST_F but
test DefinedUsingTESTAndShouldFail is defined using TEST. You probably
want to change the TEST to TEST_F or move it to another test
case.
[ FAILED ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail
[----------] 2 tests from TEST_before_TEST_F_in_same_test_case
[ RUN ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST
[ OK ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST
[ RUN ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail
gtest.cc:#: Failure
Failed
All tests in the same test case must use the same test fixture
class, so mixing TEST_F and TEST in the same test case is
illegal. In test case TEST_before_TEST_F_in_same_test_case,
test DefinedUsingTEST_FAndShouldFail is defined using TEST_F but
test DefinedUsingTEST is defined using TEST. You probably
want to change the TEST to TEST_F or move it to another test
case.
[ FAILED ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail
[----------] 7 tests from ExpectNonfatalFailureTest
[ RUN ] ExpectNonfatalFailureTest.CanReferenceGlobalVariables
[ OK ] ExpectNonfatalFailureTest.CanReferenceGlobalVariables
[ RUN ] ExpectNonfatalFailureTest.CanReferenceLocalVariables
[ OK ] ExpectNonfatalFailureTest.CanReferenceLocalVariables
[ RUN ] ExpectNonfatalFailureTest.SucceedsWhenThereIsOneNonfatalFailure
[ OK ] ExpectNonfatalFailureTest.SucceedsWhenThereIsOneNonfatalFailure
[ RUN ] ExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure
(expecting a failure)
gtest.cc:#: Failure
Expected: 1 non-fatal failure
Actual: 0 failures
[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure
[ RUN ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures
(expecting a failure)
gtest.cc:#: Failure
Expected: 1 non-fatal failure
Actual: 2 failures
gtest_output_test_.cc:#: Non-fatal failure:
Failed
Expected non-fatal failure 1.
gtest_output_test_.cc:#: Non-fatal failure:
Failed
Expected non-fatal failure 2.
[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures
[ RUN ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure
(expecting a failure)
gtest.cc:#: Failure
Expected: 1 non-fatal failure
Actual:
gtest_output_test_.cc:#: Fatal failure:
Failed
Expected fatal failure.
[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure
[ RUN ] ExpectNonfatalFailureTest.FailsWhenStatementReturns
(expecting a failure)
gtest.cc:#: Failure
Expected: 1 non-fatal failure
Actual: 0 failures
[ FAILED ] ExpectNonfatalFailureTest.FailsWhenStatementReturns
[----------] 7 tests from ExpectFatalFailureTest
[ RUN ] ExpectFatalFailureTest.CanReferenceGlobalVariables
[ OK ] ExpectFatalFailureTest.CanReferenceGlobalVariables
[ RUN ] ExpectFatalFailureTest.CanReferenceLocalStaticVariables
[ OK ] ExpectFatalFailureTest.CanReferenceLocalStaticVariables
[ RUN ] ExpectFatalFailureTest.SucceedsWhenThereIsOneFatalFailure
[ OK ] ExpectFatalFailureTest.SucceedsWhenThereIsOneFatalFailure
[ RUN ] ExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure
(expecting a failure)
gtest.cc:#: Failure
Expected: 1 fatal failure
Actual: 0 failures
[ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure
[ RUN ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures
(expecting a failure)
gtest.cc:#: Failure
Expected: 1 fatal failure
Actual: 2 failures
gtest_output_test_.cc:#: Fatal failure:
Failed
Expected fatal failure.
gtest_output_test_.cc:#: Fatal failure:
Failed
Expected fatal failure.
[ FAILED ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures
[ RUN ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure
(expecting a failure)
gtest.cc:#: Failure
Expected: 1 fatal failure
Actual:
gtest_output_test_.cc:#: Non-fatal failure:
Failed
Expected non-fatal failure.
[ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure
[ RUN ] ExpectFatalFailureTest.FailsWhenStatementReturns
(expecting a failure)
gtest.cc:#: Failure
Expected: 1 fatal failure
Actual: 0 failures
[ FAILED ] ExpectFatalFailureTest.FailsWhenStatementReturns
[----------] Global test environment tear-down
BarEnvironment::TearDown() called.
gtest_output_test_.cc:#: Failure
Failed
Expected non-fatal failure.
FooEnvironment::TearDown() called.
gtest_output_test_.cc:#: Failure
Failed
Expected fatal failure.
[==========] 40 tests from 16 test cases ran.
[ PASSED ] 11 tests.
[ FAILED ] 29 tests, listed below:
[ FAILED ] FatalFailureTest.FatalFailureInSubroutine
[ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine
[ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine
[ FAILED ] LoggingTest.InterleavingLoggingAndAssertions
[ FAILED ] SCOPED_TRACETest.ObeysScopes
[ FAILED ] SCOPED_TRACETest.WorksInLoop
[ FAILED ] SCOPED_TRACETest.WorksInSubroutine
[ FAILED ] SCOPED_TRACETest.CanBeNested
[ FAILED ] SCOPED_TRACETest.CanBeRepeated
[ FAILED ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor
[ FAILED ] FatalFailureInFixtureConstructorTest.FailureInConstructor
[ FAILED ] NonFatalFailureInSetUpTest.FailureInSetUp
[ FAILED ] FatalFailureInSetUpTest.FailureInSetUp
[ FAILED ] ExceptionInFixtureCtorTest.ExceptionInFixtureCtor
[ FAILED ] ExceptionInSetUpTest.ExceptionInSetUp
[ FAILED ] ExceptionInTestFunctionTest.SEH
[ FAILED ] MixedUpTestCaseTest.ThisShouldFail
[ FAILED ] MixedUpTestCaseTest.ThisShouldFailToo
[ FAILED ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail
[ FAILED ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail
[ FAILED ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail
[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure
[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures
[ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure
[ FAILED ] ExpectNonfatalFailureTest.FailsWhenStatementReturns
[ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure
[ FAILED ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures
[ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure
[ FAILED ] ExpectFatalFailureTest.FailsWhenStatementReturns
29 FAILED TESTS

File diff suppressed because it is too large Load Diff

57
test/gtest_prod_test.cc Normal file
View File

@ -0,0 +1,57 @@
// 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.
//
// Author: wan@google.com (Zhanyong Wan)
//
// Unit test for include/gtest/gtest_prod.h.
#include <gtest/gtest.h>
#include "test/production.h"
// Tests that private members can be accessed from a TEST declared as
// a friend of the class.
TEST(PrivateCodeTest, CanAccessPrivateMembers) {
PrivateCode a;
EXPECT_EQ(0, a.x_);
a.set_x(1);
EXPECT_EQ(1, a.x_);
}
typedef testing::Test PrivateCodeFixtureTest;
// Tests that private members can be accessed from a TEST_F declared
// as a friend of the class.
TEST_F(PrivateCodeFixtureTest, CanAccessPrivateMembers) {
PrivateCode a;
EXPECT_EQ(0, a.x_);
a.set_x(2);
EXPECT_EQ(2, a.x_);
}

223
test/gtest_repeat_test.cc Normal file
View File

@ -0,0 +1,223 @@
// 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.
//
// Author: wan@google.com (Zhanyong Wan)
// Tests the --gtest_repeat=number flag.
#include <stdlib.h>
#include <iostream>
#include <gtest/gtest.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 "src/gtest-internal-inl.h"
#undef GTEST_IMPLEMENTATION
namespace testing {
GTEST_DECLARE_string(death_test_style);
GTEST_DECLARE_string(filter);
GTEST_DECLARE_int32(repeat);
} // namespace testing
using testing::GTEST_FLAG(death_test_style);
using testing::GTEST_FLAG(filter);
using testing::GTEST_FLAG(repeat);
namespace {
#define GTEST_CHECK_INT_EQ_(expected, actual) \
do {\
const int expected_val = (expected);\
const int actual_val = (actual);\
if (expected_val != actual_val) {\
::std::cout << "Value of: " #actual "\n"\
<< " Actual: " << actual_val << "\n"\
<< "Expected: " #expected "\n"\
<< "Which is: " << expected_val << "\n";\
abort();\
}\
} while(false)
// Used for verifying that global environment set-up and tear-down are
// inside the gtest_repeat loop.
int g_environment_set_up_count = 0;
int g_environment_tear_down_count = 0;
class MyEnvironment : public testing::Environment {
public:
MyEnvironment() {}
virtual void SetUp() { g_environment_set_up_count++; }
virtual void TearDown() { g_environment_tear_down_count++; }
};
// A test that should fail.
int g_should_fail_count = 0;
TEST(FooTest, ShouldFail) {
g_should_fail_count++;
EXPECT_EQ(0, 1) << "Expected failure.";
}
// A test that should pass.
int g_should_pass_count = 0;
TEST(FooTest, ShouldPass) {
g_should_pass_count++;
}
// A test that contains a thread-safe death test and a fast death
// test. It should pass.
int g_death_test_count = 0;
TEST(BarDeathTest, ThreadSafeAndFast) {
g_death_test_count++;
GTEST_FLAG(death_test_style) = "threadsafe";
EXPECT_DEATH(abort(), "");
GTEST_FLAG(death_test_style) = "fast";
EXPECT_DEATH(abort(), "");
}
// Resets the count for each test.
void ResetCounts() {
g_environment_set_up_count = 0;
g_environment_tear_down_count = 0;
g_should_fail_count = 0;
g_should_pass_count = 0;
g_death_test_count = 0;
}
// Checks that the count for each test is expected.
void CheckCounts(int expected) {
// We cannot use Google Test assertions here since we are testing Google Test
// itself.
GTEST_CHECK_INT_EQ_(expected, g_environment_set_up_count);
GTEST_CHECK_INT_EQ_(expected, g_environment_tear_down_count);
GTEST_CHECK_INT_EQ_(expected, g_should_fail_count);
GTEST_CHECK_INT_EQ_(expected, g_should_pass_count);
GTEST_CHECK_INT_EQ_(expected, g_death_test_count);
}
// Tests the behavior of Google Test when --gtest_repeat is not specified.
void TestRepeatUnspecified() {
ResetCounts();
GTEST_CHECK_INT_EQ_(1, RUN_ALL_TESTS());
CheckCounts(1);
}
// Tests the behavior of Google Test when --gtest_repeat has the given value.
void TestRepeat(int repeat) {
GTEST_FLAG(repeat) = repeat;
ResetCounts();
GTEST_CHECK_INT_EQ_(repeat > 0 ? 1 : 0, RUN_ALL_TESTS());
CheckCounts(repeat);
}
// Tests using --gtest_repeat when --gtest_filter specifies an empty
// set of tests.
void TestRepeatWithEmptyFilter(int repeat) {
GTEST_FLAG(repeat) = repeat;
GTEST_FLAG(filter) = "None";
ResetCounts();
GTEST_CHECK_INT_EQ_(0, RUN_ALL_TESTS());
CheckCounts(0);
}
// Tests using --gtest_repeat when --gtest_filter specifies a set of
// successful tests.
void TestRepeatWithFilterForSuccessfulTests(int repeat) {
GTEST_FLAG(repeat) = repeat;
GTEST_FLAG(filter) = "*-*ShouldFail";
ResetCounts();
GTEST_CHECK_INT_EQ_(0, RUN_ALL_TESTS());
GTEST_CHECK_INT_EQ_(repeat, g_environment_set_up_count);
GTEST_CHECK_INT_EQ_(repeat, g_environment_tear_down_count);
GTEST_CHECK_INT_EQ_(0, g_should_fail_count);
GTEST_CHECK_INT_EQ_(repeat, g_should_pass_count);
GTEST_CHECK_INT_EQ_(repeat, g_death_test_count);
}
// Tests using --gtest_repeat when --gtest_filter specifies a set of
// failed tests.
void TestRepeatWithFilterForFailedTests(int repeat) {
GTEST_FLAG(repeat) = repeat;
GTEST_FLAG(filter) = "*ShouldFail";
ResetCounts();
GTEST_CHECK_INT_EQ_(1, RUN_ALL_TESTS());
GTEST_CHECK_INT_EQ_(repeat, g_environment_set_up_count);
GTEST_CHECK_INT_EQ_(repeat, g_environment_tear_down_count);
GTEST_CHECK_INT_EQ_(repeat, g_should_fail_count);
GTEST_CHECK_INT_EQ_(0, g_should_pass_count);
GTEST_CHECK_INT_EQ_(0, g_death_test_count);
}
} // namespace
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
testing::AddGlobalTestEnvironment(new MyEnvironment);
TestRepeatUnspecified();
TestRepeat(0);
TestRepeat(1);
TestRepeat(5);
TestRepeatWithEmptyFilter(2);
TestRepeatWithEmptyFilter(3);
TestRepeatWithFilterForSuccessfulTests(3);
TestRepeatWithFilterForFailedTests(4);
// It would be nice to verify that the tests indeed loop forever
// when GTEST_FLAG(repeat) is negative, but this test will be quite
// complicated to write. Since this flag is for interactive
// debugging only and doesn't affect the normal test result, such a
// test would be an overkill.
printf("PASS\n");
return 0;
}

122
test/gtest_stress_test.cc Normal file
View File

@ -0,0 +1,122 @@
// Copyright 2007, 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)
// Tests that SCOPED_TRACE() and various Google Test assertions can be
// used in a large number of threads concurrently.
#include <iostream>
#include <gtest/gtest.h>
// We must define this macro in order to #include
// gtest-internal-inl.h. This is how Google Test prevents a user from
// accidentally depending on its internal implementation.
#define GTEST_IMPLEMENTATION
#include "src/gtest-internal-inl.h"
#undef GTEST_IMPLEMENTATION
namespace testing {
namespace {
using internal::List;
using internal::ListNode;
using internal::String;
using internal::TestProperty;
using internal::TestPropertyKeyIs;
// How many threads to create?
const int kThreadCount = 50;
String IdToKey(int id, const char* suffix) {
Message key;
key << "key_" << id << "_" << suffix;
return key.GetString();
}
String IdToString(int id) {
Message id_message;
id_message << id;
return id_message.GetString();
}
void ExpectKeyAndValueWereRecordedForId(const List<TestProperty>& properties,
int id,
const char* suffix) {
TestPropertyKeyIs matches_key(IdToKey(id, suffix).c_str());
const ListNode<TestProperty>* node = properties.FindIf(matches_key);
EXPECT_TRUE(node != NULL) << "expecting " << suffix << " node for id " << id;
EXPECT_STREQ(IdToString(id).c_str(), node->element().value());
}
// Calls a large number of Google Test assertions, where exactly one of them
// will fail.
void ManyAsserts(int id) {
::std::cout << "Thread #" << id << " running...\n";
SCOPED_TRACE(Message() << "Thread #" << id);
for (int i = 0; i < kThreadCount; i++) {
SCOPED_TRACE(Message() << "Iteration #" << i);
// A bunch of assertions that should succeed.
EXPECT_TRUE(true);
ASSERT_FALSE(false) << "This shouldn't fail.";
EXPECT_STREQ("a", "a");
ASSERT_LE(5, 6);
EXPECT_EQ(i, i) << "This shouldn't fail.";
// RecordProperty() should interact safely with other threads as well.
// The shared_key forces property updates.
Test::RecordProperty(IdToKey(id, "string").c_str(), IdToString(id).c_str());
Test::RecordProperty(IdToKey(id, "int").c_str(), id);
Test::RecordProperty("shared_key", IdToString(id).c_str());
// This assertion should fail kThreadCount times per thread. It
// is for testing whether Google Test can handle failed assertions in a
// multi-threaded context.
EXPECT_LT(i, 0) << "This should always fail.";
}
}
// Tests using SCOPED_TRACE() and Google Test assertions in many threads
// concurrently.
TEST(StressTest, CanUseScopedTraceAndAssertionsInManyThreads) {
// TODO(wan): when Google Test is made thread-safe, run
// ManyAsserts() in many threads here.
}
} // namespace
} // namespace testing
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

106
test/gtest_test_utils.py Executable file
View File

@ -0,0 +1,106 @@
#!/usr/bin/env python
#
# 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.
"""Unit test utilities for Google C++ Testing Framework."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import sys
import unittest
# Initially maps a flag to its default value. After
# _ParseAndStripGTestFlags() is called, maps a flag to its actual
# value.
_flag_map = {'gtest_source_dir': os.path.dirname(sys.argv[0]),
'gtest_build_dir': os.path.dirname(sys.argv[0])}
_gtest_flags_are_parsed = False
def _ParseAndStripGTestFlags(argv):
"""Parses and strips Google Test flags from argv. This is idempotent."""
global _gtest_flags_are_parsed
if _gtest_flags_are_parsed:
return
_gtest_flags_are_parsed = True
for flag in _flag_map:
# The environment variable overrides the default value.
if flag.upper() in os.environ:
_flag_map[flag] = os.environ[flag.upper()]
# The command line flag overrides the environment variable.
i = 1 # Skips the program name.
while i < len(argv):
prefix = '--' + flag + '='
if argv[i].startswith(prefix):
_flag_map[flag] = argv[i][len(prefix):]
del argv[i]
break
else:
# We don't increment i in case we just found a --gtest_* flag
# and removed it from argv.
i += 1
def GetFlag(flag):
"""Returns the value of the given flag."""
# In case GetFlag() is called before Main(), we always call
# _ParseAndStripGTestFlags() here to make sure the --gtest_* flags
# are parsed.
_ParseAndStripGTestFlags(sys.argv)
return _flag_map[flag]
def GetSourceDir():
"""Returns the absolute path of the directory where the .py files are."""
return os.path.abspath(GetFlag('gtest_source_dir'))
def GetBuildDir():
"""Returns the absolute path of the directory where the test binaries are."""
return os.path.abspath(GetFlag('gtest_build_dir'))
def Main():
"""Runs the unit test."""
# We must call _ParseAndStripGTestFlags() before calling
# unittest.main(). Otherwise the latter will be confused by the
# --gtest_* flags.
_ParseAndStripGTestFlags(sys.argv)
unittest.main()

110
test/gtest_uninitialized_test.py Executable file
View File

@ -0,0 +1,110 @@
#!/usr/bin/env python
#
# 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.
"""Verifies that Google Test warns the user when not initialized properly."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import gtest_test_utils
import os
import sys
import unittest
IS_WINDOWS = os.name == 'nt'
IS_LINUX = os.name == 'posix'
if IS_WINDOWS:
BUILD_DIRS = [
'build.dbg\\',
'build.opt\\',
'build.dbg8\\',
'build.opt8\\',
]
COMMAND = 'gtest_uninitialized_test_.exe'
if IS_LINUX:
COMMAND = os.path.join(gtest_test_utils.GetBuildDir(),
'gtest_uninitialized_test_')
def Assert(condition):
if not condition:
raise AssertionError
def AssertEq(expected, actual):
if expected != actual:
print 'Expected: %s' % (expected,)
print ' Actual: %s' % (actual,)
raise AssertionError
def GetOutput(command):
"""Runs the given command and returns its output."""
stdin, stdout = os.popen2(command, 't')
stdin.close()
output = stdout.read()
stdout.close()
return output
def TestExitCodeAndOutput(command):
"""Runs the given command and verifies its exit code and output."""
# 256 corresponds to return code 0.
AssertEq(256, os.system(command))
output = GetOutput(command)
Assert('InitGoogleTest' in output)
if IS_WINDOWS:
def main():
for build_dir in BUILD_DIRS:
command = build_dir + COMMAND
print 'Testing with %s . . .' % (command,)
TestExitCodeAndOutput(command)
return 0
if __name__ == '__main__':
main()
if IS_LINUX:
class GTestUninitializedTest(unittest.TestCase):
def testExitCodeAndOutput(self):
TestExitCodeAndOutput(COMMAND)
if __name__ == '__main__':
gtest_test_utils.Main()

View File

@ -0,0 +1,43 @@
// 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.
//
// Author: wan@google.com (Zhanyong Wan)
#include <gtest/gtest.h>
TEST(DummyTest, Dummy) {
// This test doesn't verify anything. We just need it to create a
// realistic stage for testing the behavior of Google Test when
// RUN_ALL_TESTS() is called without testing::InitGoogleTest() being
// called first.
}
int main() {
return RUN_ALL_TESTS();
}

4299
test/gtest_unittest.cc Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,49 @@
// 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.
//
// Author: keith.ray@gmail.com (Keith Ray)
//
// gtest_xml_outfile1_test_ writes some xml via TestProperty used by
// gtest_xml_outfiles_test.py
#include <gtest/gtest.h>
class PropertyOne : public testing::Test {
protected:
virtual void SetUp() {
RecordProperty("SetUpProp", 1);
}
virtual void TearDown() {
RecordProperty("TearDownProp", 1);
}
};
TEST_F(PropertyOne, TestSomeProperties) {
RecordProperty("TestSomeProperty", 1);
}

View File

@ -0,0 +1,49 @@
// 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.
//
// Author: keith.ray@gmail.com (Keith Ray)
//
// gtest_xml_outfile2_test_ writes some xml via TestProperty used by
// gtest_xml_outfiles_test.py
#include <gtest/gtest.h>
class PropertyTwo : public testing::Test {
protected:
virtual void SetUp() {
RecordProperty("SetUpProp", 2);
}
virtual void TearDown() {
RecordProperty("TearDownProp", 2);
}
};
TEST_F(PropertyTwo, TestSomeProperties) {
RecordProperty("TestSomeProperty", 2);
}

134
test/gtest_xml_outfiles_test.py Executable file
View File

@ -0,0 +1,134 @@
#!/usr/bin/env python
#
# 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.
"""Unit test for the gtest_xml_output module."""
__author__ = "keith.ray@gmail.com (Keith Ray)"
import gtest_test_utils
import os
import sys
import tempfile
import unittest
from xml.dom import minidom, Node
import gtest_xml_test_utils
GTEST_OUTPUT_1_TEST = "gtest_xml_outfile1_test_"
GTEST_OUTPUT_2_TEST = "gtest_xml_outfile2_test_"
EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?>
<testsuite tests="1" failures="0" disabled="0" errors="0" time="*" name="AllTests">
<testsuite name="PropertyOne" tests="1" failures="0" disabled="0" errors="0" time="*">
<testcase name="TestSomeProperties" status="run" time="*" classname="PropertyOne" SetUpProp="1" TestSomeProperty="1" TearDownProp="1" />
</testsuite>
</testsuite>
"""
EXPECTED_XML_2 = """<?xml version="1.0" encoding="UTF-8"?>
<testsuite tests="1" failures="0" disabled="0" errors="0" time="*" name="AllTests">
<testsuite name="PropertyTwo" tests="1" failures="0" disabled="0" errors="0" time="*">
<testcase name="TestSomeProperties" status="run" time="*" classname="PropertyTwo" SetUpProp="2" TestSomeProperty="2" TearDownProp="2" />
</testsuite>
</testsuite>
"""
class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase):
"""Unit test for Google Test's XML output functionality."""
def setUp(self):
# We want the trailing '/' that the last "" provides in os.path.join, for
# telling Google Test to create an output directory instead of a single file
# for xml output.
self.output_dir_ = os.path.join(tempfile.mkdtemp(), "")
self.DeleteFilesAndDir()
def tearDown(self):
self.DeleteFilesAndDir()
def DeleteFilesAndDir(self):
try:
os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_1_TEST + ".xml"))
except os.error:
pass
try:
os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_2_TEST + ".xml"))
except os.error:
pass
try:
os.removedirs(self.output_dir_)
except os.error:
pass
def testOutfile1(self):
self._TestOutFile(GTEST_OUTPUT_1_TEST, EXPECTED_XML_1)
def testOutfile2(self):
self._TestOutFile(GTEST_OUTPUT_2_TEST, EXPECTED_XML_2)
def _TestOutFile(self, test_name, expected_xml):
gtest_prog_path = os.path.join(gtest_test_utils.GetBuildDir(),
test_name)
command = "cd %s && %s --gtest_output=xml:%s &> /dev/null" % (
tempfile.mkdtemp(), gtest_prog_path, self.output_dir_)
status = os.system(command)
self.assertEquals(0, status)
# TODO(wan@google.com): libtool causes the built test binary to be
# named lt-gtest_xml_outfiles_test_ instead of
# gtest_xml_outfiles_test_. To account for this possibillity, we
# allow both names in the following code. We should remove this
# hack when Chandler Carruth's libtool replacement tool is ready.
output_file_name1 = test_name + ".xml"
output_file1 = os.path.join(self.output_dir_, output_file_name1)
output_file_name2 = 'lt-' + output_file_name1
output_file2 = os.path.join(self.output_dir_, output_file_name2)
self.assert_(os.path.isfile(output_file1) or os.path.isfile(output_file2),
output_file1)
expected = minidom.parseString(expected_xml)
if os.path.isfile(output_file1):
actual = minidom.parse(output_file1)
else:
actual = minidom.parse(output_file2)
self._NormalizeXml(actual.documentElement)
self._AssertEquivalentElements(expected.documentElement,
actual.documentElement)
expected.unlink()
actual.unlink()
if __name__ == "__main__":
os.environ["GTEST_STACK_TRACE_DEPTH"] = "0"
gtest_test_utils.Main()

171
test/gtest_xml_output_unittest.py Executable file
View File

@ -0,0 +1,171 @@
#!/usr/bin/env python
#
# 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.
"""Unit test for the gtest_xml_output module"""
__author__ = 'eefacm@gmail.com (Sean Mcafee)'
import errno
import gtest_test_utils
import os
import sys
import tempfile
import unittest
from xml.dom import minidom, Node
import gtest_xml_test_utils
GTEST_OUTPUT_FLAG = "--gtest_output"
GTEST_DEFAULT_OUTPUT_FILE = "test_detail.xml"
EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuite tests="13" failures="2" disabled="2" errors="0" time="*" name="AllTests">
<testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*">
<testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/>
</testsuite>
<testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*">
<testcase name="Fails" status="run" time="*" classname="FailedTest">
<failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 2&#x0A;Expected: 1" type=""/>
</testcase>
</testsuite>
<testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*">
<testcase name="Succeeds" status="run" time="*" classname="MixedResultTest"/>
<testcase name="Fails" status="run" time="*" classname="MixedResultTest">
<failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 2&#x0A;Expected: 1" type=""/>
<failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 3&#x0A;Expected: 2" type=""/>
</testcase>
<testcase name="DISABLED_test" status="notrun" time="*" classname="MixedResultTest"/>
</testsuite>
<testsuite name="DisabledTest" tests="1" failures="0" disabled="1" errors="0" time="*">
<testcase name="DISABLED_test_not_run" status="notrun" time="*" classname="DisabledTest"/>
</testsuite>
<testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*">
<testcase name="OneProperty" status="run" time="*" classname="PropertyRecordingTest" key_1="1"/>
<testcase name="IntValuedProperty" status="run" time="*" classname="PropertyRecordingTest" key_int="1"/>
<testcase name="ThreeProperties" status="run" time="*" classname="PropertyRecordingTest" key_1="1" key_2="2" key_3="3"/>
<testcase name="TwoValuesForOneKeyUsesLastValue" status="run" time="*" classname="PropertyRecordingTest" key_1="2"/>
</testsuite>
<testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*">
<testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest" key="1"/>
<testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_int="1"/>
<testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_string="1"/>
</testsuite>
</testsuite>"""
EXPECTED_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuite tests="0" failures="0" disabled="0" errors="0" time="*" name="AllTests">
</testsuite>"""
class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
"""
Unit test for Google Test's XML output functionality.
"""
def testNonEmptyXmlOutput(self):
"""
Runs a test program that generates a non-empty XML output, and
tests that the XML output is expected.
"""
self._TestXmlOutput("gtest_xml_output_unittest_",
EXPECTED_NON_EMPTY_XML, 1)
def testEmptyXmlOutput(self):
"""
Runs a test program that generates an empty XML output, and
tests that the XML output is expected.
"""
self._TestXmlOutput("gtest_no_test_unittest",
EXPECTED_EMPTY_XML, 0)
def testDefaultOutputFile(self):
"""
Confirms that Google Test produces an XML output file with the expected
default name if no name is explicitly specified.
"""
temp_dir = tempfile.mkdtemp()
output_file = os.path.join(temp_dir,
GTEST_DEFAULT_OUTPUT_FILE)
gtest_prog_path = os.path.join(gtest_test_utils.GetBuildDir(),
"gtest_no_test_unittest")
try:
os.remove(output_file)
except OSError, e:
if e.errno != errno.ENOENT:
raise
status = os.system("cd %s && %s %s=xml &> /dev/null"
% (temp_dir, gtest_prog_path,
GTEST_OUTPUT_FLAG))
self.assertEquals(0, status)
self.assert_(os.path.isfile(output_file))
def _TestXmlOutput(self, gtest_prog_name, expected_xml, expected_exit_code):
"""
Asserts that the XML document generated by running the program
gtest_prog_name matches expected_xml, a string containing another
XML document. Furthermore, the program's exit code must be
expected_exit_code.
"""
xml_path = os.path.join(tempfile.mkdtemp(), gtest_prog_name + "out.xml")
gtest_prog_path = os.path.join(gtest_test_utils.GetBuildDir(),
gtest_prog_name)
command = ("%s %s=xml:%s &> /dev/null"
% (gtest_prog_path, GTEST_OUTPUT_FLAG, xml_path))
status = os.system(command)
signal = status & 0xff
self.assertEquals(0, signal,
"%s was killed by signal %d" % (gtest_prog_name, signal))
exit_code = status >> 8
self.assertEquals(expected_exit_code, exit_code,
"'%s' exited with code %s, which doesn't match "
"the expected exit code %s."
% (command, exit_code, expected_exit_code))
expected = minidom.parseString(expected_xml)
actual = minidom.parse(xml_path)
self._NormalizeXml(actual.documentElement)
self._AssertEquivalentElements(expected.documentElement,
actual.documentElement)
expected.unlink()
actual .unlink()
if __name__ == '__main__':
os.environ['GTEST_STACK_TRACE_DEPTH'] = '0'
gtest_test_utils.Main()

View File

@ -0,0 +1,120 @@
// 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.
// Author: eefacm@gmail.com (Sean Mcafee)
// Unit test for Google Test XML output.
//
// A user can specify XML output in a Google Test program to run via
// either the GTEST_OUTPUT environment variable or the --gtest_output
// flag. This is used for testing such functionality.
//
// This program will be invoked from a Python unit test. Don't run it
// directly.
#include <gtest/gtest.h>
class SuccessfulTest : public testing::Test {
};
TEST_F(SuccessfulTest, Succeeds) {
SUCCEED() << "This is a success.";
ASSERT_EQ(1, 1);
}
class FailedTest : public testing::Test {
};
TEST_F(FailedTest, Fails) {
ASSERT_EQ(1, 2);
}
class DisabledTest : public testing::Test {
};
TEST_F(DisabledTest, DISABLED_test_not_run) {
FAIL() << "Unexpected failure: Disabled test should not be run";
}
TEST(MixedResultTest, Succeeds) {
EXPECT_EQ(1, 1);
ASSERT_EQ(1, 1);
}
TEST(MixedResultTest, Fails) {
EXPECT_EQ(1, 2);
ASSERT_EQ(2, 3);
}
TEST(MixedResultTest, DISABLED_test) {
FAIL() << "Unexpected failure: Disabled test should not be run";
}
class PropertyRecordingTest : public testing::Test {
};
TEST_F(PropertyRecordingTest, OneProperty) {
RecordProperty("key_1", "1");
}
TEST_F(PropertyRecordingTest, IntValuedProperty) {
RecordProperty("key_int", 1);
}
TEST_F(PropertyRecordingTest, ThreeProperties) {
RecordProperty("key_1", "1");
RecordProperty("key_2", "2");
RecordProperty("key_3", "3");
}
TEST_F(PropertyRecordingTest, TwoValuesForOneKeyUsesLastValue) {
RecordProperty("key_1", "1");
RecordProperty("key_1", "2");
}
TEST(NoFixtureTest, RecordProperty) {
RecordProperty("key", "1");
}
void ExternalUtilityThatCallsRecordProperty(const char* key, int value) {
testing::Test::RecordProperty(key, value);
}
void ExternalUtilityThatCallsRecordProperty(const char* key,
const char* value) {
testing::Test::RecordProperty(key, value);
}
TEST(NoFixtureTest, ExternalUtilityThatCallsRecordIntValuedProperty) {
ExternalUtilityThatCallsRecordProperty("key_for_utility_int", 1);
}
TEST(NoFixtureTest, ExternalUtilityThatCallsRecordStringValuedProperty) {
ExternalUtilityThatCallsRecordProperty("key_for_utility_string", "1");
}

138
test/gtest_xml_test_utils.py Executable file
View File

@ -0,0 +1,138 @@
#!/usr/bin/env python
#
# 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.
"""Unit test utilities for gtest_xml_output"""
__author__ = 'eefacm@gmail.com (Sean Mcafee)'
import re
import unittest
from xml.dom import minidom, Node
GTEST_OUTPUT_FLAG = "--gtest_output"
GTEST_DEFAULT_OUTPUT_FILE = "test_detail.xml"
class GTestXMLTestCase(unittest.TestCase):
"""
Base class for tests of Google Test's XML output functionality.
"""
def _AssertEquivalentElements(self, expected_element, actual_element):
"""
Asserts that actual_element (a DOM element object) is equivalent to
expected_element (another DOM element object), in that it meets all
of the following conditions:
* It has the same tag name as expected_element.
* It has the same set of attributes as expected_element, each with
the same value as the corresponding attribute of expected_element.
An exception is any attribute named "time", which need only be
convertible to a long integer.
* Each child element is equivalent to a child element of
expected_element. Child elements are matched according to an
attribute that varies depending on the element; "name" for
<testsuite> and <testcase> elements, "message" for <failure>
elements. This matching is necessary because child elements are
not guaranteed to be ordered in any particular way.
"""
self.assertEquals(expected_element.tagName, actual_element.tagName)
expected_attributes = expected_element.attributes
actual_attributes = actual_element .attributes
self.assertEquals(expected_attributes.length, actual_attributes.length)
for i in range(expected_attributes.length):
expected_attr = expected_attributes.item(i)
actual_attr = actual_attributes.get(expected_attr.name)
self.assert_(actual_attr is not None)
self.assertEquals(expected_attr.value, actual_attr.value)
expected_child = self._GetChildElements(expected_element)
actual_child = self._GetChildElements(actual_element)
self.assertEquals(len(expected_child), len(actual_child))
for child_id, element in expected_child.iteritems():
self.assert_(child_id in actual_child,
'<%s> is not in <%s>' % (child_id, actual_child))
self._AssertEquivalentElements(element, actual_child[child_id])
identifying_attribute = {
"testsuite": "name",
"testcase": "name",
"failure": "message",
}
def _GetChildElements(self, element):
"""
Fetches all of the Element type child nodes of element, a DOM
Element object. Returns them as the values of a dictionary keyed by
the value of one of the node's attributes. For <testsuite> and
<testcase> elements, the identifying attribute is "name"; for
<failure> elements, it is "message". An exception is raised if
any element other than the above three is encountered, if two
child elements with the same identifying attributes are encountered,
or if any other type of node is encountered, other than Text nodes
containing only whitespace.
"""
children = {}
for child in element.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
self.assert_(child.tagName in self.identifying_attribute,
"Encountered unknown element <%s>" % child.tagName)
childID = child.getAttribute(self.identifying_attribute[child.tagName])
self.assert_(childID not in children)
children[childID] = child
elif child.nodeType == Node.TEXT_NODE:
self.assert_(child.nodeValue.isspace())
else:
self.fail("Encountered unexpected node type %d" % child.nodeType)
return children
def _NormalizeXml(self, element):
"""
Normalizes Google Test's XML output to eliminate references to transient
information that may change from run to run.
* The "time" attribute of <testsuite> and <testcase> elements is
replaced with a single asterisk, if it contains only digit
characters.
* The line number reported in the first line of the "message"
attribute of <failure> elements is replaced with a single asterisk.
* The directory names in file paths are removed.
"""
if element.tagName in ("testsuite", "testcase"):
time = element.getAttributeNode("time")
time.value = re.sub(r"^\d+$", "*", time.value)
elif element.tagName == "failure":
message = element.getAttributeNode("message")
message.value = re.sub(r"^.*/(.*:)\d+\n", "\\1*\n", message.value)
for child in element.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
self._NormalizeXml(child)

36
test/production.cc Normal file
View File

@ -0,0 +1,36 @@
// 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.
//
// Author: wan@google.com (Zhanyong Wan)
//
// This is part of the unit test for include/gtest/gtest_prod.h.
#include "production.h"
PrivateCode::PrivateCode() : x_(0) {}

55
test/production.h Normal file
View File

@ -0,0 +1,55 @@
// 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.
//
// Author: wan@google.com (Zhanyong Wan)
//
// This is part of the unit test for include/gtest/gtest_prod.h.
#ifndef GTEST_TEST_PRODUCTION_H_
#define GTEST_TEST_PRODUCTION_H_
#include <gtest/gtest_prod.h>
class PrivateCode {
public:
// Declares a friend test that does not use a fixture.
FRIEND_TEST(PrivateCodeTest, CanAccessPrivateMembers);
// Declares a friend test that uses a fixture.
FRIEND_TEST(PrivateCodeFixtureTest, CanAccessPrivateMembers);
PrivateCode();
int x() const { return x_; }
private:
void set_x(int x) { x_ = x; }
int x_;
};
#endif // GTEST_TEST_PRODUCTION_H_