From 8dea630e88560874eeb18b09bf3ad112e15bacab Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 1 Aug 2018 17:06:17 -0400 Subject: various changes to tests --- googletest/test/BUILD.bazel | 56 +- googletest/test/googletest-death-test_ex_test.cc | 93 ++ .../googletest-param-test-invalid-name1-test.py | 72 ++ .../googletest-param-test-invalid-name1-test_.cc | 51 + .../googletest-param-test-invalid-name2-test.py | 71 ++ .../googletest-param-test-invalid-name2-test_.cc | 56 + googletest/test/googletest-param-test-test.cc | 1110 ++++++++++++++++++++ googletest/test/googletest-param-test-test.h | 53 + googletest/test/googletest-param-test2-test.cc | 61 ++ googletest/test/googletest-test-part-test.cc | 208 ++++ googletest/test/googletest-test2_test.cc | 61 ++ googletest/test/gtest-death-test_ex_test.cc | 93 -- googletest/test/gtest-param-test2_test.cc | 61 -- googletest/test/gtest-param-test_test.cc | 1110 -------------------- googletest/test/gtest-param-test_test.h | 53 - googletest/test/gtest-test-part_test.cc | 208 ---- googletest/test/gtest_all_test.cc | 12 +- googletest/test/gtest_json_outfiles_test.py | 162 --- googletest/test/gtest_json_output_unittest.py | 611 ----------- googletest/test/gtest_uninitialized_test_.cc | 43 - 20 files changed, 1891 insertions(+), 2354 deletions(-) create mode 100644 googletest/test/googletest-death-test_ex_test.cc create mode 100644 googletest/test/googletest-param-test-invalid-name1-test.py create mode 100644 googletest/test/googletest-param-test-invalid-name1-test_.cc create mode 100644 googletest/test/googletest-param-test-invalid-name2-test.py create mode 100644 googletest/test/googletest-param-test-invalid-name2-test_.cc create mode 100644 googletest/test/googletest-param-test-test.cc create mode 100644 googletest/test/googletest-param-test-test.h create mode 100644 googletest/test/googletest-param-test2-test.cc create mode 100644 googletest/test/googletest-test-part-test.cc create mode 100644 googletest/test/googletest-test2_test.cc delete mode 100644 googletest/test/gtest-death-test_ex_test.cc delete mode 100644 googletest/test/gtest-param-test2_test.cc delete mode 100644 googletest/test/gtest-param-test_test.cc delete mode 100644 googletest/test/gtest-param-test_test.h delete mode 100644 googletest/test/gtest-test-part_test.cc delete mode 100644 googletest/test/gtest_json_outfiles_test.py delete mode 100644 googletest/test/gtest_json_output_unittest.py delete mode 100644 googletest/test/gtest_uninitialized_test_.cc diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index a5c6b14..3f6d466 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -79,6 +79,11 @@ cc_test( "googletest-list-tests-unittest_.cc", "googletest-shuffle-test_.cc", "googletest-uninitialized-test_.cc", + "googletest-death-test_ex_test.cc", + "googletest-param-test-test", + "googletest-throw-on-failure-test_.cc", + "googletest-param-test-invalid-name1-test_.cc", + "googletest-param-test-invalid-name2-test_.cc", ], ) + select({ @@ -145,16 +150,14 @@ cc_test( ) cc_test( - name = "gtest-param-test_test", + name = "googletest-param-test-test", size = "small", srcs = [ - "gtest-param-test2_test.cc", - "gtest-param-test_test.cc", - "gtest-param-test_test.h", - ], - deps = [ - "//:gtest", + "googletest-param-test-test.cc", + "googletest-param-test-test.h", + "googletest-param-test2-test.cc", ], + deps = ["//:gtest"], ) cc_test( @@ -483,3 +486,42 @@ py_test( }), deps = [":gtest_test_utils"], ) +# Verifies interaction of death tests and exceptions. +cc_test( + name = "googletest-death-test_ex_catch_test", + size = "medium", + srcs = ["googletest-death-test_ex_test.cc"], + copts = ["-fexceptions"], + defines = ["GTEST_ENABLE_CATCH_EXCEPTIONS_=1"], + deps = ["//:gtest"], +) + +cc_binary( + name = "googletest-param-test-invalid-name1-test_", + testonly = 1, + srcs = ["googletest-param-test-invalid-name1-test_.cc"], + deps = ["//:gtest"], +) + +cc_binary( + name = "googletest-param-test-invalid-name2-test_", + testonly = 1, + srcs = ["googletest-param-test-invalid-name2-test_.cc"], + deps = ["//:gtest"], +) + +py_test( + name = "googletest-param-test-invalid-name1-test", + size = "small", + srcs = ["googletest-param-test-invalid-name1-test.py"], + data = [":googletest-param-test-invalid-name1-test_"], + deps = [":gtest_test_utils"], +) + +py_test( + name = "googletest-param-test-invalid-name2-test", + size = "small", + srcs = ["googletest-param-test-invalid-name2-test.py"], + data = [":googletest-param-test-invalid-name2-test_"], + deps = [":gtest_test_utils"], +) diff --git a/googletest/test/googletest-death-test_ex_test.cc b/googletest/test/googletest-death-test_ex_test.cc new file mode 100644 index 0000000..3391074 --- /dev/null +++ b/googletest/test/googletest-death-test_ex_test.cc @@ -0,0 +1,93 @@ +// Copyright 2010, 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: vladl@google.com (Vlad Losev) +// +// Tests that verify interaction of exceptions and death tests. + +#include "gtest/gtest-death-test.h" +#include "gtest/gtest.h" + +#if GTEST_HAS_DEATH_TEST + +# if GTEST_HAS_SEH +# include // For RaiseException(). +# endif + +# include "gtest/gtest-spi.h" + +# if GTEST_HAS_EXCEPTIONS + +# include // For std::exception. + +// Tests that death tests report thrown exceptions as failures and that the +// exceptions do not escape death test macros. +TEST(CxxExceptionDeathTest, ExceptionIsFailure) { + try { + EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw 1, ""), "threw an exception"); + } catch (...) { // NOLINT + FAIL() << "An exception escaped a death test macro invocation " + << "with catch_exceptions " + << (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled"); + } +} + +class TestException : public std::exception { + public: + virtual const char* what() const throw() { return "exceptional message"; } +}; + +TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) { + // Verifies that the exception message is quoted in the failure text. + EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), + "exceptional message"); + // Verifies that the location is mentioned in the failure text. + EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), + "googletest-death-test_ex_test.cc"); +} +# endif // GTEST_HAS_EXCEPTIONS + +# if GTEST_HAS_SEH +// Tests that enabling interception of SEH exceptions with the +// catch_exceptions flag does not interfere with SEH exceptions being +// treated as death by death tests. +TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) { + EXPECT_DEATH(RaiseException(42, 0x0, 0, NULL), "") + << "with catch_exceptions " + << (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled"); +} +# endif + +#endif // GTEST_HAS_DEATH_TEST + +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + testing::GTEST_FLAG(catch_exceptions) = GTEST_ENABLE_CATCH_EXCEPTIONS_ != 0; + return RUN_ALL_TESTS(); +} diff --git a/googletest/test/googletest-param-test-invalid-name1-test.py b/googletest/test/googletest-param-test-invalid-name1-test.py new file mode 100644 index 0000000..63be043 --- /dev/null +++ b/googletest/test/googletest-param-test-invalid-name1-test.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python +# +# Copyright 2015 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__ = 'jmadill@google.com (Jamie Madill)' + +import os + +IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' + +if IS_LINUX: + import gtest_test_utils +else: + import gtest_test_utils + +binary_name = 'googletest-param-test-invalid-name1-test_' +COMMAND = gtest_test_utils.GetTestExecutablePath(binary_name) + + +def Assert(condition): + if not condition: + raise AssertionError + + +def TestExitCodeAndOutput(command): + """Runs the given command and verifies its exit code and output.""" + + err = ('Parameterized test name \'"InvalidWithQuotes"\' is invalid') + + p = gtest_test_utils.Subprocess(command) + Assert(p.terminated_by_signal) + + # Verify the output message contains appropriate output + Assert(err in p.output) + + +class GTestParamTestInvalidName1Test(gtest_test_utils.TestCase): + + def testExitCodeAndOutput(self): + TestExitCodeAndOutput(COMMAND) + + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/googletest/test/googletest-param-test-invalid-name1-test_.cc b/googletest/test/googletest-param-test-invalid-name1-test_.cc new file mode 100644 index 0000000..68dd470 --- /dev/null +++ b/googletest/test/googletest-param-test-invalid-name1-test_.cc @@ -0,0 +1,51 @@ +// Copyright 2015, 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: jmadill@google.com (Jamie Madill) + +#include "gtest/gtest.h" + +namespace { +class DummyTest : public ::testing::TestWithParam {}; + +TEST_P(DummyTest, Dummy) { +} + +INSTANTIATE_TEST_CASE_P(InvalidTestName, + DummyTest, + ::testing::Values("InvalidWithQuotes"), + ::testing::PrintToStringParamName()); + +} // namespace + +int main(int argc, char *argv[]) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} + diff --git a/googletest/test/googletest-param-test-invalid-name2-test.py b/googletest/test/googletest-param-test-invalid-name2-test.py new file mode 100644 index 0000000..b1a80c1 --- /dev/null +++ b/googletest/test/googletest-param-test-invalid-name2-test.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2015 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__ = 'jmadill@google.com (Jamie Madill)' + +import os + +IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' + +if IS_LINUX: + import gtest_test_utils +else: + import gtest_test_utils + +binary_name = 'googletest-param-test-invalid-name2-test_' +COMMAND = gtest_test_utils.GetTestExecutablePath(binary_name) + + +def Assert(condition): + if not condition: + raise AssertionError + + +def TestExitCodeAndOutput(command): + """Runs the given command and verifies its exit code and output.""" + + err = ('Duplicate parameterized test name \'a\'') + + p = gtest_test_utils.Subprocess(command) + Assert(p.terminated_by_signal) + + # Check for appropriate output + Assert(err in p.output) + + +class GTestParamTestInvalidName2Test(gtest_test_utils.TestCase): + + def testExitCodeAndOutput(self): + TestExitCodeAndOutput(COMMAND) + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/googletest/test/googletest-param-test-invalid-name2-test_.cc b/googletest/test/googletest-param-test-invalid-name2-test_.cc new file mode 100644 index 0000000..9a8ec4e --- /dev/null +++ b/googletest/test/googletest-param-test-invalid-name2-test_.cc @@ -0,0 +1,56 @@ +// Copyright 2015, 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: jmadill@google.com (Jamie Madill) + +#include "gtest/gtest.h" + +namespace { +class DummyTest : public ::testing::TestWithParam {}; + +std::string StringParamTestSuffix( + const testing::TestParamInfo& info) { + return std::string(info.param); +} + +TEST_P(DummyTest, Dummy) { +} + +INSTANTIATE_TEST_CASE_P(DuplicateTestNames, + DummyTest, + ::testing::Values("a", "b", "a", "c"), + StringParamTestSuffix); +} // namespace + +int main(int argc, char *argv[]) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} + + diff --git a/googletest/test/googletest-param-test-test.cc b/googletest/test/googletest-param-test-test.cc new file mode 100644 index 0000000..893b132 --- /dev/null +++ b/googletest/test/googletest-param-test-test.cc @@ -0,0 +1,1110 @@ +// 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: vladl@google.com (Vlad Losev) +// +// Tests for Google Test itself. This file verifies that the parameter +// generators objects produce correct parameter sequences and that +// Google Test runtime instantiates correct tests from those sequences. + +#include "gtest/gtest.h" + +# include +# include +# include +# include +# include +# include + +# include "src/gtest-internal-inl.h" // for UnitTestOptions +# include "test/googletest-param-test-test.h" + +using ::std::vector; +using ::std::sort; + +using ::testing::AddGlobalTestEnvironment; +using ::testing::Bool; +using ::testing::Message; +using ::testing::Range; +using ::testing::TestWithParam; +using ::testing::Values; +using ::testing::ValuesIn; + +# if GTEST_HAS_COMBINE +using ::testing::Combine; +using ::testing::get; +using ::testing::make_tuple; +using ::testing::tuple; +# endif // GTEST_HAS_COMBINE + +using ::testing::internal::ParamGenerator; +using ::testing::internal::UnitTestOptions; + +// Prints a value to a string. +// +// TODO(wan@google.com): remove PrintValue() when we move matchers and +// EXPECT_THAT() from Google Mock to Google Test. At that time, we +// can write EXPECT_THAT(x, Eq(y)) to compare two tuples x and y, as +// EXPECT_THAT() and the matchers know how to print tuples. +template +::std::string PrintValue(const T& value) { + ::std::stringstream stream; + stream << value; + return stream.str(); +} + +# if GTEST_HAS_COMBINE + +// These overloads allow printing tuples in our tests. We cannot +// define an operator<< for tuples, as that definition needs to be in +// the std namespace in order to be picked up by Google Test via +// Argument-Dependent Lookup, yet defining anything in the std +// namespace in non-STL code is undefined behavior. + +template +::std::string PrintValue(const tuple& value) { + ::std::stringstream stream; + stream << "(" << get<0>(value) << ", " << get<1>(value) << ")"; + return stream.str(); +} + +template +::std::string PrintValue(const tuple& value) { + ::std::stringstream stream; + stream << "(" << get<0>(value) << ", " << get<1>(value) + << ", "<< get<2>(value) << ")"; + return stream.str(); +} + +template +::std::string PrintValue( + const tuple& value) { + ::std::stringstream stream; + stream << "(" << get<0>(value) << ", " << get<1>(value) + << ", "<< get<2>(value) << ", " << get<3>(value) + << ", "<< get<4>(value) << ", " << get<5>(value) + << ", "<< get<6>(value) << ", " << get<7>(value) + << ", "<< get<8>(value) << ", " << get<9>(value) << ")"; + return stream.str(); +} + +# endif // GTEST_HAS_COMBINE + +// Verifies that a sequence generated by the generator and accessed +// via the iterator object matches the expected one using Google Test +// assertions. +template +void VerifyGenerator(const ParamGenerator& generator, + const T (&expected_values)[N]) { + typename ParamGenerator::iterator it = generator.begin(); + for (size_t i = 0; i < N; ++i) { + ASSERT_FALSE(it == generator.end()) + << "At element " << i << " when accessing via an iterator " + << "created with the copy constructor.\n"; + // We cannot use EXPECT_EQ() here as the values may be tuples, + // which don't support <<. + EXPECT_TRUE(expected_values[i] == *it) + << "where i is " << i + << ", expected_values[i] is " << PrintValue(expected_values[i]) + << ", *it is " << PrintValue(*it) + << ", and 'it' is an iterator created with the copy constructor.\n"; + ++it; + } + EXPECT_TRUE(it == generator.end()) + << "At the presumed end of sequence when accessing via an iterator " + << "created with the copy constructor.\n"; + + // Test the iterator assignment. The following lines verify that + // the sequence accessed via an iterator initialized via the + // assignment operator (as opposed to a copy constructor) matches + // just the same. + it = generator.begin(); + for (size_t i = 0; i < N; ++i) { + ASSERT_FALSE(it == generator.end()) + << "At element " << i << " when accessing via an iterator " + << "created with the assignment operator.\n"; + EXPECT_TRUE(expected_values[i] == *it) + << "where i is " << i + << ", expected_values[i] is " << PrintValue(expected_values[i]) + << ", *it is " << PrintValue(*it) + << ", and 'it' is an iterator created with the copy constructor.\n"; + ++it; + } + EXPECT_TRUE(it == generator.end()) + << "At the presumed end of sequence when accessing via an iterator " + << "created with the assignment operator.\n"; +} + +template +void VerifyGeneratorIsEmpty(const ParamGenerator& generator) { + typename ParamGenerator::iterator it = generator.begin(); + EXPECT_TRUE(it == generator.end()); + + it = generator.begin(); + EXPECT_TRUE(it == generator.end()); +} + +// Generator tests. They test that each of the provided generator functions +// generates an expected sequence of values. The general test pattern +// instantiates a generator using one of the generator functions, +// checks the sequence produced by the generator using its iterator API, +// and then resets the iterator back to the beginning of the sequence +// and checks the sequence again. + +// Tests that iterators produced by generator functions conform to the +// ForwardIterator concept. +TEST(IteratorTest, ParamIteratorConformsToForwardIteratorConcept) { + const ParamGenerator gen = Range(0, 10); + ParamGenerator::iterator it = gen.begin(); + + // Verifies that iterator initialization works as expected. + ParamGenerator::iterator it2 = it; + EXPECT_TRUE(*it == *it2) << "Initialized iterators must point to the " + << "element same as its source points to"; + + // Verifies that iterator assignment works as expected. + ++it; + EXPECT_FALSE(*it == *it2); + it2 = it; + EXPECT_TRUE(*it == *it2) << "Assigned iterators must point to the " + << "element same as its source points to"; + + // Verifies that prefix operator++() returns *this. + EXPECT_EQ(&it, &(++it)) << "Result of the prefix operator++ must be " + << "refer to the original object"; + + // Verifies that the result of the postfix operator++ points to the value + // pointed to by the original iterator. + int original_value = *it; // Have to compute it outside of macro call to be + // unaffected by the parameter evaluation order. + EXPECT_EQ(original_value, *(it++)); + + // Verifies that prefix and postfix operator++() advance an iterator + // all the same. + it2 = it; + ++it; + ++it2; + EXPECT_TRUE(*it == *it2); +} + +// Tests that Range() generates the expected sequence. +TEST(RangeTest, IntRangeWithDefaultStep) { + const ParamGenerator gen = Range(0, 3); + const int expected_values[] = {0, 1, 2}; + VerifyGenerator(gen, expected_values); +} + +// Edge case. Tests that Range() generates the single element sequence +// as expected when provided with range limits that are equal. +TEST(RangeTest, IntRangeSingleValue) { + const ParamGenerator gen = Range(0, 1); + const int expected_values[] = {0}; + VerifyGenerator(gen, expected_values); +} + +// Edge case. Tests that Range() with generates empty sequence when +// supplied with an empty range. +TEST(RangeTest, IntRangeEmpty) { + const ParamGenerator gen = Range(0, 0); + VerifyGeneratorIsEmpty(gen); +} + +// Tests that Range() with custom step (greater then one) generates +// the expected sequence. +TEST(RangeTest, IntRangeWithCustomStep) { + const ParamGenerator gen = Range(0, 9, 3); + const int expected_values[] = {0, 3, 6}; + VerifyGenerator(gen, expected_values); +} + +// Tests that Range() with custom step (greater then one) generates +// the expected sequence when the last element does not fall on the +// upper range limit. Sequences generated by Range() must not have +// elements beyond the range limits. +TEST(RangeTest, IntRangeWithCustomStepOverUpperBound) { + const ParamGenerator gen = Range(0, 4, 3); + const int expected_values[] = {0, 3}; + VerifyGenerator(gen, expected_values); +} + +// Verifies that Range works with user-defined types that define +// copy constructor, operator=(), operator+(), and operator<(). +class DogAdder { + public: + explicit DogAdder(const char* a_value) : value_(a_value) {} + DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {} + + DogAdder operator=(const DogAdder& other) { + if (this != &other) + value_ = other.value_; + return *this; + } + DogAdder operator+(const DogAdder& other) const { + Message msg; + msg << value_.c_str() << other.value_.c_str(); + return DogAdder(msg.GetString().c_str()); + } + bool operator<(const DogAdder& other) const { + return value_ < other.value_; + } + const std::string& value() const { return value_; } + + private: + std::string value_; +}; + +TEST(RangeTest, WorksWithACustomType) { + const ParamGenerator gen = + Range(DogAdder("cat"), DogAdder("catdogdog"), DogAdder("dog")); + ParamGenerator::iterator it = gen.begin(); + + ASSERT_FALSE(it == gen.end()); + EXPECT_STREQ("cat", it->value().c_str()); + + ASSERT_FALSE(++it == gen.end()); + EXPECT_STREQ("catdog", it->value().c_str()); + + EXPECT_TRUE(++it == gen.end()); +} + +class IntWrapper { + public: + explicit IntWrapper(int a_value) : value_(a_value) {} + IntWrapper(const IntWrapper& other) : value_(other.value_) {} + + IntWrapper operator=(const IntWrapper& other) { + value_ = other.value_; + return *this; + } + // operator+() adds a different type. + IntWrapper operator+(int other) const { return IntWrapper(value_ + other); } + bool operator<(const IntWrapper& other) const { + return value_ < other.value_; + } + int value() const { return value_; } + + private: + int value_; +}; + +TEST(RangeTest, WorksWithACustomTypeWithDifferentIncrementType) { + const ParamGenerator gen = Range(IntWrapper(0), IntWrapper(2)); + ParamGenerator::iterator it = gen.begin(); + + ASSERT_FALSE(it == gen.end()); + EXPECT_EQ(0, it->value()); + + ASSERT_FALSE(++it == gen.end()); + EXPECT_EQ(1, it->value()); + + EXPECT_TRUE(++it == gen.end()); +} + +// Tests that ValuesIn() with an array parameter generates +// the expected sequence. +TEST(ValuesInTest, ValuesInArray) { + int array[] = {3, 5, 8}; + const ParamGenerator gen = ValuesIn(array); + VerifyGenerator(gen, array); +} + +// Tests that ValuesIn() with a const array parameter generates +// the expected sequence. +TEST(ValuesInTest, ValuesInConstArray) { + const int array[] = {3, 5, 8}; + const ParamGenerator gen = ValuesIn(array); + VerifyGenerator(gen, array); +} + +// Edge case. Tests that ValuesIn() with an array parameter containing a +// single element generates the single element sequence. +TEST(ValuesInTest, ValuesInSingleElementArray) { + int array[] = {42}; + const ParamGenerator gen = ValuesIn(array); + VerifyGenerator(gen, array); +} + +// Tests that ValuesIn() generates the expected sequence for an STL +// container (vector). +TEST(ValuesInTest, ValuesInVector) { + typedef ::std::vector ContainerType; + ContainerType values; + values.push_back(3); + values.push_back(5); + values.push_back(8); + const ParamGenerator gen = ValuesIn(values); + + const int expected_values[] = {3, 5, 8}; + VerifyGenerator(gen, expected_values); +} + +// Tests that ValuesIn() generates the expected sequence. +TEST(ValuesInTest, ValuesInIteratorRange) { + typedef ::std::vector ContainerType; + ContainerType values; + values.push_back(3); + values.push_back(5); + values.push_back(8); + const ParamGenerator gen = ValuesIn(values.begin(), values.end()); + + const int expected_values[] = {3, 5, 8}; + VerifyGenerator(gen, expected_values); +} + +// Edge case. Tests that ValuesIn() provided with an iterator range specifying a +// single value generates a single-element sequence. +TEST(ValuesInTest, ValuesInSingleElementIteratorRange) { + typedef ::std::vector ContainerType; + ContainerType values; + values.push_back(42); + const ParamGenerator gen = ValuesIn(values.begin(), values.end()); + + const int expected_values[] = {42}; + VerifyGenerator(gen, expected_values); +} + +// Edge case. Tests that ValuesIn() provided with an empty iterator range +// generates an empty sequence. +TEST(ValuesInTest, ValuesInEmptyIteratorRange) { + typedef ::std::vector ContainerType; + ContainerType values; + const ParamGenerator gen = ValuesIn(values.begin(), values.end()); + + VerifyGeneratorIsEmpty(gen); +} + +// Tests that the Values() generates the expected sequence. +TEST(ValuesTest, ValuesWorks) { + const ParamGenerator gen = Values(3, 5, 8); + + const int expected_values[] = {3, 5, 8}; + VerifyGenerator(gen, expected_values); +} + +// Tests that Values() generates the expected sequences from elements of +// different types convertible to ParamGenerator's parameter type. +TEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) { + const ParamGenerator gen = Values(3, 5.0f, 8.0); + + const double expected_values[] = {3.0, 5.0, 8.0}; + VerifyGenerator(gen, expected_values); +} + +TEST(ValuesTest, ValuesWorksForMaxLengthList) { + const ParamGenerator gen = Values( + 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, + 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, + 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, + 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, + 410, 420, 430, 440, 450, 460, 470, 480, 490, 500); + + const int expected_values[] = { + 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, + 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, + 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, + 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, + 410, 420, 430, 440, 450, 460, 470, 480, 490, 500}; + VerifyGenerator(gen, expected_values); +} + +// Edge case test. Tests that single-parameter Values() generates the sequence +// with the single value. +TEST(ValuesTest, ValuesWithSingleParameter) { + const ParamGenerator gen = Values(42); + + const int expected_values[] = {42}; + VerifyGenerator(gen, expected_values); +} + +// Tests that Bool() generates sequence (false, true). +TEST(BoolTest, BoolWorks) { + const ParamGenerator gen = Bool(); + + const bool expected_values[] = {false, true}; + VerifyGenerator(gen, expected_values); +} + +# if GTEST_HAS_COMBINE + +// Tests that Combine() with two parameters generates the expected sequence. +TEST(CombineTest, CombineWithTwoParameters) { + const char* foo = "foo"; + const char* bar = "bar"; + const ParamGenerator > gen = + Combine(Values(foo, bar), Values(3, 4)); + + tuple expected_values[] = { + make_tuple(foo, 3), make_tuple(foo, 4), + make_tuple(bar, 3), make_tuple(bar, 4)}; + VerifyGenerator(gen, expected_values); +} + +// Tests that Combine() with three parameters generates the expected sequence. +TEST(CombineTest, CombineWithThreeParameters) { + const ParamGenerator > gen = Combine(Values(0, 1), + Values(3, 4), + Values(5, 6)); + tuple expected_values[] = { + make_tuple(0, 3, 5), make_tuple(0, 3, 6), + make_tuple(0, 4, 5), make_tuple(0, 4, 6), + make_tuple(1, 3, 5), make_tuple(1, 3, 6), + make_tuple(1, 4, 5), make_tuple(1, 4, 6)}; + VerifyGenerator(gen, expected_values); +} + +// Tests that the Combine() with the first parameter generating a single value +// sequence generates a sequence with the number of elements equal to the +// number of elements in the sequence generated by the second parameter. +TEST(CombineTest, CombineWithFirstParameterSingleValue) { + const ParamGenerator > gen = Combine(Values(42), + Values(0, 1)); + + tuple expected_values[] = {make_tuple(42, 0), make_tuple(42, 1)}; + VerifyGenerator(gen, expected_values); +} + +// Tests that the Combine() with the second parameter generating a single value +// sequence generates a sequence with the number of elements equal to the +// number of elements in the sequence generated by the first parameter. +TEST(CombineTest, CombineWithSecondParameterSingleValue) { + const ParamGenerator > gen = Combine(Values(0, 1), + Values(42)); + + tuple expected_values[] = {make_tuple(0, 42), make_tuple(1, 42)}; + VerifyGenerator(gen, expected_values); +} + +// Tests that when the first parameter produces an empty sequence, +// Combine() produces an empty sequence, too. +TEST(CombineTest, CombineWithFirstParameterEmptyRange) { + const ParamGenerator > gen = Combine(Range(0, 0), + Values(0, 1)); + VerifyGeneratorIsEmpty(gen); +} + +// Tests that when the second parameter produces an empty sequence, +// Combine() produces an empty sequence, too. +TEST(CombineTest, CombineWithSecondParameterEmptyRange) { + const ParamGenerator > gen = Combine(Values(0, 1), + Range(1, 1)); + VerifyGeneratorIsEmpty(gen); +} + +// Edge case. Tests that combine works with the maximum number +// of parameters supported by Google Test (currently 10). +TEST(CombineTest, CombineWithMaxNumberOfParameters) { + const char* foo = "foo"; + const char* bar = "bar"; + const ParamGenerator > gen = Combine(Values(foo, bar), + Values(1), Values(2), + Values(3), Values(4), + Values(5), Values(6), + Values(7), Values(8), + Values(9)); + + tuple + expected_values[] = {make_tuple(foo, 1, 2, 3, 4, 5, 6, 7, 8, 9), + make_tuple(bar, 1, 2, 3, 4, 5, 6, 7, 8, 9)}; + VerifyGenerator(gen, expected_values); +} + +#if GTEST_LANG_CXX11 + +class NonDefaultConstructAssignString { + public: + NonDefaultConstructAssignString(const std::string& s) : str_(s) {} + + const std::string& str() const { return str_; } + + private: + std::string str_; + + // Not default constructible + NonDefaultConstructAssignString(); + // Not assignable + void operator=(const NonDefaultConstructAssignString&); +}; + +TEST(CombineTest, NonDefaultConstructAssign) { + const ParamGenerator > gen = + Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"), + NonDefaultConstructAssignString("B"))); + + ParamGenerator >::iterator it = + gen.begin(); + + EXPECT_EQ(0, std::get<0>(*it)); + EXPECT_EQ("A", std::get<1>(*it).str()); + ++it; + + EXPECT_EQ(0, std::get<0>(*it)); + EXPECT_EQ("B", std::get<1>(*it).str()); + ++it; + + EXPECT_EQ(1, std::get<0>(*it)); + EXPECT_EQ("A", std::get<1>(*it).str()); + ++it; + + EXPECT_EQ(1, std::get<0>(*it)); + EXPECT_EQ("B", std::get<1>(*it).str()); + ++it; + + EXPECT_TRUE(it == gen.end()); +} + +#endif // GTEST_LANG_CXX11 +# endif // GTEST_HAS_COMBINE + +// Tests that an generator produces correct sequence after being +// assigned from another generator. +TEST(ParamGeneratorTest, AssignmentWorks) { + ParamGenerator gen = Values(1, 2); + const ParamGenerator gen2 = Values(3, 4); + gen = gen2; + + const int expected_values[] = {3, 4}; + VerifyGenerator(gen, expected_values); +} + +// This test verifies that the tests are expanded and run as specified: +// one test per element from the sequence produced by the generator +// specified in INSTANTIATE_TEST_CASE_P. It also verifies that the test's +// fixture constructor, SetUp(), and TearDown() have run and have been +// supplied with the correct parameters. + +// The use of environment object allows detection of the case where no test +// case functionality is run at all. In this case TestCaseTearDown will not +// be able to detect missing tests, naturally. +template +class TestGenerationEnvironment : public ::testing::Environment { + public: + static TestGenerationEnvironment* Instance() { + static TestGenerationEnvironment* instance = new TestGenerationEnvironment; + return instance; + } + + void FixtureConstructorExecuted() { fixture_constructor_count_++; } + void SetUpExecuted() { set_up_count_++; } + void TearDownExecuted() { tear_down_count_++; } + void TestBodyExecuted() { test_body_count_++; } + + virtual void TearDown() { + // If all MultipleTestGenerationTest tests have been de-selected + // by the filter flag, the following checks make no sense. + bool perform_check = false; + + for (int i = 0; i < kExpectedCalls; ++i) { + Message msg; + msg << "TestsExpandedAndRun/" << i; + if (UnitTestOptions::FilterMatchesTest( + "TestExpansionModule/MultipleTestGenerationTest", + msg.GetString().c_str())) { + perform_check = true; + } + } + if (perform_check) { + EXPECT_EQ(kExpectedCalls, fixture_constructor_count_) + << "Fixture constructor of ParamTestGenerationTest test case " + << "has not been run as expected."; + EXPECT_EQ(kExpectedCalls, set_up_count_) + << "Fixture SetUp method of ParamTestGenerationTest test case " + << "has not been run as expected."; + EXPECT_EQ(kExpectedCalls, tear_down_count_) + << "Fixture TearDown method of ParamTestGenerationTest test case " + << "has not been run as expected."; + EXPECT_EQ(kExpectedCalls, test_body_count_) + << "Test in ParamTestGenerationTest test case " + << "has not been run as expected."; + } + } + + private: + TestGenerationEnvironment() : fixture_constructor_count_(0), set_up_count_(0), + tear_down_count_(0), test_body_count_(0) {} + + int fixture_constructor_count_; + int set_up_count_; + int tear_down_count_; + int test_body_count_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationEnvironment); +}; + +const int test_generation_params[] = {36, 42, 72}; + +class TestGenerationTest : public TestWithParam { + public: + enum { + PARAMETER_COUNT = + sizeof(test_generation_params)/sizeof(test_generation_params[0]) + }; + + typedef TestGenerationEnvironment Environment; + + TestGenerationTest() { + Environment::Instance()->FixtureConstructorExecuted(); + current_parameter_ = GetParam(); + } + virtual void SetUp() { + Environment::Instance()->SetUpExecuted(); + EXPECT_EQ(current_parameter_, GetParam()); + } + virtual void TearDown() { + Environment::Instance()->TearDownExecuted(); + EXPECT_EQ(current_parameter_, GetParam()); + } + + static void SetUpTestCase() { + bool all_tests_in_test_case_selected = true; + + for (int i = 0; i < PARAMETER_COUNT; ++i) { + Message test_name; + test_name << "TestsExpandedAndRun/" << i; + if ( !UnitTestOptions::FilterMatchesTest( + "TestExpansionModule/MultipleTestGenerationTest", + test_name.GetString())) { + all_tests_in_test_case_selected = false; + } + } + EXPECT_TRUE(all_tests_in_test_case_selected) + << "When running the TestGenerationTest test case all of its tests\n" + << "must be selected by the filter flag for the test case to pass.\n" + << "If not all of them are enabled, we can't reliably conclude\n" + << "that the correct number of tests have been generated."; + + collected_parameters_.clear(); + } + + static void TearDownTestCase() { + vector expected_values(test_generation_params, + test_generation_params + PARAMETER_COUNT); + // Test execution order is not guaranteed by Google Test, + // so the order of values in collected_parameters_ can be + // different and we have to sort to compare. + sort(expected_values.begin(), expected_values.end()); + sort(collected_parameters_.begin(), collected_parameters_.end()); + + EXPECT_TRUE(collected_parameters_ == expected_values); + } + + protected: + int current_parameter_; + static vector collected_parameters_; + + private: + GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationTest); +}; +vector TestGenerationTest::collected_parameters_; + +TEST_P(TestGenerationTest, TestsExpandedAndRun) { + Environment::Instance()->TestBodyExecuted(); + EXPECT_EQ(current_parameter_, GetParam()); + collected_parameters_.push_back(GetParam()); +} +INSTANTIATE_TEST_CASE_P(TestExpansionModule, TestGenerationTest, + ValuesIn(test_generation_params)); + +// This test verifies that the element sequence (third parameter of +// INSTANTIATE_TEST_CASE_P) is evaluated in InitGoogleTest() and neither at +// the call site of INSTANTIATE_TEST_CASE_P nor in RUN_ALL_TESTS(). For +// that, we declare param_value_ to be a static member of +// GeneratorEvaluationTest and initialize it to 0. We set it to 1 in +// main(), just before invocation of InitGoogleTest(). After calling +// InitGoogleTest(), we set the value to 2. If the sequence is evaluated +// before or after InitGoogleTest, INSTANTIATE_TEST_CASE_P will create a +// test with parameter other than 1, and the test body will fail the +// assertion. +class GeneratorEvaluationTest : public TestWithParam { + public: + static int param_value() { return param_value_; } + static void set_param_value(int param_value) { param_value_ = param_value; } + + private: + static int param_value_; +}; +int GeneratorEvaluationTest::param_value_ = 0; + +TEST_P(GeneratorEvaluationTest, GeneratorsEvaluatedInMain) { + EXPECT_EQ(1, GetParam()); +} +INSTANTIATE_TEST_CASE_P(GenEvalModule, + GeneratorEvaluationTest, + Values(GeneratorEvaluationTest::param_value())); + +// Tests that generators defined in a different translation unit are +// functional. Generator extern_gen is defined in gtest-param-test_test2.cc. +extern ParamGenerator extern_gen; +class ExternalGeneratorTest : public TestWithParam {}; +TEST_P(ExternalGeneratorTest, ExternalGenerator) { + // Sequence produced by extern_gen contains only a single value + // which we verify here. + EXPECT_EQ(GetParam(), 33); +} +INSTANTIATE_TEST_CASE_P(ExternalGeneratorModule, + ExternalGeneratorTest, + extern_gen); + +// Tests that a parameterized test case can be defined in one translation +// unit and instantiated in another. This test will be instantiated in +// gtest-param-test_test2.cc. ExternalInstantiationTest fixture class is +// defined in gtest-param-test_test.h. +TEST_P(ExternalInstantiationTest, IsMultipleOf33) { + EXPECT_EQ(0, GetParam() % 33); +} + +// Tests that a parameterized test case can be instantiated with multiple +// generators. +class MultipleInstantiationTest : public TestWithParam {}; +TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) { +} +INSTANTIATE_TEST_CASE_P(Sequence1, MultipleInstantiationTest, Values(1, 2)); +INSTANTIATE_TEST_CASE_P(Sequence2, MultipleInstantiationTest, Range(3, 5)); + +// Tests that a parameterized test case can be instantiated +// in multiple translation units. This test will be instantiated +// here and in gtest-param-test_test2.cc. +// InstantiationInMultipleTranslationUnitsTest fixture class +// is defined in gtest-param-test_test.h. +TEST_P(InstantiationInMultipleTranslaionUnitsTest, IsMultipleOf42) { + EXPECT_EQ(0, GetParam() % 42); +} +INSTANTIATE_TEST_CASE_P(Sequence1, + InstantiationInMultipleTranslaionUnitsTest, + Values(42, 42*2)); + +// Tests that each iteration of parameterized test runs in a separate test +// object. +class SeparateInstanceTest : public TestWithParam { + public: + SeparateInstanceTest() : count_(0) {} + + static void TearDownTestCase() { + EXPECT_GE(global_count_, 2) + << "If some (but not all) SeparateInstanceTest tests have been " + << "filtered out this test will fail. Make sure that all " + << "GeneratorEvaluationTest are selected or de-selected together " + << "by the test filter."; + } + + protected: + int count_; + static int global_count_; +}; +int SeparateInstanceTest::global_count_ = 0; + +TEST_P(SeparateInstanceTest, TestsRunInSeparateInstances) { + EXPECT_EQ(0, count_++); + global_count_++; +} +INSTANTIATE_TEST_CASE_P(FourElemSequence, SeparateInstanceTest, Range(1, 4)); + +// Tests that all instantiations of a test have named appropriately. Test +// defined with TEST_P(TestCaseName, TestName) and instantiated with +// INSTANTIATE_TEST_CASE_P(SequenceName, TestCaseName, generator) must be named +// SequenceName/TestCaseName.TestName/i, where i is the 0-based index of the +// sequence element used to instantiate the test. +class NamingTest : public TestWithParam {}; + +TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) { + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + + EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_case_name()); + + Message index_stream; + index_stream << "TestsReportCorrectNamesAndParameters/" << GetParam(); + EXPECT_STREQ(index_stream.GetString().c_str(), test_info->name()); + + EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param()); +} + +INSTANTIATE_TEST_CASE_P(ZeroToFiveSequence, NamingTest, Range(0, 5)); + +// Tests that macros in test names are expanded correctly. +class MacroNamingTest : public TestWithParam {}; + +#define PREFIX_WITH_FOO(test_name) Foo##test_name +#define PREFIX_WITH_MACRO(test_name) Macro##test_name + +TEST_P(PREFIX_WITH_MACRO(NamingTest), PREFIX_WITH_FOO(SomeTestName)) { + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + + EXPECT_STREQ("FortyTwo/MacroNamingTest", test_info->test_case_name()); + EXPECT_STREQ("FooSomeTestName", test_info->name()); +} + +INSTANTIATE_TEST_CASE_P(FortyTwo, MacroNamingTest, Values(42)); + +// Tests the same thing for non-parametrized tests. +class MacroNamingTestNonParametrized : public ::testing::Test {}; + +TEST_F(PREFIX_WITH_MACRO(NamingTestNonParametrized), + PREFIX_WITH_FOO(SomeTestName)) { + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + + EXPECT_STREQ("MacroNamingTestNonParametrized", test_info->test_case_name()); + EXPECT_STREQ("FooSomeTestName", test_info->name()); +} + +// Tests that user supplied custom parameter names are working correctly. +// Runs the test with a builtin helper method which uses PrintToString, +// as well as a custom function and custom functor to ensure all possible +// uses work correctly. +class CustomFunctorNamingTest : public TestWithParam {}; +TEST_P(CustomFunctorNamingTest, CustomTestNames) {} + +struct CustomParamNameFunctor { + std::string operator()(const ::testing::TestParamInfo& inf) { + return inf.param; + } +}; + +INSTANTIATE_TEST_CASE_P(CustomParamNameFunctor, + CustomFunctorNamingTest, + Values(std::string("FunctorName")), + CustomParamNameFunctor()); + +INSTANTIATE_TEST_CASE_P(AllAllowedCharacters, + CustomFunctorNamingTest, + Values("abcdefghijklmnopqrstuvwxyz", + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", + "01234567890_"), + CustomParamNameFunctor()); + +inline std::string CustomParamNameFunction( + const ::testing::TestParamInfo& inf) { + return inf.param; +} + +class CustomFunctionNamingTest : public TestWithParam {}; +TEST_P(CustomFunctionNamingTest, CustomTestNames) {} + +INSTANTIATE_TEST_CASE_P(CustomParamNameFunction, + CustomFunctionNamingTest, + Values(std::string("FunctionName")), + CustomParamNameFunction); + +#if GTEST_LANG_CXX11 + +// Test custom naming with a lambda + +class CustomLambdaNamingTest : public TestWithParam {}; +TEST_P(CustomLambdaNamingTest, CustomTestNames) {} + +INSTANTIATE_TEST_CASE_P(CustomParamNameLambda, CustomLambdaNamingTest, + Values(std::string("LambdaName")), + [](const ::testing::TestParamInfo& inf) { + return inf.param; + }); + +#endif // GTEST_LANG_CXX11 + +TEST(CustomNamingTest, CheckNameRegistry) { + ::testing::UnitTest* unit_test = ::testing::UnitTest::GetInstance(); + std::set test_names; + for (int case_num = 0; + case_num < unit_test->total_test_case_count(); + ++case_num) { + const ::testing::TestCase* test_case = unit_test->GetTestCase(case_num); + for (int test_num = 0; + test_num < test_case->total_test_count(); + ++test_num) { + const ::testing::TestInfo* test_info = test_case->GetTestInfo(test_num); + test_names.insert(std::string(test_info->name())); + } + } + EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctorName")); + EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctionName")); +#if GTEST_LANG_CXX11 + EXPECT_EQ(1u, test_names.count("CustomTestNames/LambdaName")); +#endif // GTEST_LANG_CXX11 +} + +// Test a numeric name to ensure PrintToStringParamName works correctly. + +class CustomIntegerNamingTest : public TestWithParam {}; + +TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) { + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + Message test_name_stream; + test_name_stream << "TestsReportCorrectNames/" << GetParam(); + EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); +} + +INSTANTIATE_TEST_CASE_P(PrintToString, + CustomIntegerNamingTest, + Range(0, 5), + ::testing::PrintToStringParamName()); + +// Test a custom struct with PrintToString. + +struct CustomStruct { + explicit CustomStruct(int value) : x(value) {} + int x; +}; + +std::ostream& operator<<(std::ostream& stream, const CustomStruct& val) { + stream << val.x; + return stream; +} + +class CustomStructNamingTest : public TestWithParam {}; + +TEST_P(CustomStructNamingTest, TestsReportCorrectNames) { + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + Message test_name_stream; + test_name_stream << "TestsReportCorrectNames/" << GetParam(); + EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); +} + +INSTANTIATE_TEST_CASE_P(PrintToString, + CustomStructNamingTest, + Values(CustomStruct(0), CustomStruct(1)), + ::testing::PrintToStringParamName()); + +// Test that using a stateful parameter naming function works as expected. + +struct StatefulNamingFunctor { + StatefulNamingFunctor() : sum(0) {} + std::string operator()(const ::testing::TestParamInfo& info) { + int value = info.param + sum; + sum += info.param; + return ::testing::PrintToString(value); + } + int sum; +}; + +class StatefulNamingTest : public ::testing::TestWithParam { + protected: + StatefulNamingTest() : sum_(0) {} + int sum_; +}; + +TEST_P(StatefulNamingTest, TestsReportCorrectNames) { + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + sum_ += GetParam(); + Message test_name_stream; + test_name_stream << "TestsReportCorrectNames/" << sum_; + EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); +} + +INSTANTIATE_TEST_CASE_P(StatefulNamingFunctor, + StatefulNamingTest, + Range(0, 5), + StatefulNamingFunctor()); + +// Class that cannot be streamed into an ostream. It needs to be copyable +// (and, in case of MSVC, also assignable) in order to be a test parameter +// type. Its default copy constructor and assignment operator do exactly +// what we need. +class Unstreamable { + public: + explicit Unstreamable(int value) : value_(value) {} + + private: + int value_; +}; + +class CommentTest : public TestWithParam {}; + +TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) { + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + + EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param()); +} + +INSTANTIATE_TEST_CASE_P(InstantiationWithComments, + CommentTest, + Values(Unstreamable(1))); + +// Verify that we can create a hierarchy of test fixtures, where the base +// class fixture is not parameterized and the derived class is. In this case +// ParameterizedDerivedTest inherits from NonParameterizedBaseTest. We +// perform simple tests on both. +class NonParameterizedBaseTest : public ::testing::Test { + public: + NonParameterizedBaseTest() : n_(17) { } + protected: + int n_; +}; + +class ParameterizedDerivedTest : public NonParameterizedBaseTest, + public ::testing::WithParamInterface { + protected: + ParameterizedDerivedTest() : count_(0) { } + int count_; + static int global_count_; +}; + +int ParameterizedDerivedTest::global_count_ = 0; + +TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { + EXPECT_EQ(17, n_); +} + +TEST_P(ParameterizedDerivedTest, SeesSequence) { + EXPECT_EQ(17, n_); + EXPECT_EQ(0, count_++); + EXPECT_EQ(GetParam(), global_count_++); +} + +class ParameterizedDeathTest : public ::testing::TestWithParam { }; + +TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) { + EXPECT_DEATH_IF_SUPPORTED(GetParam(), + ".* value-parameterized test .*"); +} + +INSTANTIATE_TEST_CASE_P(RangeZeroToFive, ParameterizedDerivedTest, Range(0, 5)); + + +int main(int argc, char **argv) { + // Used in TestGenerationTest test case. + AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance()); + // Used in GeneratorEvaluationTest test case. Tests that the updated value + // will be picked up for instantiating tests in GeneratorEvaluationTest. + GeneratorEvaluationTest::set_param_value(1); + + ::testing::InitGoogleTest(&argc, argv); + + // Used in GeneratorEvaluationTest test case. Tests that value updated + // here will NOT be used for instantiating tests in + // GeneratorEvaluationTest. + GeneratorEvaluationTest::set_param_value(2); + + return RUN_ALL_TESTS(); +} diff --git a/googletest/test/googletest-param-test-test.h b/googletest/test/googletest-param-test-test.h new file mode 100644 index 0000000..ea1e884 --- /dev/null +++ b/googletest/test/googletest-param-test-test.h @@ -0,0 +1,53 @@ +// 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: vladl@google.com (Vlad Losev) +// +// The Google C++ Testing and Mocking Framework (Google Test) +// +// This header file provides classes and functions used internally +// for testing Google Test itself. + +#ifndef GTEST_TEST_GTEST_PARAM_TEST_TEST_H_ +#define GTEST_TEST_GTEST_PARAM_TEST_TEST_H_ + +#include "gtest/gtest.h" + +// Test fixture for testing definition and instantiation of a test +// in separate translation units. +class ExternalInstantiationTest : public ::testing::TestWithParam { +}; + +// Test fixture for testing instantiation of a test in multiple +// translation units. +class InstantiationInMultipleTranslaionUnitsTest + : public ::testing::TestWithParam { +}; + +#endif // GTEST_TEST_GTEST_PARAM_TEST_TEST_H_ diff --git a/googletest/test/googletest-param-test2-test.cc b/googletest/test/googletest-param-test2-test.cc new file mode 100644 index 0000000..c0db7bf --- /dev/null +++ b/googletest/test/googletest-param-test2-test.cc @@ -0,0 +1,61 @@ +// 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: vladl@google.com (Vlad Losev) +// +// Tests for Google Test itself. This verifies that the basic constructs of +// Google Test work. + +#include "gtest/gtest.h" +#include "googletest-param-test-test.h" + +using ::testing::Values; +using ::testing::internal::ParamGenerator; + +// Tests that generators defined in a different translation unit +// are functional. The test using extern_gen is defined +// in gtest-param-test_test.cc. +ParamGenerator extern_gen = Values(33); + +// Tests that a parameterized test case can be defined in one translation unit +// and instantiated in another. The test is defined in gtest-param-test_test.cc +// and ExternalInstantiationTest fixture class is defined in +// gtest-param-test_test.h. +INSTANTIATE_TEST_CASE_P(MultiplesOf33, + ExternalInstantiationTest, + Values(33, 66)); + +// Tests that a parameterized test case can be instantiated +// in multiple translation units. Another instantiation is defined +// in gtest-param-test_test.cc and InstantiationInMultipleTranslaionUnitsTest +// fixture is defined in gtest-param-test_test.h +INSTANTIATE_TEST_CASE_P(Sequence2, + InstantiationInMultipleTranslaionUnitsTest, + Values(42*3, 42*4, 42*5)); + diff --git a/googletest/test/googletest-test-part-test.cc b/googletest/test/googletest-test-part-test.cc new file mode 100644 index 0000000..ca8ba93 --- /dev/null +++ b/googletest/test/googletest-test-part-test.cc @@ -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. +// +// Author: mheule@google.com (Markus Heule) +// + +#include "gtest/gtest-test-part.h" + +#include "gtest/gtest.h" + +using testing::Message; +using testing::Test; +using testing::TestPartResult; +using testing::TestPartResultArray; + +namespace { + +// Tests the TestPartResult class. + +// The test fixture for testing TestPartResult. +class TestPartResultTest : public Test { + protected: + TestPartResultTest() + : r1_(TestPartResult::kSuccess, "foo/bar.cc", 10, "Success!"), + r2_(TestPartResult::kNonFatalFailure, "foo/bar.cc", -1, "Failure!"), + r3_(TestPartResult::kFatalFailure, NULL, -1, "Failure!") {} + + TestPartResult r1_, r2_, r3_; +}; + + +TEST_F(TestPartResultTest, ConstructorWorks) { + Message message; + message << "something is terribly wrong"; + message << static_cast(testing::internal::kStackTraceMarker); + message << "some unimportant stack trace"; + + const TestPartResult result(TestPartResult::kNonFatalFailure, + "some_file.cc", + 42, + message.GetString().c_str()); + + EXPECT_EQ(TestPartResult::kNonFatalFailure, result.type()); + EXPECT_STREQ("some_file.cc", result.file_name()); + EXPECT_EQ(42, result.line_number()); + EXPECT_STREQ(message.GetString().c_str(), result.message()); + EXPECT_STREQ("something is terribly wrong", result.summary()); +} + +TEST_F(TestPartResultTest, ResultAccessorsWork) { + const TestPartResult success(TestPartResult::kSuccess, + "file.cc", + 42, + "message"); + EXPECT_TRUE(success.passed()); + EXPECT_FALSE(success.failed()); + EXPECT_FALSE(success.nonfatally_failed()); + EXPECT_FALSE(success.fatally_failed()); + + const TestPartResult nonfatal_failure(TestPartResult::kNonFatalFailure, + "file.cc", + 42, + "message"); + EXPECT_FALSE(nonfatal_failure.passed()); + EXPECT_TRUE(nonfatal_failure.failed()); + EXPECT_TRUE(nonfatal_failure.nonfatally_failed()); + EXPECT_FALSE(nonfatal_failure.fatally_failed()); + + const TestPartResult fatal_failure(TestPartResult::kFatalFailure, + "file.cc", + 42, + "message"); + EXPECT_FALSE(fatal_failure.passed()); + EXPECT_TRUE(fatal_failure.failed()); + EXPECT_FALSE(fatal_failure.nonfatally_failed()); + EXPECT_TRUE(fatal_failure.fatally_failed()); +} + +// Tests TestPartResult::type(). +TEST_F(TestPartResultTest, type) { + EXPECT_EQ(TestPartResult::kSuccess, r1_.type()); + EXPECT_EQ(TestPartResult::kNonFatalFailure, r2_.type()); + EXPECT_EQ(TestPartResult::kFatalFailure, r3_.type()); +} + +// Tests TestPartResult::file_name(). +TEST_F(TestPartResultTest, file_name) { + EXPECT_STREQ("foo/bar.cc", r1_.file_name()); + EXPECT_STREQ(NULL, r3_.file_name()); +} + +// Tests TestPartResult::line_number(). +TEST_F(TestPartResultTest, line_number) { + EXPECT_EQ(10, r1_.line_number()); + EXPECT_EQ(-1, r2_.line_number()); +} + +// Tests TestPartResult::message(). +TEST_F(TestPartResultTest, message) { + EXPECT_STREQ("Success!", r1_.message()); +} + +// Tests TestPartResult::passed(). +TEST_F(TestPartResultTest, Passed) { + EXPECT_TRUE(r1_.passed()); + EXPECT_FALSE(r2_.passed()); + EXPECT_FALSE(r3_.passed()); +} + +// Tests TestPartResult::failed(). +TEST_F(TestPartResultTest, Failed) { + EXPECT_FALSE(r1_.failed()); + EXPECT_TRUE(r2_.failed()); + EXPECT_TRUE(r3_.failed()); +} + +// Tests TestPartResult::fatally_failed(). +TEST_F(TestPartResultTest, FatallyFailed) { + EXPECT_FALSE(r1_.fatally_failed()); + EXPECT_FALSE(r2_.fatally_failed()); + EXPECT_TRUE(r3_.fatally_failed()); +} + +// Tests TestPartResult::nonfatally_failed(). +TEST_F(TestPartResultTest, NonfatallyFailed) { + EXPECT_FALSE(r1_.nonfatally_failed()); + EXPECT_TRUE(r2_.nonfatally_failed()); + EXPECT_FALSE(r3_.nonfatally_failed()); +} + +// Tests the TestPartResultArray class. + +class TestPartResultArrayTest : public Test { + protected: + TestPartResultArrayTest() + : r1_(TestPartResult::kNonFatalFailure, "foo/bar.cc", -1, "Failure 1"), + r2_(TestPartResult::kFatalFailure, "foo/bar.cc", -1, "Failure 2") {} + + const TestPartResult r1_, r2_; +}; + +// Tests that TestPartResultArray initially has size 0. +TEST_F(TestPartResultArrayTest, InitialSizeIsZero) { + TestPartResultArray results; + EXPECT_EQ(0, results.size()); +} + +// Tests that TestPartResultArray contains the given TestPartResult +// after one Append() operation. +TEST_F(TestPartResultArrayTest, ContainsGivenResultAfterAppend) { + TestPartResultArray results; + results.Append(r1_); + EXPECT_EQ(1, results.size()); + EXPECT_STREQ("Failure 1", results.GetTestPartResult(0).message()); +} + +// Tests that TestPartResultArray contains the given TestPartResults +// after two Append() operations. +TEST_F(TestPartResultArrayTest, ContainsGivenResultsAfterTwoAppends) { + TestPartResultArray results; + results.Append(r1_); + results.Append(r2_); + EXPECT_EQ(2, results.size()); + EXPECT_STREQ("Failure 1", results.GetTestPartResult(0).message()); + EXPECT_STREQ("Failure 2", results.GetTestPartResult(1).message()); +} + +typedef TestPartResultArrayTest TestPartResultArrayDeathTest; + +// Tests that the program dies when GetTestPartResult() is called with +// an invalid index. +TEST_F(TestPartResultArrayDeathTest, DiesWhenIndexIsOutOfBound) { + TestPartResultArray results; + results.Append(r1_); + + EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(-1), ""); + EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(1), ""); +} + +// TODO(mheule@google.com): Add a test for the class HasNewFatalFailureHelper. + +} // namespace diff --git a/googletest/test/googletest-test2_test.cc b/googletest/test/googletest-test2_test.cc new file mode 100644 index 0000000..732e356 --- /dev/null +++ b/googletest/test/googletest-test2_test.cc @@ -0,0 +1,61 @@ +// 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: vladl@google.com (Vlad Losev) +// +// Tests for Google Test itself. This verifies that the basic constructs of +// Google Test work. + +#include "gtest/gtest.h" +#include "googletest-param-test-test.h" + +using ::testing::Values; +using ::testing::internal::ParamGenerator; + +// Tests that generators defined in a different translation unit +// are functional. The test using extern_gen_2 is defined +// in gtest-param-test_test.cc. +ParamGenerator extern_gen_2 = Values(33); + +// Tests that a parameterized test case can be defined in one translation unit +// and instantiated in another. The test is defined in gtest-param-test_test.cc +// and ExternalInstantiationTest fixture class is defined in +// gtest-param-test_test.h. +INSTANTIATE_TEST_CASE_P(MultiplesOf33, + ExternalInstantiationTest, + Values(33, 66)); + +// Tests that a parameterized test case can be instantiated +// in multiple translation units. Another instantiation is defined +// in gtest-param-test_test.cc and InstantiationInMultipleTranslaionUnitsTest +// fixture is defined in gtest-param-test_test.h +INSTANTIATE_TEST_CASE_P(Sequence2, + InstantiationInMultipleTranslaionUnitsTest, + Values(42*3, 42*4, 42*5)); + diff --git a/googletest/test/gtest-death-test_ex_test.cc b/googletest/test/gtest-death-test_ex_test.cc deleted file mode 100644 index b50a13d..0000000 --- a/googletest/test/gtest-death-test_ex_test.cc +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2010, 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: vladl@google.com (Vlad Losev) -// -// Tests that verify interaction of exceptions and death tests. - -#include "gtest/gtest-death-test.h" -#include "gtest/gtest.h" - -#if GTEST_HAS_DEATH_TEST - -# if GTEST_HAS_SEH -# include // For RaiseException(). -# endif - -# include "gtest/gtest-spi.h" - -# if GTEST_HAS_EXCEPTIONS - -# include // For std::exception. - -// Tests that death tests report thrown exceptions as failures and that the -// exceptions do not escape death test macros. -TEST(CxxExceptionDeathTest, ExceptionIsFailure) { - try { - EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw 1, ""), "threw an exception"); - } catch (...) { // NOLINT - FAIL() << "An exception escaped a death test macro invocation " - << "with catch_exceptions " - << (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled"); - } -} - -class TestException : public std::exception { - public: - virtual const char* what() const throw() { return "exceptional message"; } -}; - -TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) { - // Verifies that the exception message is quoted in the failure text. - EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), - "exceptional message"); - // Verifies that the location is mentioned in the failure text. - EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), - "gtest-death-test_ex_test.cc"); -} -# endif // GTEST_HAS_EXCEPTIONS - -# if GTEST_HAS_SEH -// Tests that enabling interception of SEH exceptions with the -// catch_exceptions flag does not interfere with SEH exceptions being -// treated as death by death tests. -TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) { - EXPECT_DEATH(RaiseException(42, 0x0, 0, NULL), "") - << "with catch_exceptions " - << (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled"); -} -# endif - -#endif // GTEST_HAS_DEATH_TEST - -int main(int argc, char** argv) { - testing::InitGoogleTest(&argc, argv); - testing::GTEST_FLAG(catch_exceptions) = GTEST_ENABLE_CATCH_EXCEPTIONS_ != 0; - return RUN_ALL_TESTS(); -} diff --git a/googletest/test/gtest-param-test2_test.cc b/googletest/test/gtest-param-test2_test.cc deleted file mode 100644 index c3b2d18..0000000 --- a/googletest/test/gtest-param-test2_test.cc +++ /dev/null @@ -1,61 +0,0 @@ -// 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: vladl@google.com (Vlad Losev) -// -// Tests for Google Test itself. This verifies that the basic constructs of -// Google Test work. - -#include "gtest/gtest.h" -#include "gtest-param-test_test.h" - -using ::testing::Values; -using ::testing::internal::ParamGenerator; - -// Tests that generators defined in a different translation unit -// are functional. The test using extern_gen is defined -// in gtest-param-test_test.cc. -ParamGenerator extern_gen = Values(33); - -// Tests that a parameterized test case can be defined in one translation unit -// and instantiated in another. The test is defined in gtest-param-test_test.cc -// and ExternalInstantiationTest fixture class is defined in -// gtest-param-test_test.h. -INSTANTIATE_TEST_CASE_P(MultiplesOf33, - ExternalInstantiationTest, - Values(33, 66)); - -// Tests that a parameterized test case can be instantiated -// in multiple translation units. Another instantiation is defined -// in gtest-param-test_test.cc and InstantiationInMultipleTranslaionUnitsTest -// fixture is defined in gtest-param-test_test.h -INSTANTIATE_TEST_CASE_P(Sequence2, - InstantiationInMultipleTranslaionUnitsTest, - Values(42*3, 42*4, 42*5)); - diff --git a/googletest/test/gtest-param-test_test.cc b/googletest/test/gtest-param-test_test.cc deleted file mode 100644 index adc4d1b..0000000 --- a/googletest/test/gtest-param-test_test.cc +++ /dev/null @@ -1,1110 +0,0 @@ -// 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: vladl@google.com (Vlad Losev) -// -// Tests for Google Test itself. This file verifies that the parameter -// generators objects produce correct parameter sequences and that -// Google Test runtime instantiates correct tests from those sequences. - -#include "gtest/gtest.h" - -# include -# include -# include -# include -# include -# include - -# include "src/gtest-internal-inl.h" // for UnitTestOptions -# include "test/gtest-param-test_test.h" - -using ::std::vector; -using ::std::sort; - -using ::testing::AddGlobalTestEnvironment; -using ::testing::Bool; -using ::testing::Message; -using ::testing::Range; -using ::testing::TestWithParam; -using ::testing::Values; -using ::testing::ValuesIn; - -# if GTEST_HAS_COMBINE -using ::testing::Combine; -using ::testing::get; -using ::testing::make_tuple; -using ::testing::tuple; -# endif // GTEST_HAS_COMBINE - -using ::testing::internal::ParamGenerator; -using ::testing::internal::UnitTestOptions; - -// Prints a value to a string. -// -// TODO(wan@google.com): remove PrintValue() when we move matchers and -// EXPECT_THAT() from Google Mock to Google Test. At that time, we -// can write EXPECT_THAT(x, Eq(y)) to compare two tuples x and y, as -// EXPECT_THAT() and the matchers know how to print tuples. -template -::std::string PrintValue(const T& value) { - ::std::stringstream stream; - stream << value; - return stream.str(); -} - -# if GTEST_HAS_COMBINE - -// These overloads allow printing tuples in our tests. We cannot -// define an operator<< for tuples, as that definition needs to be in -// the std namespace in order to be picked up by Google Test via -// Argument-Dependent Lookup, yet defining anything in the std -// namespace in non-STL code is undefined behavior. - -template -::std::string PrintValue(const tuple& value) { - ::std::stringstream stream; - stream << "(" << get<0>(value) << ", " << get<1>(value) << ")"; - return stream.str(); -} - -template -::std::string PrintValue(const tuple& value) { - ::std::stringstream stream; - stream << "(" << get<0>(value) << ", " << get<1>(value) - << ", "<< get<2>(value) << ")"; - return stream.str(); -} - -template -::std::string PrintValue( - const tuple& value) { - ::std::stringstream stream; - stream << "(" << get<0>(value) << ", " << get<1>(value) - << ", "<< get<2>(value) << ", " << get<3>(value) - << ", "<< get<4>(value) << ", " << get<5>(value) - << ", "<< get<6>(value) << ", " << get<7>(value) - << ", "<< get<8>(value) << ", " << get<9>(value) << ")"; - return stream.str(); -} - -# endif // GTEST_HAS_COMBINE - -// Verifies that a sequence generated by the generator and accessed -// via the iterator object matches the expected one using Google Test -// assertions. -template -void VerifyGenerator(const ParamGenerator& generator, - const T (&expected_values)[N]) { - typename ParamGenerator::iterator it = generator.begin(); - for (size_t i = 0; i < N; ++i) { - ASSERT_FALSE(it == generator.end()) - << "At element " << i << " when accessing via an iterator " - << "created with the copy constructor.\n"; - // We cannot use EXPECT_EQ() here as the values may be tuples, - // which don't support <<. - EXPECT_TRUE(expected_values[i] == *it) - << "where i is " << i - << ", expected_values[i] is " << PrintValue(expected_values[i]) - << ", *it is " << PrintValue(*it) - << ", and 'it' is an iterator created with the copy constructor.\n"; - ++it; - } - EXPECT_TRUE(it == generator.end()) - << "At the presumed end of sequence when accessing via an iterator " - << "created with the copy constructor.\n"; - - // Test the iterator assignment. The following lines verify that - // the sequence accessed via an iterator initialized via the - // assignment operator (as opposed to a copy constructor) matches - // just the same. - it = generator.begin(); - for (size_t i = 0; i < N; ++i) { - ASSERT_FALSE(it == generator.end()) - << "At element " << i << " when accessing via an iterator " - << "created with the assignment operator.\n"; - EXPECT_TRUE(expected_values[i] == *it) - << "where i is " << i - << ", expected_values[i] is " << PrintValue(expected_values[i]) - << ", *it is " << PrintValue(*it) - << ", and 'it' is an iterator created with the copy constructor.\n"; - ++it; - } - EXPECT_TRUE(it == generator.end()) - << "At the presumed end of sequence when accessing via an iterator " - << "created with the assignment operator.\n"; -} - -template -void VerifyGeneratorIsEmpty(const ParamGenerator& generator) { - typename ParamGenerator::iterator it = generator.begin(); - EXPECT_TRUE(it == generator.end()); - - it = generator.begin(); - EXPECT_TRUE(it == generator.end()); -} - -// Generator tests. They test that each of the provided generator functions -// generates an expected sequence of values. The general test pattern -// instantiates a generator using one of the generator functions, -// checks the sequence produced by the generator using its iterator API, -// and then resets the iterator back to the beginning of the sequence -// and checks the sequence again. - -// Tests that iterators produced by generator functions conform to the -// ForwardIterator concept. -TEST(IteratorTest, ParamIteratorConformsToForwardIteratorConcept) { - const ParamGenerator gen = Range(0, 10); - ParamGenerator::iterator it = gen.begin(); - - // Verifies that iterator initialization works as expected. - ParamGenerator::iterator it2 = it; - EXPECT_TRUE(*it == *it2) << "Initialized iterators must point to the " - << "element same as its source points to"; - - // Verifies that iterator assignment works as expected. - ++it; - EXPECT_FALSE(*it == *it2); - it2 = it; - EXPECT_TRUE(*it == *it2) << "Assigned iterators must point to the " - << "element same as its source points to"; - - // Verifies that prefix operator++() returns *this. - EXPECT_EQ(&it, &(++it)) << "Result of the prefix operator++ must be " - << "refer to the original object"; - - // Verifies that the result of the postfix operator++ points to the value - // pointed to by the original iterator. - int original_value = *it; // Have to compute it outside of macro call to be - // unaffected by the parameter evaluation order. - EXPECT_EQ(original_value, *(it++)); - - // Verifies that prefix and postfix operator++() advance an iterator - // all the same. - it2 = it; - ++it; - ++it2; - EXPECT_TRUE(*it == *it2); -} - -// Tests that Range() generates the expected sequence. -TEST(RangeTest, IntRangeWithDefaultStep) { - const ParamGenerator gen = Range(0, 3); - const int expected_values[] = {0, 1, 2}; - VerifyGenerator(gen, expected_values); -} - -// Edge case. Tests that Range() generates the single element sequence -// as expected when provided with range limits that are equal. -TEST(RangeTest, IntRangeSingleValue) { - const ParamGenerator gen = Range(0, 1); - const int expected_values[] = {0}; - VerifyGenerator(gen, expected_values); -} - -// Edge case. Tests that Range() with generates empty sequence when -// supplied with an empty range. -TEST(RangeTest, IntRangeEmpty) { - const ParamGenerator gen = Range(0, 0); - VerifyGeneratorIsEmpty(gen); -} - -// Tests that Range() with custom step (greater then one) generates -// the expected sequence. -TEST(RangeTest, IntRangeWithCustomStep) { - const ParamGenerator gen = Range(0, 9, 3); - const int expected_values[] = {0, 3, 6}; - VerifyGenerator(gen, expected_values); -} - -// Tests that Range() with custom step (greater then one) generates -// the expected sequence when the last element does not fall on the -// upper range limit. Sequences generated by Range() must not have -// elements beyond the range limits. -TEST(RangeTest, IntRangeWithCustomStepOverUpperBound) { - const ParamGenerator gen = Range(0, 4, 3); - const int expected_values[] = {0, 3}; - VerifyGenerator(gen, expected_values); -} - -// Verifies that Range works with user-defined types that define -// copy constructor, operator=(), operator+(), and operator<(). -class DogAdder { - public: - explicit DogAdder(const char* a_value) : value_(a_value) {} - DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {} - - DogAdder operator=(const DogAdder& other) { - if (this != &other) - value_ = other.value_; - return *this; - } - DogAdder operator+(const DogAdder& other) const { - Message msg; - msg << value_.c_str() << other.value_.c_str(); - return DogAdder(msg.GetString().c_str()); - } - bool operator<(const DogAdder& other) const { - return value_ < other.value_; - } - const std::string& value() const { return value_; } - - private: - std::string value_; -}; - -TEST(RangeTest, WorksWithACustomType) { - const ParamGenerator gen = - Range(DogAdder("cat"), DogAdder("catdogdog"), DogAdder("dog")); - ParamGenerator::iterator it = gen.begin(); - - ASSERT_FALSE(it == gen.end()); - EXPECT_STREQ("cat", it->value().c_str()); - - ASSERT_FALSE(++it == gen.end()); - EXPECT_STREQ("catdog", it->value().c_str()); - - EXPECT_TRUE(++it == gen.end()); -} - -class IntWrapper { - public: - explicit IntWrapper(int a_value) : value_(a_value) {} - IntWrapper(const IntWrapper& other) : value_(other.value_) {} - - IntWrapper operator=(const IntWrapper& other) { - value_ = other.value_; - return *this; - } - // operator+() adds a different type. - IntWrapper operator+(int other) const { return IntWrapper(value_ + other); } - bool operator<(const IntWrapper& other) const { - return value_ < other.value_; - } - int value() const { return value_; } - - private: - int value_; -}; - -TEST(RangeTest, WorksWithACustomTypeWithDifferentIncrementType) { - const ParamGenerator gen = Range(IntWrapper(0), IntWrapper(2)); - ParamGenerator::iterator it = gen.begin(); - - ASSERT_FALSE(it == gen.end()); - EXPECT_EQ(0, it->value()); - - ASSERT_FALSE(++it == gen.end()); - EXPECT_EQ(1, it->value()); - - EXPECT_TRUE(++it == gen.end()); -} - -// Tests that ValuesIn() with an array parameter generates -// the expected sequence. -TEST(ValuesInTest, ValuesInArray) { - int array[] = {3, 5, 8}; - const ParamGenerator gen = ValuesIn(array); - VerifyGenerator(gen, array); -} - -// Tests that ValuesIn() with a const array parameter generates -// the expected sequence. -TEST(ValuesInTest, ValuesInConstArray) { - const int array[] = {3, 5, 8}; - const ParamGenerator gen = ValuesIn(array); - VerifyGenerator(gen, array); -} - -// Edge case. Tests that ValuesIn() with an array parameter containing a -// single element generates the single element sequence. -TEST(ValuesInTest, ValuesInSingleElementArray) { - int array[] = {42}; - const ParamGenerator gen = ValuesIn(array); - VerifyGenerator(gen, array); -} - -// Tests that ValuesIn() generates the expected sequence for an STL -// container (vector). -TEST(ValuesInTest, ValuesInVector) { - typedef ::std::vector ContainerType; - ContainerType values; - values.push_back(3); - values.push_back(5); - values.push_back(8); - const ParamGenerator gen = ValuesIn(values); - - const int expected_values[] = {3, 5, 8}; - VerifyGenerator(gen, expected_values); -} - -// Tests that ValuesIn() generates the expected sequence. -TEST(ValuesInTest, ValuesInIteratorRange) { - typedef ::std::vector ContainerType; - ContainerType values; - values.push_back(3); - values.push_back(5); - values.push_back(8); - const ParamGenerator gen = ValuesIn(values.begin(), values.end()); - - const int expected_values[] = {3, 5, 8}; - VerifyGenerator(gen, expected_values); -} - -// Edge case. Tests that ValuesIn() provided with an iterator range specifying a -// single value generates a single-element sequence. -TEST(ValuesInTest, ValuesInSingleElementIteratorRange) { - typedef ::std::vector ContainerType; - ContainerType values; - values.push_back(42); - const ParamGenerator gen = ValuesIn(values.begin(), values.end()); - - const int expected_values[] = {42}; - VerifyGenerator(gen, expected_values); -} - -// Edge case. Tests that ValuesIn() provided with an empty iterator range -// generates an empty sequence. -TEST(ValuesInTest, ValuesInEmptyIteratorRange) { - typedef ::std::vector ContainerType; - ContainerType values; - const ParamGenerator gen = ValuesIn(values.begin(), values.end()); - - VerifyGeneratorIsEmpty(gen); -} - -// Tests that the Values() generates the expected sequence. -TEST(ValuesTest, ValuesWorks) { - const ParamGenerator gen = Values(3, 5, 8); - - const int expected_values[] = {3, 5, 8}; - VerifyGenerator(gen, expected_values); -} - -// Tests that Values() generates the expected sequences from elements of -// different types convertible to ParamGenerator's parameter type. -TEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) { - const ParamGenerator gen = Values(3, 5.0f, 8.0); - - const double expected_values[] = {3.0, 5.0, 8.0}; - VerifyGenerator(gen, expected_values); -} - -TEST(ValuesTest, ValuesWorksForMaxLengthList) { - const ParamGenerator gen = Values( - 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, - 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, - 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, - 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, - 410, 420, 430, 440, 450, 460, 470, 480, 490, 500); - - const int expected_values[] = { - 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, - 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, - 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, - 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, - 410, 420, 430, 440, 450, 460, 470, 480, 490, 500}; - VerifyGenerator(gen, expected_values); -} - -// Edge case test. Tests that single-parameter Values() generates the sequence -// with the single value. -TEST(ValuesTest, ValuesWithSingleParameter) { - const ParamGenerator gen = Values(42); - - const int expected_values[] = {42}; - VerifyGenerator(gen, expected_values); -} - -// Tests that Bool() generates sequence (false, true). -TEST(BoolTest, BoolWorks) { - const ParamGenerator gen = Bool(); - - const bool expected_values[] = {false, true}; - VerifyGenerator(gen, expected_values); -} - -# if GTEST_HAS_COMBINE - -// Tests that Combine() with two parameters generates the expected sequence. -TEST(CombineTest, CombineWithTwoParameters) { - const char* foo = "foo"; - const char* bar = "bar"; - const ParamGenerator > gen = - Combine(Values(foo, bar), Values(3, 4)); - - tuple expected_values[] = { - make_tuple(foo, 3), make_tuple(foo, 4), - make_tuple(bar, 3), make_tuple(bar, 4)}; - VerifyGenerator(gen, expected_values); -} - -// Tests that Combine() with three parameters generates the expected sequence. -TEST(CombineTest, CombineWithThreeParameters) { - const ParamGenerator > gen = Combine(Values(0, 1), - Values(3, 4), - Values(5, 6)); - tuple expected_values[] = { - make_tuple(0, 3, 5), make_tuple(0, 3, 6), - make_tuple(0, 4, 5), make_tuple(0, 4, 6), - make_tuple(1, 3, 5), make_tuple(1, 3, 6), - make_tuple(1, 4, 5), make_tuple(1, 4, 6)}; - VerifyGenerator(gen, expected_values); -} - -// Tests that the Combine() with the first parameter generating a single value -// sequence generates a sequence with the number of elements equal to the -// number of elements in the sequence generated by the second parameter. -TEST(CombineTest, CombineWithFirstParameterSingleValue) { - const ParamGenerator > gen = Combine(Values(42), - Values(0, 1)); - - tuple expected_values[] = {make_tuple(42, 0), make_tuple(42, 1)}; - VerifyGenerator(gen, expected_values); -} - -// Tests that the Combine() with the second parameter generating a single value -// sequence generates a sequence with the number of elements equal to the -// number of elements in the sequence generated by the first parameter. -TEST(CombineTest, CombineWithSecondParameterSingleValue) { - const ParamGenerator > gen = Combine(Values(0, 1), - Values(42)); - - tuple expected_values[] = {make_tuple(0, 42), make_tuple(1, 42)}; - VerifyGenerator(gen, expected_values); -} - -// Tests that when the first parameter produces an empty sequence, -// Combine() produces an empty sequence, too. -TEST(CombineTest, CombineWithFirstParameterEmptyRange) { - const ParamGenerator > gen = Combine(Range(0, 0), - Values(0, 1)); - VerifyGeneratorIsEmpty(gen); -} - -// Tests that when the second parameter produces an empty sequence, -// Combine() produces an empty sequence, too. -TEST(CombineTest, CombineWithSecondParameterEmptyRange) { - const ParamGenerator > gen = Combine(Values(0, 1), - Range(1, 1)); - VerifyGeneratorIsEmpty(gen); -} - -// Edge case. Tests that combine works with the maximum number -// of parameters supported by Google Test (currently 10). -TEST(CombineTest, CombineWithMaxNumberOfParameters) { - const char* foo = "foo"; - const char* bar = "bar"; - const ParamGenerator > gen = Combine(Values(foo, bar), - Values(1), Values(2), - Values(3), Values(4), - Values(5), Values(6), - Values(7), Values(8), - Values(9)); - - tuple - expected_values[] = {make_tuple(foo, 1, 2, 3, 4, 5, 6, 7, 8, 9), - make_tuple(bar, 1, 2, 3, 4, 5, 6, 7, 8, 9)}; - VerifyGenerator(gen, expected_values); -} - -#if GTEST_LANG_CXX11 - -class NonDefaultConstructAssignString { - public: - NonDefaultConstructAssignString(const std::string& s) : str_(s) {} - - const std::string& str() const { return str_; } - - private: - std::string str_; - - // Not default constructible - NonDefaultConstructAssignString(); - // Not assignable - void operator=(const NonDefaultConstructAssignString&); -}; - -TEST(CombineTest, NonDefaultConstructAssign) { - const ParamGenerator > gen = - Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"), - NonDefaultConstructAssignString("B"))); - - ParamGenerator >::iterator it = - gen.begin(); - - EXPECT_EQ(0, std::get<0>(*it)); - EXPECT_EQ("A", std::get<1>(*it).str()); - ++it; - - EXPECT_EQ(0, std::get<0>(*it)); - EXPECT_EQ("B", std::get<1>(*it).str()); - ++it; - - EXPECT_EQ(1, std::get<0>(*it)); - EXPECT_EQ("A", std::get<1>(*it).str()); - ++it; - - EXPECT_EQ(1, std::get<0>(*it)); - EXPECT_EQ("B", std::get<1>(*it).str()); - ++it; - - EXPECT_TRUE(it == gen.end()); -} - -#endif // GTEST_LANG_CXX11 -# endif // GTEST_HAS_COMBINE - -// Tests that an generator produces correct sequence after being -// assigned from another generator. -TEST(ParamGeneratorTest, AssignmentWorks) { - ParamGenerator gen = Values(1, 2); - const ParamGenerator gen2 = Values(3, 4); - gen = gen2; - - const int expected_values[] = {3, 4}; - VerifyGenerator(gen, expected_values); -} - -// This test verifies that the tests are expanded and run as specified: -// one test per element from the sequence produced by the generator -// specified in INSTANTIATE_TEST_CASE_P. It also verifies that the test's -// fixture constructor, SetUp(), and TearDown() have run and have been -// supplied with the correct parameters. - -// The use of environment object allows detection of the case where no test -// case functionality is run at all. In this case TestCaseTearDown will not -// be able to detect missing tests, naturally. -template -class TestGenerationEnvironment : public ::testing::Environment { - public: - static TestGenerationEnvironment* Instance() { - static TestGenerationEnvironment* instance = new TestGenerationEnvironment; - return instance; - } - - void FixtureConstructorExecuted() { fixture_constructor_count_++; } - void SetUpExecuted() { set_up_count_++; } - void TearDownExecuted() { tear_down_count_++; } - void TestBodyExecuted() { test_body_count_++; } - - virtual void TearDown() { - // If all MultipleTestGenerationTest tests have been de-selected - // by the filter flag, the following checks make no sense. - bool perform_check = false; - - for (int i = 0; i < kExpectedCalls; ++i) { - Message msg; - msg << "TestsExpandedAndRun/" << i; - if (UnitTestOptions::FilterMatchesTest( - "TestExpansionModule/MultipleTestGenerationTest", - msg.GetString().c_str())) { - perform_check = true; - } - } - if (perform_check) { - EXPECT_EQ(kExpectedCalls, fixture_constructor_count_) - << "Fixture constructor of ParamTestGenerationTest test case " - << "has not been run as expected."; - EXPECT_EQ(kExpectedCalls, set_up_count_) - << "Fixture SetUp method of ParamTestGenerationTest test case " - << "has not been run as expected."; - EXPECT_EQ(kExpectedCalls, tear_down_count_) - << "Fixture TearDown method of ParamTestGenerationTest test case " - << "has not been run as expected."; - EXPECT_EQ(kExpectedCalls, test_body_count_) - << "Test in ParamTestGenerationTest test case " - << "has not been run as expected."; - } - } - - private: - TestGenerationEnvironment() : fixture_constructor_count_(0), set_up_count_(0), - tear_down_count_(0), test_body_count_(0) {} - - int fixture_constructor_count_; - int set_up_count_; - int tear_down_count_; - int test_body_count_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationEnvironment); -}; - -const int test_generation_params[] = {36, 42, 72}; - -class TestGenerationTest : public TestWithParam { - public: - enum { - PARAMETER_COUNT = - sizeof(test_generation_params)/sizeof(test_generation_params[0]) - }; - - typedef TestGenerationEnvironment Environment; - - TestGenerationTest() { - Environment::Instance()->FixtureConstructorExecuted(); - current_parameter_ = GetParam(); - } - virtual void SetUp() { - Environment::Instance()->SetUpExecuted(); - EXPECT_EQ(current_parameter_, GetParam()); - } - virtual void TearDown() { - Environment::Instance()->TearDownExecuted(); - EXPECT_EQ(current_parameter_, GetParam()); - } - - static void SetUpTestCase() { - bool all_tests_in_test_case_selected = true; - - for (int i = 0; i < PARAMETER_COUNT; ++i) { - Message test_name; - test_name << "TestsExpandedAndRun/" << i; - if ( !UnitTestOptions::FilterMatchesTest( - "TestExpansionModule/MultipleTestGenerationTest", - test_name.GetString())) { - all_tests_in_test_case_selected = false; - } - } - EXPECT_TRUE(all_tests_in_test_case_selected) - << "When running the TestGenerationTest test case all of its tests\n" - << "must be selected by the filter flag for the test case to pass.\n" - << "If not all of them are enabled, we can't reliably conclude\n" - << "that the correct number of tests have been generated."; - - collected_parameters_.clear(); - } - - static void TearDownTestCase() { - vector expected_values(test_generation_params, - test_generation_params + PARAMETER_COUNT); - // Test execution order is not guaranteed by Google Test, - // so the order of values in collected_parameters_ can be - // different and we have to sort to compare. - sort(expected_values.begin(), expected_values.end()); - sort(collected_parameters_.begin(), collected_parameters_.end()); - - EXPECT_TRUE(collected_parameters_ == expected_values); - } - - protected: - int current_parameter_; - static vector collected_parameters_; - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationTest); -}; -vector TestGenerationTest::collected_parameters_; - -TEST_P(TestGenerationTest, TestsExpandedAndRun) { - Environment::Instance()->TestBodyExecuted(); - EXPECT_EQ(current_parameter_, GetParam()); - collected_parameters_.push_back(GetParam()); -} -INSTANTIATE_TEST_CASE_P(TestExpansionModule, TestGenerationTest, - ValuesIn(test_generation_params)); - -// This test verifies that the element sequence (third parameter of -// INSTANTIATE_TEST_CASE_P) is evaluated in InitGoogleTest() and neither at -// the call site of INSTANTIATE_TEST_CASE_P nor in RUN_ALL_TESTS(). For -// that, we declare param_value_ to be a static member of -// GeneratorEvaluationTest and initialize it to 0. We set it to 1 in -// main(), just before invocation of InitGoogleTest(). After calling -// InitGoogleTest(), we set the value to 2. If the sequence is evaluated -// before or after InitGoogleTest, INSTANTIATE_TEST_CASE_P will create a -// test with parameter other than 1, and the test body will fail the -// assertion. -class GeneratorEvaluationTest : public TestWithParam { - public: - static int param_value() { return param_value_; } - static void set_param_value(int param_value) { param_value_ = param_value; } - - private: - static int param_value_; -}; -int GeneratorEvaluationTest::param_value_ = 0; - -TEST_P(GeneratorEvaluationTest, GeneratorsEvaluatedInMain) { - EXPECT_EQ(1, GetParam()); -} -INSTANTIATE_TEST_CASE_P(GenEvalModule, - GeneratorEvaluationTest, - Values(GeneratorEvaluationTest::param_value())); - -// Tests that generators defined in a different translation unit are -// functional. Generator extern_gen is defined in gtest-param-test_test2.cc. -extern ParamGenerator extern_gen; -class ExternalGeneratorTest : public TestWithParam {}; -TEST_P(ExternalGeneratorTest, ExternalGenerator) { - // Sequence produced by extern_gen contains only a single value - // which we verify here. - EXPECT_EQ(GetParam(), 33); -} -INSTANTIATE_TEST_CASE_P(ExternalGeneratorModule, - ExternalGeneratorTest, - extern_gen); - -// Tests that a parameterized test case can be defined in one translation -// unit and instantiated in another. This test will be instantiated in -// gtest-param-test_test2.cc. ExternalInstantiationTest fixture class is -// defined in gtest-param-test_test.h. -TEST_P(ExternalInstantiationTest, IsMultipleOf33) { - EXPECT_EQ(0, GetParam() % 33); -} - -// Tests that a parameterized test case can be instantiated with multiple -// generators. -class MultipleInstantiationTest : public TestWithParam {}; -TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) { -} -INSTANTIATE_TEST_CASE_P(Sequence1, MultipleInstantiationTest, Values(1, 2)); -INSTANTIATE_TEST_CASE_P(Sequence2, MultipleInstantiationTest, Range(3, 5)); - -// Tests that a parameterized test case can be instantiated -// in multiple translation units. This test will be instantiated -// here and in gtest-param-test_test2.cc. -// InstantiationInMultipleTranslationUnitsTest fixture class -// is defined in gtest-param-test_test.h. -TEST_P(InstantiationInMultipleTranslaionUnitsTest, IsMultipleOf42) { - EXPECT_EQ(0, GetParam() % 42); -} -INSTANTIATE_TEST_CASE_P(Sequence1, - InstantiationInMultipleTranslaionUnitsTest, - Values(42, 42*2)); - -// Tests that each iteration of parameterized test runs in a separate test -// object. -class SeparateInstanceTest : public TestWithParam { - public: - SeparateInstanceTest() : count_(0) {} - - static void TearDownTestCase() { - EXPECT_GE(global_count_, 2) - << "If some (but not all) SeparateInstanceTest tests have been " - << "filtered out this test will fail. Make sure that all " - << "GeneratorEvaluationTest are selected or de-selected together " - << "by the test filter."; - } - - protected: - int count_; - static int global_count_; -}; -int SeparateInstanceTest::global_count_ = 0; - -TEST_P(SeparateInstanceTest, TestsRunInSeparateInstances) { - EXPECT_EQ(0, count_++); - global_count_++; -} -INSTANTIATE_TEST_CASE_P(FourElemSequence, SeparateInstanceTest, Range(1, 4)); - -// Tests that all instantiations of a test have named appropriately. Test -// defined with TEST_P(TestCaseName, TestName) and instantiated with -// INSTANTIATE_TEST_CASE_P(SequenceName, TestCaseName, generator) must be named -// SequenceName/TestCaseName.TestName/i, where i is the 0-based index of the -// sequence element used to instantiate the test. -class NamingTest : public TestWithParam {}; - -TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) { - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); - - EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_case_name()); - - Message index_stream; - index_stream << "TestsReportCorrectNamesAndParameters/" << GetParam(); - EXPECT_STREQ(index_stream.GetString().c_str(), test_info->name()); - - EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param()); -} - -INSTANTIATE_TEST_CASE_P(ZeroToFiveSequence, NamingTest, Range(0, 5)); - -// Tests that macros in test names are expanded correctly. -class MacroNamingTest : public TestWithParam {}; - -#define PREFIX_WITH_FOO(test_name) Foo##test_name -#define PREFIX_WITH_MACRO(test_name) Macro##test_name - -TEST_P(PREFIX_WITH_MACRO(NamingTest), PREFIX_WITH_FOO(SomeTestName)) { - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); - - EXPECT_STREQ("FortyTwo/MacroNamingTest", test_info->test_case_name()); - EXPECT_STREQ("FooSomeTestName", test_info->name()); -} - -INSTANTIATE_TEST_CASE_P(FortyTwo, MacroNamingTest, Values(42)); - -// Tests the same thing for non-parametrized tests. -class MacroNamingTestNonParametrized : public ::testing::Test {}; - -TEST_F(PREFIX_WITH_MACRO(NamingTestNonParametrized), - PREFIX_WITH_FOO(SomeTestName)) { - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); - - EXPECT_STREQ("MacroNamingTestNonParametrized", test_info->test_case_name()); - EXPECT_STREQ("FooSomeTestName", test_info->name()); -} - -// Tests that user supplied custom parameter names are working correctly. -// Runs the test with a builtin helper method which uses PrintToString, -// as well as a custom function and custom functor to ensure all possible -// uses work correctly. -class CustomFunctorNamingTest : public TestWithParam {}; -TEST_P(CustomFunctorNamingTest, CustomTestNames) {} - -struct CustomParamNameFunctor { - std::string operator()(const ::testing::TestParamInfo& inf) { - return inf.param; - } -}; - -INSTANTIATE_TEST_CASE_P(CustomParamNameFunctor, - CustomFunctorNamingTest, - Values(std::string("FunctorName")), - CustomParamNameFunctor()); - -INSTANTIATE_TEST_CASE_P(AllAllowedCharacters, - CustomFunctorNamingTest, - Values("abcdefghijklmnopqrstuvwxyz", - "ABCDEFGHIJKLMNOPQRSTUVWXYZ", - "01234567890_"), - CustomParamNameFunctor()); - -inline std::string CustomParamNameFunction( - const ::testing::TestParamInfo& inf) { - return inf.param; -} - -class CustomFunctionNamingTest : public TestWithParam {}; -TEST_P(CustomFunctionNamingTest, CustomTestNames) {} - -INSTANTIATE_TEST_CASE_P(CustomParamNameFunction, - CustomFunctionNamingTest, - Values(std::string("FunctionName")), - CustomParamNameFunction); - -#if GTEST_LANG_CXX11 - -// Test custom naming with a lambda - -class CustomLambdaNamingTest : public TestWithParam {}; -TEST_P(CustomLambdaNamingTest, CustomTestNames) {} - -INSTANTIATE_TEST_CASE_P(CustomParamNameLambda, CustomLambdaNamingTest, - Values(std::string("LambdaName")), - [](const ::testing::TestParamInfo& inf) { - return inf.param; - }); - -#endif // GTEST_LANG_CXX11 - -TEST(CustomNamingTest, CheckNameRegistry) { - ::testing::UnitTest* unit_test = ::testing::UnitTest::GetInstance(); - std::set test_names; - for (int case_num = 0; - case_num < unit_test->total_test_case_count(); - ++case_num) { - const ::testing::TestCase* test_case = unit_test->GetTestCase(case_num); - for (int test_num = 0; - test_num < test_case->total_test_count(); - ++test_num) { - const ::testing::TestInfo* test_info = test_case->GetTestInfo(test_num); - test_names.insert(std::string(test_info->name())); - } - } - EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctorName")); - EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctionName")); -#if GTEST_LANG_CXX11 - EXPECT_EQ(1u, test_names.count("CustomTestNames/LambdaName")); -#endif // GTEST_LANG_CXX11 -} - -// Test a numeric name to ensure PrintToStringParamName works correctly. - -class CustomIntegerNamingTest : public TestWithParam {}; - -TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) { - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); - Message test_name_stream; - test_name_stream << "TestsReportCorrectNames/" << GetParam(); - EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); -} - -INSTANTIATE_TEST_CASE_P(PrintToString, - CustomIntegerNamingTest, - Range(0, 5), - ::testing::PrintToStringParamName()); - -// Test a custom struct with PrintToString. - -struct CustomStruct { - explicit CustomStruct(int value) : x(value) {} - int x; -}; - -std::ostream& operator<<(std::ostream& stream, const CustomStruct& val) { - stream << val.x; - return stream; -} - -class CustomStructNamingTest : public TestWithParam {}; - -TEST_P(CustomStructNamingTest, TestsReportCorrectNames) { - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); - Message test_name_stream; - test_name_stream << "TestsReportCorrectNames/" << GetParam(); - EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); -} - -INSTANTIATE_TEST_CASE_P(PrintToString, - CustomStructNamingTest, - Values(CustomStruct(0), CustomStruct(1)), - ::testing::PrintToStringParamName()); - -// Test that using a stateful parameter naming function works as expected. - -struct StatefulNamingFunctor { - StatefulNamingFunctor() : sum(0) {} - std::string operator()(const ::testing::TestParamInfo& info) { - int value = info.param + sum; - sum += info.param; - return ::testing::PrintToString(value); - } - int sum; -}; - -class StatefulNamingTest : public ::testing::TestWithParam { - protected: - StatefulNamingTest() : sum_(0) {} - int sum_; -}; - -TEST_P(StatefulNamingTest, TestsReportCorrectNames) { - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); - sum_ += GetParam(); - Message test_name_stream; - test_name_stream << "TestsReportCorrectNames/" << sum_; - EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); -} - -INSTANTIATE_TEST_CASE_P(StatefulNamingFunctor, - StatefulNamingTest, - Range(0, 5), - StatefulNamingFunctor()); - -// Class that cannot be streamed into an ostream. It needs to be copyable -// (and, in case of MSVC, also assignable) in order to be a test parameter -// type. Its default copy constructor and assignment operator do exactly -// what we need. -class Unstreamable { - public: - explicit Unstreamable(int value) : value_(value) {} - - private: - int value_; -}; - -class CommentTest : public TestWithParam {}; - -TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) { - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); - - EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param()); -} - -INSTANTIATE_TEST_CASE_P(InstantiationWithComments, - CommentTest, - Values(Unstreamable(1))); - -// Verify that we can create a hierarchy of test fixtures, where the base -// class fixture is not parameterized and the derived class is. In this case -// ParameterizedDerivedTest inherits from NonParameterizedBaseTest. We -// perform simple tests on both. -class NonParameterizedBaseTest : public ::testing::Test { - public: - NonParameterizedBaseTest() : n_(17) { } - protected: - int n_; -}; - -class ParameterizedDerivedTest : public NonParameterizedBaseTest, - public ::testing::WithParamInterface { - protected: - ParameterizedDerivedTest() : count_(0) { } - int count_; - static int global_count_; -}; - -int ParameterizedDerivedTest::global_count_ = 0; - -TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { - EXPECT_EQ(17, n_); -} - -TEST_P(ParameterizedDerivedTest, SeesSequence) { - EXPECT_EQ(17, n_); - EXPECT_EQ(0, count_++); - EXPECT_EQ(GetParam(), global_count_++); -} - -class ParameterizedDeathTest : public ::testing::TestWithParam { }; - -TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) { - EXPECT_DEATH_IF_SUPPORTED(GetParam(), - ".* value-parameterized test .*"); -} - -INSTANTIATE_TEST_CASE_P(RangeZeroToFive, ParameterizedDerivedTest, Range(0, 5)); - - -int main(int argc, char **argv) { - // Used in TestGenerationTest test case. - AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance()); - // Used in GeneratorEvaluationTest test case. Tests that the updated value - // will be picked up for instantiating tests in GeneratorEvaluationTest. - GeneratorEvaluationTest::set_param_value(1); - - ::testing::InitGoogleTest(&argc, argv); - - // Used in GeneratorEvaluationTest test case. Tests that value updated - // here will NOT be used for instantiating tests in - // GeneratorEvaluationTest. - GeneratorEvaluationTest::set_param_value(2); - - return RUN_ALL_TESTS(); -} diff --git a/googletest/test/gtest-param-test_test.h b/googletest/test/gtest-param-test_test.h deleted file mode 100644 index ea1e884..0000000 --- a/googletest/test/gtest-param-test_test.h +++ /dev/null @@ -1,53 +0,0 @@ -// 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: vladl@google.com (Vlad Losev) -// -// The Google C++ Testing and Mocking Framework (Google Test) -// -// This header file provides classes and functions used internally -// for testing Google Test itself. - -#ifndef GTEST_TEST_GTEST_PARAM_TEST_TEST_H_ -#define GTEST_TEST_GTEST_PARAM_TEST_TEST_H_ - -#include "gtest/gtest.h" - -// Test fixture for testing definition and instantiation of a test -// in separate translation units. -class ExternalInstantiationTest : public ::testing::TestWithParam { -}; - -// Test fixture for testing instantiation of a test in multiple -// translation units. -class InstantiationInMultipleTranslaionUnitsTest - : public ::testing::TestWithParam { -}; - -#endif // GTEST_TEST_GTEST_PARAM_TEST_TEST_H_ diff --git a/googletest/test/gtest-test-part_test.cc b/googletest/test/gtest-test-part_test.cc deleted file mode 100644 index ca8ba93..0000000 --- a/googletest/test/gtest-test-part_test.cc +++ /dev/null @@ -1,208 +0,0 @@ -// 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: mheule@google.com (Markus Heule) -// - -#include "gtest/gtest-test-part.h" - -#include "gtest/gtest.h" - -using testing::Message; -using testing::Test; -using testing::TestPartResult; -using testing::TestPartResultArray; - -namespace { - -// Tests the TestPartResult class. - -// The test fixture for testing TestPartResult. -class TestPartResultTest : public Test { - protected: - TestPartResultTest() - : r1_(TestPartResult::kSuccess, "foo/bar.cc", 10, "Success!"), - r2_(TestPartResult::kNonFatalFailure, "foo/bar.cc", -1, "Failure!"), - r3_(TestPartResult::kFatalFailure, NULL, -1, "Failure!") {} - - TestPartResult r1_, r2_, r3_; -}; - - -TEST_F(TestPartResultTest, ConstructorWorks) { - Message message; - message << "something is terribly wrong"; - message << static_cast(testing::internal::kStackTraceMarker); - message << "some unimportant stack trace"; - - const TestPartResult result(TestPartResult::kNonFatalFailure, - "some_file.cc", - 42, - message.GetString().c_str()); - - EXPECT_EQ(TestPartResult::kNonFatalFailure, result.type()); - EXPECT_STREQ("some_file.cc", result.file_name()); - EXPECT_EQ(42, result.line_number()); - EXPECT_STREQ(message.GetString().c_str(), result.message()); - EXPECT_STREQ("something is terribly wrong", result.summary()); -} - -TEST_F(TestPartResultTest, ResultAccessorsWork) { - const TestPartResult success(TestPartResult::kSuccess, - "file.cc", - 42, - "message"); - EXPECT_TRUE(success.passed()); - EXPECT_FALSE(success.failed()); - EXPECT_FALSE(success.nonfatally_failed()); - EXPECT_FALSE(success.fatally_failed()); - - const TestPartResult nonfatal_failure(TestPartResult::kNonFatalFailure, - "file.cc", - 42, - "message"); - EXPECT_FALSE(nonfatal_failure.passed()); - EXPECT_TRUE(nonfatal_failure.failed()); - EXPECT_TRUE(nonfatal_failure.nonfatally_failed()); - EXPECT_FALSE(nonfatal_failure.fatally_failed()); - - const TestPartResult fatal_failure(TestPartResult::kFatalFailure, - "file.cc", - 42, - "message"); - EXPECT_FALSE(fatal_failure.passed()); - EXPECT_TRUE(fatal_failure.failed()); - EXPECT_FALSE(fatal_failure.nonfatally_failed()); - EXPECT_TRUE(fatal_failure.fatally_failed()); -} - -// Tests TestPartResult::type(). -TEST_F(TestPartResultTest, type) { - EXPECT_EQ(TestPartResult::kSuccess, r1_.type()); - EXPECT_EQ(TestPartResult::kNonFatalFailure, r2_.type()); - EXPECT_EQ(TestPartResult::kFatalFailure, r3_.type()); -} - -// Tests TestPartResult::file_name(). -TEST_F(TestPartResultTest, file_name) { - EXPECT_STREQ("foo/bar.cc", r1_.file_name()); - EXPECT_STREQ(NULL, r3_.file_name()); -} - -// Tests TestPartResult::line_number(). -TEST_F(TestPartResultTest, line_number) { - EXPECT_EQ(10, r1_.line_number()); - EXPECT_EQ(-1, r2_.line_number()); -} - -// Tests TestPartResult::message(). -TEST_F(TestPartResultTest, message) { - EXPECT_STREQ("Success!", r1_.message()); -} - -// Tests TestPartResult::passed(). -TEST_F(TestPartResultTest, Passed) { - EXPECT_TRUE(r1_.passed()); - EXPECT_FALSE(r2_.passed()); - EXPECT_FALSE(r3_.passed()); -} - -// Tests TestPartResult::failed(). -TEST_F(TestPartResultTest, Failed) { - EXPECT_FALSE(r1_.failed()); - EXPECT_TRUE(r2_.failed()); - EXPECT_TRUE(r3_.failed()); -} - -// Tests TestPartResult::fatally_failed(). -TEST_F(TestPartResultTest, FatallyFailed) { - EXPECT_FALSE(r1_.fatally_failed()); - EXPECT_FALSE(r2_.fatally_failed()); - EXPECT_TRUE(r3_.fatally_failed()); -} - -// Tests TestPartResult::nonfatally_failed(). -TEST_F(TestPartResultTest, NonfatallyFailed) { - EXPECT_FALSE(r1_.nonfatally_failed()); - EXPECT_TRUE(r2_.nonfatally_failed()); - EXPECT_FALSE(r3_.nonfatally_failed()); -} - -// Tests the TestPartResultArray class. - -class TestPartResultArrayTest : public Test { - protected: - TestPartResultArrayTest() - : r1_(TestPartResult::kNonFatalFailure, "foo/bar.cc", -1, "Failure 1"), - r2_(TestPartResult::kFatalFailure, "foo/bar.cc", -1, "Failure 2") {} - - const TestPartResult r1_, r2_; -}; - -// Tests that TestPartResultArray initially has size 0. -TEST_F(TestPartResultArrayTest, InitialSizeIsZero) { - TestPartResultArray results; - EXPECT_EQ(0, results.size()); -} - -// Tests that TestPartResultArray contains the given TestPartResult -// after one Append() operation. -TEST_F(TestPartResultArrayTest, ContainsGivenResultAfterAppend) { - TestPartResultArray results; - results.Append(r1_); - EXPECT_EQ(1, results.size()); - EXPECT_STREQ("Failure 1", results.GetTestPartResult(0).message()); -} - -// Tests that TestPartResultArray contains the given TestPartResults -// after two Append() operations. -TEST_F(TestPartResultArrayTest, ContainsGivenResultsAfterTwoAppends) { - TestPartResultArray results; - results.Append(r1_); - results.Append(r2_); - EXPECT_EQ(2, results.size()); - EXPECT_STREQ("Failure 1", results.GetTestPartResult(0).message()); - EXPECT_STREQ("Failure 2", results.GetTestPartResult(1).message()); -} - -typedef TestPartResultArrayTest TestPartResultArrayDeathTest; - -// Tests that the program dies when GetTestPartResult() is called with -// an invalid index. -TEST_F(TestPartResultArrayDeathTest, DiesWhenIndexIsOutOfBound) { - TestPartResultArray results; - results.Append(r1_); - - EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(-1), ""); - EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(1), ""); -} - -// TODO(mheule@google.com): Add a test for the class HasNewFatalFailureHelper. - -} // namespace diff --git a/googletest/test/gtest_all_test.cc b/googletest/test/gtest_all_test.cc index e6c1b01..656066d 100644 --- a/googletest/test/gtest_all_test.cc +++ b/googletest/test/gtest_all_test.cc @@ -33,14 +33,14 @@ // // Sometimes it's desirable to build most of Google Test's own tests // by compiling a single file. This file serves this purpose. -#include "gtest-filepath_test.cc" -#include "gtest-linked_ptr_test.cc" -#include "gtest-message_test.cc" -#include "gtest-options_test.cc" -#include "gtest-port_test.cc" +#include "googletest-filepath-test.cc" +#include "googletest-linked-ptr-test.cc" +#include "googletest-message-test.cc" +#include "googletest-options-test.cc" +#include "googletest-port-test.cc" #include "gtest_pred_impl_unittest.cc" #include "gtest_prod_test.cc" -#include "gtest-test-part_test.cc" +#include "googletest-test-part-test.cc" #include "gtest-typed-test_test.cc" #include "gtest-typed-test2_test.cc" #include "gtest_unittest.cc" diff --git a/googletest/test/gtest_json_outfiles_test.py b/googletest/test/gtest_json_outfiles_test.py deleted file mode 100644 index 46010d8..0000000 --- a/googletest/test/gtest_json_outfiles_test.py +++ /dev/null @@ -1,162 +0,0 @@ -#!/usr/bin/env python -# Copyright 2018, 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_json_output module.""" - -import json -import os -import gtest_json_test_utils -import gtest_test_utils - -GTEST_OUTPUT_SUBDIR = 'json_outfiles' -GTEST_OUTPUT_1_TEST = 'gtest_xml_outfile1_test_' -GTEST_OUTPUT_2_TEST = 'gtest_xml_outfile2_test_' - -EXPECTED_1 = { - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'timestamp': u'*', - u'name': u'AllTests', - u'testsuites': [{ - u'name': u'PropertyOne', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [{ - u'name': u'TestSomeProperties', - u'status': u'RUN', - u'time': u'*', - u'classname': u'PropertyOne', - u'SetUpProp': u'1', - u'TestSomeProperty': u'1', - u'TearDownProp': u'1', - }], - }], -} - -EXPECTED_2 = { - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'timestamp': u'*', - u'name': u'AllTests', - u'testsuites': [{ - u'name': u'PropertyTwo', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [{ - u'name': u'TestSomeProperties', - u'status': u'RUN', - u'time': u'*', - u'classname': u'PropertyTwo', - u'SetUpProp': u'2', - u'TestSomeProperty': u'2', - u'TearDownProp': u'2', - }], - }], -} - - -class GTestJsonOutFilesTest(gtest_test_utils.TestCase): - """Unit test for Google Test's JSON 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(gtest_test_utils.GetTempDir(), - GTEST_OUTPUT_SUBDIR, '') - self.DeleteFilesAndDir() - - def tearDown(self): - self.DeleteFilesAndDir() - - def DeleteFilesAndDir(self): - try: - os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_1_TEST + '.json')) - except os.error: - pass - try: - os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_2_TEST + '.json')) - except os.error: - pass - try: - os.rmdir(self.output_dir_) - except os.error: - pass - - def testOutfile1(self): - self._TestOutFile(GTEST_OUTPUT_1_TEST, EXPECTED_1) - - def testOutfile2(self): - self._TestOutFile(GTEST_OUTPUT_2_TEST, EXPECTED_2) - - def _TestOutFile(self, test_name, expected): - gtest_prog_path = gtest_test_utils.GetTestExecutablePath(test_name) - command = [gtest_prog_path, '--gtest_output=json:%s' % self.output_dir_] - p = gtest_test_utils.Subprocess(command, - working_dir=gtest_test_utils.GetTempDir()) - self.assert_(p.exited) - self.assertEquals(0, p.exit_code) - - # 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 possibility, 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 + '.json' - 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) - - if os.path.isfile(output_file1): - with open(output_file1) as f: - actual = json.load(f) - else: - with open(output_file2) as f: - actual = json.load(f) - self.assertEqual(expected, gtest_json_test_utils.normalize(actual)) - - -if __name__ == '__main__': - os.environ['GTEST_STACK_TRACE_DEPTH'] = '0' - gtest_test_utils.Main() diff --git a/googletest/test/gtest_json_output_unittest.py b/googletest/test/gtest_json_output_unittest.py deleted file mode 100644 index 12047c4..0000000 --- a/googletest/test/gtest_json_output_unittest.py +++ /dev/null @@ -1,611 +0,0 @@ -#!/usr/bin/env python -# Copyright 2018, 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_json_output module.""" - -import datetime -import errno -import json -import os -import re -import sys - -import gtest_json_test_utils -import gtest_test_utils - -GTEST_FILTER_FLAG = '--gtest_filter' -GTEST_LIST_TESTS_FLAG = '--gtest_list_tests' -GTEST_OUTPUT_FLAG = '--gtest_output' -GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.json' -GTEST_PROGRAM_NAME = 'gtest_xml_output_unittest_' - -SUPPORTS_STACK_TRACES = False - -if SUPPORTS_STACK_TRACES: - STACK_TRACE_TEMPLATE = '\nStack trace:\n*' -else: - STACK_TRACE_TEMPLATE = '' - -EXPECTED_NON_EMPTY = { - u'tests': 23, - u'failures': 4, - u'disabled': 2, - u'errors': 0, - u'timestamp': u'*', - u'time': u'*', - u'ad_hoc_property': u'42', - u'name': u'AllTests', - u'testsuites': [ - { - u'name': u'SuccessfulTest', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'Succeeds', - u'status': u'RUN', - u'time': u'*', - u'classname': u'SuccessfulTest' - } - ] - }, - { - u'name': u'FailedTest', - u'tests': 1, - u'failures': 1, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'Fails', - u'status': u'RUN', - u'time': u'*', - u'classname': u'FailedTest', - u'failures': [ - { - u'failure': - u'gtest_xml_output_unittest_.cc:*\n' - u'Expected equality of these values:\n' - u' 1\n 2' + STACK_TRACE_TEMPLATE, - u'type': u'' - } - ] - } - ] - }, - { - u'name': u'DisabledTest', - u'tests': 1, - u'failures': 0, - u'disabled': 1, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'DISABLED_test_not_run', - u'status': u'NOTRUN', - u'time': u'*', - u'classname': u'DisabledTest' - } - ] - }, - { - u'name': u'MixedResultTest', - u'tests': 3, - u'failures': 1, - u'disabled': 1, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'Succeeds', - u'status': u'RUN', - u'time': u'*', - u'classname': u'MixedResultTest' - }, - { - u'name': u'Fails', - u'status': u'RUN', - u'time': u'*', - u'classname': u'MixedResultTest', - u'failures': [ - { - u'failure': - u'gtest_xml_output_unittest_.cc:*\n' - u'Expected equality of these values:\n' - u' 1\n 2' + STACK_TRACE_TEMPLATE, - u'type': u'' - }, - { - u'failure': - u'gtest_xml_output_unittest_.cc:*\n' - u'Expected equality of these values:\n' - u' 2\n 3' + STACK_TRACE_TEMPLATE, - u'type': u'' - } - ] - }, - { - u'name': u'DISABLED_test', - u'status': u'NOTRUN', - u'time': u'*', - u'classname': u'MixedResultTest' - } - ] - }, - { - u'name': u'XmlQuotingTest', - u'tests': 1, - u'failures': 1, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'OutputsCData', - u'status': u'RUN', - u'time': u'*', - u'classname': u'XmlQuotingTest', - u'failures': [ - { - u'failure': - u'gtest_xml_output_unittest_.cc:*\n' - u'Failed\nXML output: ' - u'' + - STACK_TRACE_TEMPLATE, - u'type': u'' - } - ] - } - ] - }, - { - u'name': u'InvalidCharactersTest', - u'tests': 1, - u'failures': 1, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'InvalidCharactersInMessage', - u'status': u'RUN', - u'time': u'*', - u'classname': u'InvalidCharactersTest', - u'failures': [ - { - u'failure': - u'gtest_xml_output_unittest_.cc:*\n' - u'Failed\nInvalid characters in brackets' - u' [\x01\x02]' + STACK_TRACE_TEMPLATE, - u'type': u'' - } - ] - } - ] - }, - { - u'name': u'PropertyRecordingTest', - u'tests': 4, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'SetUpTestCase': u'yes', - u'TearDownTestCase': u'aye', - u'testsuite': [ - { - u'name': u'OneProperty', - u'status': u'RUN', - u'time': u'*', - u'classname': u'PropertyRecordingTest', - u'key_1': u'1' - }, - { - u'name': u'IntValuedProperty', - u'status': u'RUN', - u'time': u'*', - u'classname': u'PropertyRecordingTest', - u'key_int': u'1' - }, - { - u'name': u'ThreeProperties', - u'status': u'RUN', - u'time': u'*', - u'classname': u'PropertyRecordingTest', - u'key_1': u'1', - u'key_2': u'2', - u'key_3': u'3' - }, - { - u'name': u'TwoValuesForOneKeyUsesLastValue', - u'status': u'RUN', - u'time': u'*', - u'classname': u'PropertyRecordingTest', - u'key_1': u'2' - } - ] - }, - { - u'name': u'NoFixtureTest', - u'tests': 3, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'RecordProperty', - u'status': u'RUN', - u'time': u'*', - u'classname': u'NoFixtureTest', - u'key': u'1' - }, - { - u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty', - u'status': u'RUN', - u'time': u'*', - u'classname': u'NoFixtureTest', - u'key_for_utility_int': u'1' - }, - { - u'name': - u'ExternalUtilityThatCallsRecordStringValuedProperty', - u'status': u'RUN', - u'time': u'*', - u'classname': u'NoFixtureTest', - u'key_for_utility_string': u'1' - } - ] - }, - { - u'name': u'TypedTest/0', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'HasTypeParamAttribute', - u'type_param': u'int', - u'status': u'RUN', - u'time': u'*', - u'classname': u'TypedTest/0' - } - ] - }, - { - u'name': u'TypedTest/1', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'HasTypeParamAttribute', - u'type_param': u'long', - u'status': u'RUN', - u'time': u'*', - u'classname': u'TypedTest/1' - } - ] - }, - { - u'name': u'Single/TypeParameterizedTestCase/0', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'HasTypeParamAttribute', - u'type_param': u'int', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/TypeParameterizedTestCase/0' - } - ] - }, - { - u'name': u'Single/TypeParameterizedTestCase/1', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'HasTypeParamAttribute', - u'type_param': u'long', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/TypeParameterizedTestCase/1' - } - ] - }, - { - u'name': u'Single/ValueParamTest', - u'tests': 4, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [ - { - u'name': u'HasValueParamAttribute/0', - u'value_param': u'33', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/ValueParamTest' - }, - { - u'name': u'HasValueParamAttribute/1', - u'value_param': u'42', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/ValueParamTest' - }, - { - u'name': u'AnotherTestThatHasValueParamAttribute/0', - u'value_param': u'33', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/ValueParamTest' - }, - { - u'name': u'AnotherTestThatHasValueParamAttribute/1', - u'value_param': u'42', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/ValueParamTest' - } - ] - } - ] -} - -EXPECTED_FILTERED = { - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'timestamp': u'*', - u'name': u'AllTests', - u'ad_hoc_property': u'42', - u'testsuites': [{ - u'name': u'SuccessfulTest', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'testsuite': [{ - u'name': u'Succeeds', - u'status': u'RUN', - u'time': u'*', - u'classname': u'SuccessfulTest', - }] - }], -} - -EXPECTED_EMPTY = { - u'tests': 0, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'timestamp': u'*', - u'name': u'AllTests', - u'testsuites': [], -} - -GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME) - -SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess( - [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output - - -class GTestJsonOutputUnitTest(gtest_test_utils.TestCase): - """Unit test for Google Test's JSON output functionality. - """ - - # This test currently breaks on platforms that do not support typed and - # type-parameterized tests, so we don't run it under them. - if SUPPORTS_TYPED_TESTS: - - def testNonEmptyJsonOutput(self): - """Verifies JSON output for a Google Test binary with non-empty output. - - Runs a test program that generates a non-empty JSON output, and - tests that the JSON output is expected. - """ - self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY, 1) - - def testEmptyJsonOutput(self): - """Verifies JSON output for a Google Test binary without actual tests. - - Runs a test program that generates an empty JSON output, and - tests that the JSON output is expected. - """ - - self._TestJsonOutput('gtest_no_test_unittest', EXPECTED_EMPTY, 0) - - def testTimestampValue(self): - """Checks whether the timestamp attribute in the JSON output is valid. - - Runs a test program that generates an empty JSON output, and checks if - the timestamp attribute in the testsuites tag is valid. - """ - actual = self._GetJsonOutput('gtest_no_test_unittest', [], 0) - date_time_str = actual['timestamp'] - # datetime.strptime() is only available in Python 2.5+ so we have to - # parse the expected datetime manually. - match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str) - self.assertTrue( - re.match, - 'JSON datettime string %s has incorrect format' % date_time_str) - date_time_from_json = datetime.datetime( - year=int(match.group(1)), month=int(match.group(2)), - day=int(match.group(3)), hour=int(match.group(4)), - minute=int(match.group(5)), second=int(match.group(6))) - - time_delta = abs(datetime.datetime.now() - date_time_from_json) - # timestamp value should be near the current local time - self.assertTrue(time_delta < datetime.timedelta(seconds=600), - 'time_delta is %s' % time_delta) - - def testDefaultOutputFile(self): - """Verifies the default output file name. - - Confirms that Google Test produces an JSON output file with the expected - default name if no name is explicitly specified. - """ - output_file = os.path.join(gtest_test_utils.GetTempDir(), - GTEST_DEFAULT_OUTPUT_FILE) - gtest_prog_path = gtest_test_utils.GetTestExecutablePath( - 'gtest_no_test_unittest') - try: - os.remove(output_file) - except OSError: - e = sys.exc_info()[1] - if e.errno != errno.ENOENT: - raise - - p = gtest_test_utils.Subprocess( - [gtest_prog_path, '%s=json' % GTEST_OUTPUT_FLAG], - working_dir=gtest_test_utils.GetTempDir()) - self.assert_(p.exited) - self.assertEquals(0, p.exit_code) - self.assert_(os.path.isfile(output_file)) - - def testSuppressedJsonOutput(self): - """Verifies that no JSON output is generated. - - Tests that no JSON file is generated if the default JSON listener is - shut down before RUN_ALL_TESTS is invoked. - """ - - json_path = os.path.join(gtest_test_utils.GetTempDir(), - GTEST_PROGRAM_NAME + 'out.json') - if os.path.isfile(json_path): - os.remove(json_path) - - command = [GTEST_PROGRAM_PATH, - '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path), - '--shut_down_xml'] - p = gtest_test_utils.Subprocess(command) - if p.terminated_by_signal: - # p.signal is available only if p.terminated_by_signal is True. - self.assertFalse( - p.terminated_by_signal, - '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal)) - else: - self.assert_(p.exited) - self.assertEquals(1, p.exit_code, - "'%s' exited with code %s, which doesn't match " - 'the expected exit code %s.' - % (command, p.exit_code, 1)) - - self.assert_(not os.path.isfile(json_path)) - - def testFilteredTestJsonOutput(self): - """Verifies JSON output when a filter is applied. - - Runs a test program that executes only some tests and verifies that - non-selected tests do not show up in the JSON output. - """ - - self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED, 0, - extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG]) - - def _GetJsonOutput(self, gtest_prog_name, extra_args, expected_exit_code): - """Returns the JSON output generated by running the program gtest_prog_name. - - Furthermore, the program's exit code must be expected_exit_code. - - Args: - gtest_prog_name: Google Test binary name. - extra_args: extra arguments to binary invocation. - expected_exit_code: program's exit code. - """ - json_path = os.path.join(gtest_test_utils.GetTempDir(), - gtest_prog_name + 'out.json') - gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name) - - command = ( - [gtest_prog_path, '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path)] + - extra_args - ) - p = gtest_test_utils.Subprocess(command) - if p.terminated_by_signal: - self.assert_(False, - '%s was killed by signal %d' % (gtest_prog_name, p.signal)) - else: - self.assert_(p.exited) - self.assertEquals(expected_exit_code, p.exit_code, - "'%s' exited with code %s, which doesn't match " - 'the expected exit code %s.' - % (command, p.exit_code, expected_exit_code)) - with open(json_path) as f: - actual = json.load(f) - return actual - - def _TestJsonOutput(self, gtest_prog_name, expected, - expected_exit_code, extra_args=None): - """Checks the JSON output generated by the Google Test binary. - - Asserts that the JSON document generated by running the program - gtest_prog_name matches expected_json, a string containing another - JSON document. Furthermore, the program's exit code must be - expected_exit_code. - - Args: - gtest_prog_name: Google Test binary name. - expected: expected output. - expected_exit_code: program's exit code. - extra_args: extra arguments to binary invocation. - """ - - actual = self._GetJsonOutput(gtest_prog_name, extra_args or [], - expected_exit_code) - self.assertEqual(expected, gtest_json_test_utils.normalize(actual)) - - -if __name__ == '__main__': - os.environ['GTEST_STACK_TRACE_DEPTH'] = '1' - gtest_test_utils.Main() diff --git a/googletest/test/gtest_uninitialized_test_.cc b/googletest/test/gtest_uninitialized_test_.cc deleted file mode 100644 index 2ba0e8b..0000000 --- a/googletest/test/gtest_uninitialized_test_.cc +++ /dev/null @@ -1,43 +0,0 @@ -// 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(); -} -- cgit v0.12