diff options
Diffstat (limited to 'security/nss/gtests/google_test/gtest/test')
77 files changed, 4138 insertions, 993 deletions
diff --git a/security/nss/gtests/google_test/gtest/test/BUILD.bazel b/security/nss/gtests/google_test/gtest/test/BUILD.bazel new file mode 100644 index 000000000..a930d65e0 --- /dev/null +++ b/security/nss/gtests/google_test/gtest/test/BUILD.bazel @@ -0,0 +1,527 @@ +# Copyright 2017 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: misterg@google.com (Gennadiy Civil) +# +# Bazel BUILD for The Google C++ Testing Framework (Google Test) + +licenses(["notice"]) + +config_setting( + name = "windows", + values = {"cpu": "x64_windows"}, +) + +config_setting( + name = "windows_msvc", + values = {"cpu": "x64_windows_msvc"}, +) + +config_setting( + name = "has_absl", + values = {"define": "absl=1"}, +) + +#on windows exclude gtest-tuple.h and googletest-tuple-test.cc +cc_test( + name = "gtest_all_test", + size = "small", + srcs = glob( + include = [ + "gtest-*.cc", + "googletest-*.cc", + "*.h", + "googletest/include/gtest/**/*.h", + ], + exclude = [ + "gtest-unittest-api_test.cc", + "googletest-tuple-test.cc", + "googletest/src/gtest-all.cc", + "gtest_all_test.cc", + "gtest-death-test_ex_test.cc", + "gtest-listener_test.cc", + "gtest-unittest-api_test.cc", + "googletest-param-test-test.cc", + "googletest-catch-exceptions-test_.cc", + "googletest-color-test_.cc", + "googletest-env-var-test_.cc", + "googletest-filter-unittest_.cc", + "googletest-break-on-failure-unittest_.cc", + "googletest-listener-test.cc", + "googletest-output-test_.cc", + "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({ + "//:windows": [], + "//:windows_msvc": [], + "//conditions:default": [ + "googletest-tuple-test.cc", + ], + }), + copts = select({ + "//:windows": ["-DGTEST_USE_OWN_TR1_TUPLE=0"], + "//:windows_msvc": ["-DGTEST_USE_OWN_TR1_TUPLE=0"], + "//conditions:default": ["-DGTEST_USE_OWN_TR1_TUPLE=1"], + }), + includes = [ + "googletest", + "googletest/include", + "googletest/include/internal", + "googletest/test", + ], + linkopts = select({ + "//:windows": [], + "//:windows_msvc": [], + "//conditions:default": [ + "-pthread", + ], + }), + deps = ["//:gtest_main"], +) + + +# Tests death tests. +cc_test( + name = "googletest-death-test-test", + size = "medium", + srcs = ["googletest-death-test-test.cc"], + deps = ["//:gtest_main"], +) + +cc_test( + name = "gtest_test_macro_stack_footprint_test", + size = "small", + srcs = ["gtest_test_macro_stack_footprint_test.cc"], + deps = ["//:gtest"], +) + +#These googletest tests have their own main() +cc_test( + name = "googletest-listener-test", + size = "small", + srcs = ["googletest-listener-test.cc"], + deps = ["//:gtest_main"], +) + +cc_test( + name = "gtest-unittest-api_test", + size = "small", + srcs = [ + "gtest-unittest-api_test.cc", + ], + deps = [ + "//:gtest", + ], +) + +cc_test( + name = "googletest-param-test-test", + size = "small", + srcs = [ + "googletest-param-test-test.cc", + "googletest-param-test-test.h", + "googletest-param-test2-test.cc", + ], + deps = ["//:gtest"], +) + +cc_test( + name = "gtest_unittest", + size = "small", + srcs = ["gtest_unittest.cc"], + args = ["--heap_check=strict"], + shard_count = 2, + deps = ["//:gtest_main"], +) + +# Py tests + +py_library( + name = "gtest_test_utils", + testonly = 1, + srcs = ["gtest_test_utils.py"], +) + +cc_binary( + name = "gtest_help_test_", + testonly = 1, + srcs = ["gtest_help_test_.cc"], + deps = ["//:gtest_main"], +) + +py_test( + name = "gtest_help_test", + size = "small", + srcs = ["gtest_help_test.py"], + data = [":gtest_help_test_"], + deps = [":gtest_test_utils"], +) + +cc_binary( + name = "googletest-output-test_", + testonly = 1, + srcs = ["googletest-output-test_.cc"], + deps = ["//:gtest"], +) + + +py_test( + name = "googletest-output-test", + size = "small", + srcs = ["googletest-output-test.py"], + args = select({ + ":has_absl": [], + "//conditions:default": ["--no_stacktrace_support"], + }), + data = [ + "googletest-output-test-golden-lin.txt", + ":googletest-output-test_", + ], + deps = [":gtest_test_utils"], +) + +cc_binary( + name = "googletest-color-test_", + testonly = 1, + srcs = ["googletest-color-test_.cc"], + deps = ["//:gtest"], +) + +py_test( + name = "googletest-color-test", + size = "small", + srcs = ["googletest-color-test.py"], + data = [":googletest-color-test_"], + deps = [":gtest_test_utils"], +) + +cc_binary( + name = "googletest-env-var-test_", + testonly = 1, + srcs = ["googletest-env-var-test_.cc"], + deps = ["//:gtest"], +) + +py_test( + name = "googletest-env-var-test", + size = "medium", + srcs = ["googletest-env-var-test.py"], + data = [":googletest-env-var-test_"], + deps = [":gtest_test_utils"], +) + +cc_binary( + name = "googletest-filter-unittest_", + testonly = 1, + srcs = ["googletest-filter-unittest_.cc"], + deps = ["//:gtest"], +) + +py_test( + name = "googletest-filter-unittest", + size = "medium", + srcs = ["googletest-filter-unittest.py"], + data = [":googletest-filter-unittest_"], + deps = [":gtest_test_utils"], +) + + +cc_binary( + name = "googletest-break-on-failure-unittest_", + testonly = 1, + srcs = ["googletest-break-on-failure-unittest_.cc"], + deps = ["//:gtest"], +) + + + +py_test( + name = "googletest-break-on-failure-unittest", + size = "small", + srcs = ["googletest-break-on-failure-unittest.py"], + data = [":googletest-break-on-failure-unittest_"], + deps = [":gtest_test_utils"], +) + + +cc_test( + name = "gtest_assert_by_exception_test", + size = "small", + srcs = ["gtest_assert_by_exception_test.cc"], + deps = ["//:gtest"], +) + + + +cc_binary( + name = "googletest-throw-on-failure-test_", + testonly = 1, + srcs = ["googletest-throw-on-failure-test_.cc"], + deps = ["//:gtest"], +) + +py_test( + name = "googletest-throw-on-failure-test", + size = "small", + srcs = ["googletest-throw-on-failure-test.py"], + data = [":googletest-throw-on-failure-test_"], + deps = [":gtest_test_utils"], +) + + +cc_binary( + name = "googletest-list-tests-unittest_", + testonly = 1, + srcs = ["googletest-list-tests-unittest_.cc"], + deps = ["//:gtest"], +) + +py_test( + name = "googletest-list-tests-unittest", + size = "small", + srcs = ["googletest-list-tests-unittest.py"], + data = [":googletest-list-tests-unittest_"], + deps = [":gtest_test_utils"], +) + +cc_binary( + name = "googletest-shuffle-test_", + srcs = ["googletest-shuffle-test_.cc"], + deps = ["//:gtest"], +) + +py_test( + name = "googletest-shuffle-test", + size = "small", + srcs = ["googletest-shuffle-test.py"], + data = [":googletest-shuffle-test_"], + deps = [":gtest_test_utils"], +) + +cc_binary( + name = "googletest-catch-exceptions-no-ex-test_", + testonly = 1, + srcs = ["googletest-catch-exceptions-test_.cc"], + deps = ["//:gtest_main"], +) + +cc_binary( + name = "googletest-catch-exceptions-ex-test_", + testonly = 1, + srcs = ["googletest-catch-exceptions-test_.cc"], + copts = ["-fexceptions"], + deps = ["//:gtest_main"], +) + +py_test( + name = "googletest-catch-exceptions-test", + size = "small", + srcs = ["googletest-catch-exceptions-test.py"], + data = [ + ":googletest-catch-exceptions-ex-test_", + ":googletest-catch-exceptions-no-ex-test_", + ], + deps = [":gtest_test_utils"], +) + +cc_binary( + name = "gtest_xml_output_unittest_", + testonly = 1, + srcs = ["gtest_xml_output_unittest_.cc"], + deps = ["//:gtest"], +) + +cc_test( + name = "gtest_no_test_unittest", + size = "small", + srcs = ["gtest_no_test_unittest.cc"], + deps = ["//:gtest"], +) + +py_test( + name = "gtest_xml_output_unittest", + size = "small", + srcs = [ + "gtest_xml_output_unittest.py", + "gtest_xml_test_utils.py", + ], + args = select({ + ":has_absl": [], + "//conditions:default": ["--no_stacktrace_support"], + }), + data = [ + # We invoke gtest_no_test_unittest to verify the XML output + # when the test program contains no test definition. + ":gtest_no_test_unittest", + ":gtest_xml_output_unittest_", + ], + deps = [":gtest_test_utils"], +) + +cc_binary( + name = "gtest_xml_outfile1_test_", + testonly = 1, + srcs = ["gtest_xml_outfile1_test_.cc"], + deps = ["//:gtest_main"], +) + +cc_binary( + name = "gtest_xml_outfile2_test_", + testonly = 1, + srcs = ["gtest_xml_outfile2_test_.cc"], + deps = ["//:gtest_main"], +) + +py_test( + name = "gtest_xml_outfiles_test", + size = "small", + srcs = [ + "gtest_xml_outfiles_test.py", + "gtest_xml_test_utils.py", + ], + data = [ + ":gtest_xml_outfile1_test_", + ":gtest_xml_outfile2_test_", + ], + deps = [":gtest_test_utils"], +) + +cc_binary( + name = "googletest-uninitialized-test_", + testonly = 1, + srcs = ["googletest-uninitialized-test_.cc"], + deps = ["//:gtest"], +) + +py_test( + name = "googletest-uninitialized-test", + size = "medium", + srcs = ["googletest-uninitialized-test.py"], + data = ["googletest-uninitialized-test_"], + deps = [":gtest_test_utils"], +) + +cc_binary( + name = "gtest_testbridge_test_", + testonly = 1, + srcs = ["gtest_testbridge_test_.cc"], + deps = ["//:gtest_main"], +) + +# Tests that filtering via testbridge works +py_test( + name = "gtest_testbridge_test", + size = "small", + srcs = ["gtest_testbridge_test.py"], + data = [":gtest_testbridge_test_"], + deps = [":gtest_test_utils"], +) + + +py_test( + name = "googletest-json-outfiles-test", + size = "small", + srcs = [ + "googletest-json-outfiles-test.py", + "gtest_json_test_utils.py", + ], + data = [ + ":gtest_xml_outfile1_test_", + ":gtest_xml_outfile2_test_", + ], + deps = [":gtest_test_utils"], +) + +py_test( + name = "googletest-json-output-unittest", + size = "medium", + srcs = [ + "googletest-json-output-unittest.py", + "gtest_json_test_utils.py", + ], + data = [ + # We invoke gtest_no_test_unittest to verify the JSON output + # when the test program contains no test definition. + ":gtest_no_test_unittest", + ":gtest_xml_output_unittest_", + ], + args = select({ + ":has_absl": [], + "//conditions:default": ["--no_stacktrace_support"], + }), + 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/security/nss/gtests/google_test/gtest/test/gtest_break_on_failure_unittest.py b/security/nss/gtests/google_test/gtest/test/googletest-break-on-failure-unittest.py index 78f3e0f53..a5dfbc693 100755..100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_break_on_failure_unittest.py +++ b/security/nss/gtests/google_test/gtest/test/googletest-break-on-failure-unittest.py @@ -34,16 +34,12 @@ A user can ask Google Test to seg-fault when an assertion fails, using either the GTEST_BREAK_ON_FAILURE environment variable or the --gtest_break_on_failure flag. This script tests such functionality -by invoking gtest_break_on_failure_unittest_ (a program written with +by invoking googletest-break-on-failure-unittest_ (a program written with Google Test) with different environments and command line flags. """ -__author__ = 'wan@google.com (Zhanyong Wan)' - -import gtest_test_utils import os -import sys - +import gtest_test_utils # Constants. @@ -61,9 +57,9 @@ THROW_ON_FAILURE_ENV_VAR = 'GTEST_THROW_ON_FAILURE' # The environment variable for enabling/disabling the catch-exceptions mode. CATCH_EXCEPTIONS_ENV_VAR = 'GTEST_CATCH_EXCEPTIONS' -# Path to the gtest_break_on_failure_unittest_ program. +# Path to the googletest-break-on-failure-unittest_ program. EXE_PATH = gtest_test_utils.GetTestExecutablePath( - 'gtest_break_on_failure_unittest_') + 'googletest-break-on-failure-unittest_') environ = gtest_test_utils.environ @@ -97,7 +93,7 @@ class GTestBreakOnFailureUnitTest(gtest_test_utils.TestCase): """ def RunAndVerify(self, env_var_value, flag_value, expect_seg_fault): - """Runs gtest_break_on_failure_unittest_ and verifies that it does + """Runs googletest-break-on-failure-unittest_ and verifies that it does (or does not) have a seg-fault. Args: diff --git a/security/nss/gtests/google_test/gtest/test/gtest_break_on_failure_unittest_.cc b/security/nss/gtests/google_test/gtest/test/googletest-break-on-failure-unittest_.cc index dd07478c0..f84957a2d 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_break_on_failure_unittest_.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-break-on-failure-unittest_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Unit test for Google Test's break-on-failure mode. // @@ -80,8 +79,7 @@ int main(int argc, char **argv) { SetUnhandledExceptionFilter(ExitWithExceptionCode); # endif -#endif - +#endif // GTEST_OS_WINDOWS testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/security/nss/gtests/google_test/gtest/test/gtest_catch_exceptions_test.py b/security/nss/gtests/google_test/gtest/test/googletest-catch-exceptions-test.py index e6fc22fd1..5d49c1023 100755..100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_catch_exceptions_test.py +++ b/security/nss/gtests/google_test/gtest/test/googletest-catch-exceptions-test.py @@ -30,15 +30,11 @@ """Tests Google Test's exception catching behavior. -This script invokes gtest_catch_exceptions_test_ and -gtest_catch_exceptions_ex_test_ (programs written with +This script invokes googletest-catch-exceptions-test_ and +googletest-catch-exceptions-ex-test_ (programs written with Google Test) and verifies their output. """ -__author__ = 'vladl@google.com (Vlad Losev)' - -import os - import gtest_test_utils # Constants. @@ -47,15 +43,15 @@ LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests' NO_CATCH_EXCEPTIONS_FLAG = FLAG_PREFIX + 'catch_exceptions=0' FILTER_FLAG = FLAG_PREFIX + 'filter' -# Path to the gtest_catch_exceptions_ex_test_ binary, compiled with +# Path to the googletest-catch-exceptions-ex-test_ binary, compiled with # exceptions enabled. EX_EXE_PATH = gtest_test_utils.GetTestExecutablePath( - 'gtest_catch_exceptions_ex_test_') + 'googletest-catch-exceptions-ex-test_') -# Path to the gtest_catch_exceptions_test_ binary, compiled with +# Path to the googletest-catch-exceptions-test_ binary, compiled with # exceptions disabled. EXE_PATH = gtest_test_utils.GetTestExecutablePath( - 'gtest_catch_exceptions_no_ex_test_') + 'googletest-catch-exceptions-no-ex-test_') environ = gtest_test_utils.environ SetEnvVar = gtest_test_utils.SetEnvVar diff --git a/security/nss/gtests/google_test/gtest/test/gtest_catch_exceptions_test_.cc b/security/nss/gtests/google_test/gtest/test/googletest-catch-exceptions-test_.cc index d0fc82c99..09dae7003 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_catch_exceptions_test_.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-catch-exceptions-test_.cc @@ -26,17 +26,17 @@ // 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. Tests in this file throw C++ or SEH -// exceptions, and the output is verified by gtest_catch_exceptions_test.py. - -#include "gtest/gtest.h" +// exceptions, and the output is verified by +// googletest-catch-exceptions-test.py. #include <stdio.h> // NOLINT #include <stdlib.h> // For exit(). +#include "gtest/gtest.h" + #if GTEST_HAS_SEH # include <windows.h> #endif @@ -138,7 +138,7 @@ TEST_F(CxxExceptionInConstructorTest, ThrowsExceptionInConstructor) { } // Exceptions in destructors are not supported in C++11. -#if !defined(__GXX_EXPERIMENTAL_CXX0X__) && __cplusplus < 201103L +#if !GTEST_LANG_CXX11 class CxxExceptionInDestructorTest : public Test { public: static void TearDownTestCase() { diff --git a/security/nss/gtests/google_test/gtest/test/gtest_color_test.py b/security/nss/gtests/google_test/gtest/test/googletest-color-test.py index d02a53ed8..f3b7c9990 100755..100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_color_test.py +++ b/security/nss/gtests/google_test/gtest/test/googletest-color-test.py @@ -31,17 +31,14 @@ """Verifies that Google Test correctly determines whether to use colors.""" -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import gtest_test_utils - -IS_WINDOWS = os.name = 'nt' +IS_WINDOWS = os.name == 'nt' COLOR_ENV_VAR = 'GTEST_COLOR' COLOR_FLAG = 'gtest_color' -COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_color_test_') +COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-color-test_') def SetEnvVar(env_var, value): @@ -54,7 +51,7 @@ def SetEnvVar(env_var, value): def UsesColor(term, color_env_var, color_flag): - """Runs gtest_color_test_ and returns its exit code.""" + """Runs googletest-color-test_ and returns its exit code.""" SetEnvVar('TERM', term) SetEnvVar(COLOR_ENV_VAR, color_env_var) diff --git a/security/nss/gtests/google_test/gtest/test/gtest_color_test_.cc b/security/nss/gtests/google_test/gtest/test/googletest-color-test_.cc index f61ebb89b..220a3a005 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_color_test_.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-color-test_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // A helper program for testing how Google Test determines whether to use // colors in the output. It prints "YES" and returns 1 if Google Test @@ -36,15 +35,7 @@ #include <stdio.h> #include "gtest/gtest.h" - -// Indicates that this translation unit is part of Google Test's -// implementation. It must come before gtest-internal-inl.h is -// included, or there will be a compiler error. This trick is to -// prevent a user from accidentally including gtest-internal-inl.h in -// his code. -#define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" -#undef GTEST_IMPLEMENTATION_ using testing::internal::ShouldUseColor; diff --git a/security/nss/gtests/google_test/gtest/test/gtest-death-test_test.cc b/security/nss/gtests/google_test/gtest/test/googletest-death-test-test.cc index b25bc2296..c0c3026fb 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-death-test_test.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-death-test-test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Tests for death tests. @@ -56,15 +55,7 @@ using testing::internal::AlwaysTrue; # endif // GTEST_OS_LINUX # include "gtest/gtest-spi.h" - -// Indicates that this translation unit is part of Google Test's -// implementation. It must come before gtest-internal-inl.h is -// included, or there will be a compiler error. This trick is to -// prevent a user from accidentally including gtest-internal-inl.h in -// his code. -# define GTEST_IMPLEMENTATION_ 1 # include "src/gtest-internal-inl.h" -# undef GTEST_IMPLEMENTATION_ namespace posix = ::testing::internal::posix; @@ -208,7 +199,7 @@ int DieInDebugElse12(int* sideeffect) { return 12; } -# if GTEST_OS_WINDOWS +# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA // Tests the ExitedWithCode predicate. TEST(ExitStatusPredicateTest, ExitedWithCode) { @@ -280,7 +271,7 @@ TEST(ExitStatusPredicateTest, KilledBySignal) { EXPECT_FALSE(pred_kill(status_segv)); } -# endif // GTEST_OS_WINDOWS +# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA // Tests that the death test macros expand to code which may or may not // be followed by operator<<, and that in either case the complete text @@ -313,14 +304,14 @@ void DieWithEmbeddedNul() { } # if GTEST_USES_PCRE + // Tests that EXPECT_DEATH and ASSERT_DEATH work when the error // message has a NUL character in it. TEST_F(TestForDeathTest, EmbeddedNulInMessage) { - // TODO(wan@google.com): <regex.h> doesn't support matching strings - // with embedded NUL characters - find a way to workaround it. EXPECT_DEATH(DieWithEmbeddedNul(), "my null world"); ASSERT_DEATH(DieWithEmbeddedNul(), "my null world"); } + # endif // GTEST_USES_PCRE // Tests that death test macros expand to code which interacts well with switch @@ -505,13 +496,17 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) { # if GTEST_HAS_GLOBAL_STRING - const string regex_str(regex_c_str); + const ::string regex_str(regex_c_str); EXPECT_DEATH(GlobalFunction(), regex_str); # endif // GTEST_HAS_GLOBAL_STRING +# if !GTEST_USES_PCRE + const ::std::string regex_std_str(regex_c_str); EXPECT_DEATH(GlobalFunction(), regex_std_str); + +# endif // !GTEST_USES_PCRE } // Tests that a non-void function can be used in a death test. @@ -621,7 +616,11 @@ TEST_F(TestForDeathTest, ReturnIsFailure) { TEST_F(TestForDeathTest, TestExpectDebugDeath) { int sideeffect = 0; - EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12") + // Put the regex in a local variable to make sure we don't get an "unused" + // warning in opt mode. + const char* regex = "death.*DieInDebugElse12"; + + EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex) << "Must accept a streamed message"; # ifdef NDEBUG @@ -784,11 +783,12 @@ static void TestExitMacros() { // Of all signals effects on the process exit code, only those of SIGABRT // are documented on Windows. - // See http://msdn.microsoft.com/en-us/library/dwwzkt4c(VS.71).aspx. + // See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c. EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar"; -# else +# elif !GTEST_OS_FUCHSIA + // Fuchsia has no unix signals. EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo"; ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar"; @@ -887,9 +887,9 @@ class MockDeathTestFactory : public DeathTestFactory { // Accessors. int AssumeRoleCalls() const { return assume_role_calls_; } int WaitCalls() const { return wait_calls_; } - int PassedCalls() const { return passed_args_.size(); } + size_t PassedCalls() const { return passed_args_.size(); } bool PassedArgument(int n) const { return passed_args_[n]; } - int AbortCalls() const { return abort_args_.size(); } + size_t AbortCalls() const { return abort_args_.size(); } DeathTest::AbortReason AbortArgument(int n) const { return abort_args_[n]; } @@ -1050,8 +1050,8 @@ TEST_F(MacroLogicDeathTest, NothingHappens) { EXPECT_FALSE(flag); EXPECT_EQ(0, factory_->AssumeRoleCalls()); EXPECT_EQ(0, factory_->WaitCalls()); - EXPECT_EQ(0, factory_->PassedCalls()); - EXPECT_EQ(0, factory_->AbortCalls()); + EXPECT_EQ(0U, factory_->PassedCalls()); + EXPECT_EQ(0U, factory_->AbortCalls()); EXPECT_FALSE(factory_->TestDeleted()); } @@ -1065,9 +1065,9 @@ TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) { EXPECT_FALSE(flag); EXPECT_EQ(1, factory_->AssumeRoleCalls()); EXPECT_EQ(1, factory_->WaitCalls()); - ASSERT_EQ(1, factory_->PassedCalls()); + ASSERT_EQ(1U, factory_->PassedCalls()); EXPECT_FALSE(factory_->PassedArgument(0)); - EXPECT_EQ(0, factory_->AbortCalls()); + EXPECT_EQ(0U, factory_->AbortCalls()); EXPECT_TRUE(factory_->TestDeleted()); } @@ -1080,9 +1080,9 @@ TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) { EXPECT_FALSE(flag); EXPECT_EQ(1, factory_->AssumeRoleCalls()); EXPECT_EQ(1, factory_->WaitCalls()); - ASSERT_EQ(1, factory_->PassedCalls()); + ASSERT_EQ(1U, factory_->PassedCalls()); EXPECT_TRUE(factory_->PassedArgument(0)); - EXPECT_EQ(0, factory_->AbortCalls()); + EXPECT_EQ(0U, factory_->AbortCalls()); EXPECT_TRUE(factory_->TestDeleted()); } @@ -1096,8 +1096,8 @@ TEST_F(MacroLogicDeathTest, ChildPerformsReturn) { EXPECT_TRUE(flag); EXPECT_EQ(1, factory_->AssumeRoleCalls()); EXPECT_EQ(0, factory_->WaitCalls()); - EXPECT_EQ(0, factory_->PassedCalls()); - EXPECT_EQ(1, factory_->AbortCalls()); + EXPECT_EQ(0U, factory_->PassedCalls()); + EXPECT_EQ(1U, factory_->AbortCalls()); EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT, factory_->AbortArgument(0)); EXPECT_TRUE(factory_->TestDeleted()); @@ -1112,13 +1112,13 @@ TEST_F(MacroLogicDeathTest, ChildDoesNotDie) { EXPECT_TRUE(flag); EXPECT_EQ(1, factory_->AssumeRoleCalls()); EXPECT_EQ(0, factory_->WaitCalls()); - EXPECT_EQ(0, factory_->PassedCalls()); + EXPECT_EQ(0U, factory_->PassedCalls()); // This time there are two calls to Abort: one since the test didn't // die, and another from the ReturnSentinel when it's destroyed. The // sentinel normally isn't destroyed if a test doesn't die, since // _exit(2) is called in that case by ForkingDeathTest, but not by // our MockDeathTest. - ASSERT_EQ(2, factory_->AbortCalls()); + ASSERT_EQ(2U, factory_->AbortCalls()); EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, factory_->AbortArgument(0)); EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT, @@ -1279,7 +1279,7 @@ TEST(ParseNaturalNumberTest, WorksForShorterIntegers) { # if GTEST_OS_WINDOWS TEST(EnvironmentTest, HandleFitsIntoSizeT) { - // TODO(vladl@google.com): Remove this test after this condition is verified + // FIXME: Remove this test after this condition is verified // in a static assertion in gtest-death-test.cc in the function // GetStatusFileDescriptor. ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t)); diff --git a/security/nss/gtests/google_test/gtest/test/gtest-death-test_ex_test.cc b/security/nss/gtests/google_test/gtest/test/googletest-death-test_ex_test.cc index b50a13d5e..b8b9470fc 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-death-test_ex_test.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-death-test_ex_test.cc @@ -26,8 +26,7 @@ // 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. @@ -69,7 +68,7 @@ TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) { "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"); + "googletest-death-test_ex_test.cc"); } # endif // GTEST_HAS_EXCEPTIONS diff --git a/security/nss/gtests/google_test/gtest/test/gtest_env_var_test.py b/security/nss/gtests/google_test/gtest/test/googletest-env-var-test.py index ac24337fa..e1efeee1e 100755..100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_env_var_test.py +++ b/security/nss/gtests/google_test/gtest/test/googletest-env-var-test.py @@ -31,8 +31,6 @@ """Verifies that Google Test correctly parses environment variables.""" -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import gtest_test_utils @@ -40,7 +38,7 @@ import gtest_test_utils IS_WINDOWS = os.name == 'nt' IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' -COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_env_var_test_') +COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-env-var-test_') environ = os.environ.copy() @@ -62,7 +60,7 @@ def SetEnvVar(env_var, value): def GetFlag(flag): - """Runs gtest_env_var_test_ and returns its output.""" + """Runs googletest-env-var-test_ and returns its output.""" args = [COMMAND] if flag is not None: @@ -81,12 +79,14 @@ def TestFlag(flag, test_val, default_val): class GTestEnvVarTest(gtest_test_utils.TestCase): + def testEnvVarAffectsFlag(self): """Tests that environment variable should affect the corresponding flag.""" TestFlag('break_on_failure', '1', '0') TestFlag('color', 'yes', 'auto') TestFlag('filter', 'FooTest.Bar', '*') + SetEnvVar('XML_OUTPUT_FILE', None) # For 'output' test TestFlag('output', 'xml:tmp/foo.xml', '') TestFlag('print_time', '0', '1') TestFlag('repeat', '999', '1') @@ -99,5 +99,19 @@ class GTestEnvVarTest(gtest_test_utils.TestCase): TestFlag('stack_trace_depth', '0', '100') + def testXmlOutputFile(self): + """Tests that $XML_OUTPUT_FILE affects the output flag.""" + + SetEnvVar('GTEST_OUTPUT', None) + SetEnvVar('XML_OUTPUT_FILE', 'tmp/bar.xml') + AssertEq('xml:tmp/bar.xml', GetFlag('output')) + + def testXmlOutputFileOverride(self): + """Tests that $XML_OUTPUT_FILE is overridden by $GTEST_OUTPUT.""" + + SetEnvVar('GTEST_OUTPUT', 'xml:tmp/foo.xml') + SetEnvVar('XML_OUTPUT_FILE', 'tmp/bar.xml') + AssertEq('xml:tmp/foo.xml', GetFlag('output')) + if __name__ == '__main__': gtest_test_utils.Main() diff --git a/security/nss/gtests/google_test/gtest/test/gtest_env_var_test_.cc b/security/nss/gtests/google_test/gtest/test/googletest-env-var-test_.cc index 539afc968..fd2aa82f7 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_env_var_test_.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-env-var-test_.cc @@ -26,19 +26,15 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // A helper program for testing that Google Test parses the environment // variables correctly. -#include "gtest/gtest.h" - #include <iostream> -#define GTEST_IMPLEMENTATION_ 1 +#include "gtest/gtest.h" #include "src/gtest-internal-inl.h" -#undef GTEST_IMPLEMENTATION_ using ::std::cout; @@ -117,7 +113,7 @@ int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); if (argc != 2) { - cout << "Usage: gtest_env_var_test_ NAME_OF_FLAG\n"; + cout << "Usage: googletest-env-var-test_ NAME_OF_FLAG\n"; return 1; } diff --git a/security/nss/gtests/google_test/gtest/test/gtest-filepath_test.cc b/security/nss/gtests/google_test/gtest/test/googletest-filepath-test.cc index ae9f55a0c..37f02fb4b 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-filepath_test.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-filepath-test.cc @@ -27,28 +27,17 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// Authors: keith.ray@gmail.com (Keith Ray) -// // Google Test filepath utilities // // This file tests classes and functions used internally by // Google Test. They are subject to change without notice. // -// This file is #included from gtest_unittest.cc, to avoid changing -// build or make-files for some existing Google Test clients. Do not -// #include this file anywhere else! +// This file is #included from gtest-internal.h. +// Do not #include this file anywhere else! #include "gtest/internal/gtest-filepath.h" #include "gtest/gtest.h" - -// Indicates that this translation unit is part of Google Test's -// implementation. It must come before gtest-internal-inl.h is -// included, or there will be a compiler error. This trick is to -// prevent a user from accidentally including gtest-internal-inl.h in -// his code. -#define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" -#undef GTEST_IMPLEMENTATION_ #if GTEST_OS_WINDOWS_MOBILE # include <windows.h> // NOLINT @@ -61,7 +50,7 @@ namespace internal { namespace { #if GTEST_OS_WINDOWS_MOBILE -// TODO(wan@google.com): Move these to the POSIX adapter section in +// FIXME: Move these to the POSIX adapter section in // gtest-port.h. // Windows CE doesn't have the remove C function. @@ -514,24 +503,6 @@ class DirectoryCreationTest : public Test { posix::RmDir(testdata_path_.c_str()); } - std::string TempDir() const { -#if GTEST_OS_WINDOWS_MOBILE - return "\\temp\\"; -#elif GTEST_OS_WINDOWS - const char* temp_dir = posix::GetEnv("TEMP"); - if (temp_dir == NULL || temp_dir[0] == '\0') - return "\\temp\\"; - else if (temp_dir[strlen(temp_dir) - 1] == '\\') - return temp_dir; - else - return std::string(temp_dir) + "\\"; -#elif GTEST_OS_LINUX_ANDROID - return "/sdcard/"; -#else - return "/tmp/"; -#endif // GTEST_OS_WINDOWS_MOBILE - } - void CreateTextFile(const char* filename) { FILE* f = posix::FOpen(filename, "w"); fprintf(f, "text\n"); diff --git a/security/nss/gtests/google_test/gtest/test/gtest_filter_unittest.py b/security/nss/gtests/google_test/gtest/test/googletest-filter-unittest.py index 0d1a77005..dc0b5bd9a 100755..100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_filter_unittest.py +++ b/security/nss/gtests/google_test/gtest/test/googletest-filter-unittest.py @@ -33,20 +33,17 @@ A user can specify which test(s) in a Google Test program to run via either the GTEST_FILTER environment variable or the --gtest_filter flag. This script tests such functionality by invoking -gtest_filter_unittest_ (a program written with Google Test) with different +googletest-filter-unittest_ (a program written with Google Test) with different environments and command line flags. Note that test sharding may also influence which tests are filtered. Therefore, we test that here also. """ -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import re import sets import sys - import gtest_test_utils # Constants. @@ -56,10 +53,12 @@ import gtest_test_utils # script in a subprocess to print whether the variable is STILL in # os.environ. We then use 'eval' to parse the child's output so that an # exception is thrown if the input is anything other than 'True' nor 'False'. -os.environ['EMPTY_VAR'] = '' -child = gtest_test_utils.Subprocess( - [sys.executable, '-c', 'import os; print \'EMPTY_VAR\' in os.environ']) -CAN_PASS_EMPTY_ENV = eval(child.output) +CAN_PASS_EMPTY_ENV = False +if sys.executable: + os.environ['EMPTY_VAR'] = '' + child = gtest_test_utils.Subprocess( + [sys.executable, '-c', 'import os; print \'EMPTY_VAR\' in os.environ']) + CAN_PASS_EMPTY_ENV = eval(child.output) # Check if this platform can unset environment variables in child processes. @@ -68,11 +67,14 @@ CAN_PASS_EMPTY_ENV = eval(child.output) # is NO LONGER in os.environ. # We use 'eval' to parse the child's output so that an exception # is thrown if the input is neither 'True' nor 'False'. -os.environ['UNSET_VAR'] = 'X' -del os.environ['UNSET_VAR'] -child = gtest_test_utils.Subprocess( - [sys.executable, '-c', 'import os; print \'UNSET_VAR\' not in os.environ']) -CAN_UNSET_ENV = eval(child.output) +CAN_UNSET_ENV = False +if sys.executable: + os.environ['UNSET_VAR'] = 'X' + del os.environ['UNSET_VAR'] + child = gtest_test_utils.Subprocess( + [sys.executable, '-c', 'import os; print \'UNSET_VAR\' not in os.environ' + ]) + CAN_UNSET_ENV = eval(child.output) # Checks if we should test with an empty filter. This doesn't @@ -94,10 +96,10 @@ SHARD_STATUS_FILE_ENV_VAR = 'GTEST_SHARD_STATUS_FILE' FILTER_FLAG = 'gtest_filter' # The command line flag for including disabled tests. -ALSO_RUN_DISABED_TESTS_FLAG = 'gtest_also_run_disabled_tests' +ALSO_RUN_DISABLED_TESTS_FLAG = 'gtest_also_run_disabled_tests' -# Command to run the gtest_filter_unittest_ program. -COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_filter_unittest_') +# Command to run the googletest-filter-unittest_ program. +COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-filter-unittest_') # Regex for determining whether parameterized tests are enabled in the binary. PARAM_TEST_REGEX = re.compile(r'/ParamTest') @@ -116,7 +118,7 @@ LIST_TESTS_FLAG = '--gtest_list_tests' SUPPORTS_DEATH_TESTS = 'HasDeathTest' in gtest_test_utils.Subprocess( [COMMAND, LIST_TESTS_FLAG]).output -# Full names of all tests in gtest_filter_unittests_. +# Full names of all tests in googletest-filter-unittests_. PARAM_TESTS = [ 'SeqP/ParamTest.TestX/0', 'SeqP/ParamTest.TestX/1', @@ -288,9 +290,10 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase): args=None, check_exit_0=False): """Checks that binary runs correct tests for the given filter and shard. - Runs all shards of gtest_filter_unittest_ with the given filter, and + Runs all shards of googletest-filter-unittest_ with the given filter, and verifies that the right set of tests were run. The union of tests run on each shard should be identical to tests_to_run, without duplicates. + If check_exit_0, . Args: gtest_filter: A filter to apply to the tests. @@ -325,7 +328,7 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase): def RunAndVerifyAllowingDisabled(self, gtest_filter, tests_to_run): """Checks that the binary runs correct set of tests for the given filter. - Runs gtest_filter_unittest_ with the given filter, and enables + Runs googletest-filter-unittest_ with the given filter, and enables disabled tests. Verifies that the right set of tests were run. Args: @@ -336,7 +339,7 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase): tests_to_run = self.AdjustForParameterizedTests(tests_to_run) # Construct the command line. - args = ['--%s' % ALSO_RUN_DISABED_TESTS_FLAG] + args = ['--%s' % ALSO_RUN_DISABLED_TESTS_FLAG] if gtest_filter is not None: args.append('--%s=%s' % (FILTER_FLAG, gtest_filter)) diff --git a/security/nss/gtests/google_test/gtest/test/gtest_filter_unittest_.cc b/security/nss/gtests/google_test/gtest/test/googletest-filter-unittest_.cc index 77deffc38..d335b6039 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_filter_unittest_.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-filter-unittest_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Unit test for Google Test test filters. // @@ -117,7 +116,6 @@ TEST(DISABLED_FoobarbazTest, TestA) { FAIL() << "Expected failure."; } -#if GTEST_HAS_PARAM_TEST class ParamTest : public testing::TestWithParam<int> { }; @@ -129,7 +127,6 @@ TEST_P(ParamTest, TestY) { INSTANTIATE_TEST_CASE_P(SeqP, ParamTest, testing::Values(1, 2)); INSTANTIATE_TEST_CASE_P(SeqQ, ParamTest, testing::Values(5, 6)); -#endif // GTEST_HAS_PARAM_TEST } // namespace diff --git a/security/nss/gtests/google_test/gtest/test/googletest-json-outfiles-test.py b/security/nss/gtests/google_test/gtest/test/googletest-json-outfiles-test.py new file mode 100644 index 000000000..c99be48e8 --- /dev/null +++ b/security/nss/gtests/google_test/gtest/test/googletest-json-outfiles-test.py @@ -0,0 +1,162 @@ +#!/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) + + # FIXME: 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 + # when 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/security/nss/gtests/google_test/gtest/test/googletest-json-output-unittest.py b/security/nss/gtests/google_test/gtest/test/googletest-json-output-unittest.py new file mode 100644 index 000000000..57dcd5fa1 --- /dev/null +++ b/security/nss/gtests/google_test/gtest/test/googletest-json-output-unittest.py @@ -0,0 +1,618 @@ +#!/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_' + +# The flag indicating stacktraces are not supported +NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support' + +SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv + +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: <?xml encoding="utf-8">' + u'<top><![CDATA[cdata text]]></top>' + + 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__': + if NO_STACKTRACE_SUPPORT_FLAG in sys.argv: + # unittest.main() can't handle unknown flags + sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG) + + os.environ['GTEST_STACK_TRACE_DEPTH'] = '1' + gtest_test_utils.Main() diff --git a/security/nss/gtests/google_test/gtest/test/gtest-linked_ptr_test.cc b/security/nss/gtests/google_test/gtest/test/googletest-linked-ptr-test.cc index 6fcf5124a..fa00f3429 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-linked_ptr_test.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-linked-ptr-test.cc @@ -26,13 +26,10 @@ // 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: Dan Egnor (egnor@google.com) -// Ported to Windows: Vadim Berman (vadimb@google.com) - -#include "gtest/internal/gtest-linked_ptr.h" #include <stdlib.h> + +#include "gtest/internal/gtest-linked_ptr.h" #include "gtest/gtest.h" namespace { diff --git a/security/nss/gtests/google_test/gtest/test/gtest_list_tests_unittest.py b/security/nss/gtests/google_test/gtest/test/googletest-list-tests-unittest.py index 925b09d9c..81423a339 100755..100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_list_tests_unittest.py +++ b/security/nss/gtests/google_test/gtest/test/googletest-list-tests-unittest.py @@ -33,25 +33,22 @@ A user can ask Google Test to list all tests by specifying the --gtest_list_tests flag. This script tests such functionality -by invoking gtest_list_tests_unittest_ (a program written with +by invoking googletest-list-tests-unittest_ (a program written with Google Test) the command line flags. """ -__author__ = 'phanna@google.com (Patrick Hanna)' - -import gtest_test_utils import re - +import gtest_test_utils # Constants. # The command line flag for enabling/disabling listing all tests. LIST_TESTS_FLAG = 'gtest_list_tests' -# Path to the gtest_list_tests_unittest_ program. -EXE_PATH = gtest_test_utils.GetTestExecutablePath('gtest_list_tests_unittest_') +# Path to the googletest-list-tests-unittest_ program. +EXE_PATH = gtest_test_utils.GetTestExecutablePath('googletest-list-tests-unittest_') -# The expected output when running gtest_list_tests_unittest_ with +# The expected output when running googletest-list-tests-unittest_ with # --gtest_list_tests EXPECTED_OUTPUT_NO_FILTER_RE = re.compile(r"""FooDeathTest\. Test1 @@ -71,7 +68,7 @@ FooTest\. TypedTest/0\. # TypeParam = (VeryLo{245}|class VeryLo{239})\.\.\. TestA TestB -TypedTest/1\. # TypeParam = int\s*\* +TypedTest/1\. # TypeParam = int\s*\*( __ptr64)? TestA TestB TypedTest/2\. # TypeParam = .*MyArray<bool,\s*42> @@ -80,7 +77,7 @@ TypedTest/2\. # TypeParam = .*MyArray<bool,\s*42> My/TypeParamTest/0\. # TypeParam = (VeryLo{245}|class VeryLo{239})\.\.\. TestA TestB -My/TypeParamTest/1\. # TypeParam = int\s*\* +My/TypeParamTest/1\. # TypeParam = int\s*\*( __ptr64)? TestA TestB My/TypeParamTest/2\. # TypeParam = .*MyArray<bool,\s*42> @@ -95,7 +92,7 @@ MyInstantiation/ValueParamTest\. TestB/2 # GetParam\(\) = a very\\nlo{241}\.\.\. """) -# The expected output when running gtest_list_tests_unittest_ with +# The expected output when running googletest-list-tests-unittest_ with # --gtest_list_tests and --gtest_filter=Foo*. EXPECTED_OUTPUT_FILTER_FOO_RE = re.compile(r"""FooDeathTest\. Test1 @@ -115,7 +112,7 @@ FooTest\. def Run(args): - """Runs gtest_list_tests_unittest_ and returns the list of tests printed.""" + """Runs googletest-list-tests-unittest_ and returns the list of tests printed.""" return gtest_test_utils.Subprocess([EXE_PATH] + args, capture_stderr=False).output @@ -123,11 +120,12 @@ def Run(args): # The unit test. + class GTestListTestsUnitTest(gtest_test_utils.TestCase): """Tests using the --gtest_list_tests flag to list all tests.""" def RunAndVerify(self, flag_value, expected_output_re, other_flag): - """Runs gtest_list_tests_unittest_ and verifies that it prints + """Runs googletest-list-tests-unittest_ and verifies that it prints the correct tests. Args: diff --git a/security/nss/gtests/google_test/gtest/test/gtest_list_tests_unittest_.cc b/security/nss/gtests/google_test/gtest/test/googletest-list-tests-unittest_.cc index 907c176ba..f473c7d1a 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_list_tests_unittest_.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-list-tests-unittest_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: phanna@google.com (Patrick Hanna) + // Unit test for Google Test's --gtest_list_tests flag. // diff --git a/security/nss/gtests/google_test/gtest/test/gtest-listener_test.cc b/security/nss/gtests/google_test/gtest/test/googletest-listener-test.cc index 99662cff3..835559715 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-listener_test.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-listener-test.cc @@ -25,17 +25,17 @@ // 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) -// -// The Google C++ Testing Framework (Google Test) +// The Google C++ Testing and Mocking Framework (Google Test) // // This file verifies Google Test event listeners receive events at the // right times. -#include "gtest/gtest.h" #include <vector> +#include "gtest/gtest.h" + using ::testing::AddGlobalTestEnvironment; using ::testing::Environment; using ::testing::InitGoogleTest; @@ -176,16 +176,16 @@ using ::testing::internal::EventRecordingListener; void VerifyResults(const std::vector<std::string>& data, const char* const* expected_data, - int expected_data_size) { - const int actual_size = data.size(); + size_t expected_data_size) { + const size_t actual_size = data.size(); // If the following assertion fails, a new entry will be appended to // data. Hence we save data.size() first. EXPECT_EQ(expected_data_size, actual_size); // Compares the common prefix. - const int shorter_size = expected_data_size <= actual_size ? + const size_t shorter_size = expected_data_size <= actual_size ? expected_data_size : actual_size; - int i = 0; + size_t i = 0; for (; i < shorter_size; ++i) { ASSERT_STREQ(expected_data[i], data[i].c_str()) << "at position " << i; @@ -193,7 +193,8 @@ void VerifyResults(const std::vector<std::string>& data, // Prints extra elements in the actual data. for (; i < actual_size; ++i) { - printf(" Actual event #%d: %s\n", i, data[i].c_str()); + printf(" Actual event #%lu: %s\n", + static_cast<unsigned long>(i), data[i].c_str()); } } diff --git a/security/nss/gtests/google_test/gtest/test/gtest-message_test.cc b/security/nss/gtests/google_test/gtest/test/googletest-message-test.cc index 175238ef4..c6445853e 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-message_test.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-message-test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Tests for the Message class. diff --git a/security/nss/gtests/google_test/gtest/test/gtest-options_test.cc b/security/nss/gtests/google_test/gtest/test/googletest-options-test.cc index 5586dc3b1..edd4eba3b 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-options_test.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-options-test.cc @@ -27,8 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// Authors: keith.ray@gmail.com (Keith Ray) -// // Google Test UnitTestOptions tests // // This file tests classes and functions used internally by @@ -46,14 +44,7 @@ # include <direct.h> #endif // GTEST_OS_WINDOWS_MOBILE -// Indicates that this translation unit is part of Google Test's -// implementation. It must come before gtest-internal-inl.h is -// included, or there will be a compiler error. This trick is to -// prevent a user from accidentally including gtest-internal-inl.h in -// his code. -#define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" -#undef GTEST_IMPLEMENTATION_ namespace testing { namespace internal { @@ -107,15 +98,16 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) { const std::string exe_str = GetCurrentExecutableName().string(); #if GTEST_OS_WINDOWS const bool success = - _strcmpi("gtest-options_test", exe_str.c_str()) == 0 || + _strcmpi("googletest-options-test", exe_str.c_str()) == 0 || _strcmpi("gtest-options-ex_test", exe_str.c_str()) == 0 || _strcmpi("gtest_all_test", exe_str.c_str()) == 0 || _strcmpi("gtest_dll_test", exe_str.c_str()) == 0; +#elif GTEST_OS_FUCHSIA + const bool success = exe_str == "app"; #else - // TODO(wan@google.com): remove the hard-coded "lt-" prefix when - // Chandler Carruth's libtool replacement is ready. + // FIXME: remove the hard-coded "lt-" prefix when libtool replacement is ready const bool success = - exe_str == "gtest-options_test" || + exe_str == "googletest-options-test" || exe_str == "gtest_all_test" || exe_str == "lt-gtest_all_test" || exe_str == "gtest_dll_test"; @@ -124,6 +116,8 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) { FAIL() << "GetCurrentExecutableName() returns " << exe_str; } +#if !GTEST_OS_FUCHSIA + class XmlOutputChangeDirTest : public Test { protected: virtual void SetUp() { @@ -210,6 +204,8 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsolutePath) { #endif } +#endif // !GTEST_OS_FUCHSIA + } // namespace } // namespace internal } // namespace testing diff --git a/security/nss/gtests/google_test/gtest/test/gtest_output_test_golden_lin.txt b/security/nss/gtests/google_test/gtest/test/googletest-output-test-golden-lin.txt index da541700e..86da845b7 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_output_test_golden_lin.txt +++ b/security/nss/gtests/google_test/gtest/test/googletest-output-test-golden-lin.txt @@ -1,13 +1,18 @@ The non-test part of the code is expected to have 2 failures. -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Value of: false Actual: false Expected: true -gtest_output_test_.cc:#: Failure -Value of: 3 -Expected: 2 -[0;32m[==========] [mRunning 64 tests from 28 test cases. +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 2 + 3 +Stack trace: (omitted) + +[0;32m[==========] [mRunning 76 tests from 34 test cases. [0;32m[----------] [mGlobal test environment set-up. FooEnvironment::SetUp() called. BarEnvironment::SetUp() called. @@ -33,237 +38,351 @@ BarEnvironment::SetUp() called. [0;32m[ OK ] [mPassingTest.PassingTest2 [0;32m[----------] [m2 tests from NonfatalFailureTest [0;32m[ RUN ] [mNonfatalFailureTest.EscapesStringOperands -gtest_output_test_.cc:#: Failure -Value of: actual - Actual: "actual \"string\"" -Expected: kGoldenString -Which is: "\"Line" -gtest_output_test_.cc:#: Failure -Value of: actual - Actual: "actual \"string\"" -Expected: golden -Which is: "\"Line" +googletest-output-test_.cc:#: Failure +Expected equality of these values: + kGoldenString + Which is: "\"Line" + actual + Which is: "actual \"string\"" +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Expected equality of these values: + golden + Which is: "\"Line" + actual + Which is: "actual \"string\"" +Stack trace: (omitted) + [0;31m[ FAILED ] [mNonfatalFailureTest.EscapesStringOperands [0;32m[ RUN ] [mNonfatalFailureTest.DiffForLongStrings -gtest_output_test_.cc:#: Failure -Value of: "Line 2" -Expected: golden_str -Which is: "\"Line\0 1\"\nLine 2" +googletest-output-test_.cc:#: Failure +Expected equality of these values: + golden_str + Which is: "\"Line\0 1\"\nLine 2" + "Line 2" With diff: @@ -1,2 @@ -\"Line\0 1\" Line 2 +Stack trace: (omitted) + [0;31m[ FAILED ] [mNonfatalFailureTest.DiffForLongStrings [0;32m[----------] [m3 tests from FatalFailureTest [0;32m[ RUN ] [mFatalFailureTest.FatalFailureInSubroutine (expecting a failure that x should be 1) -gtest_output_test_.cc:#: Failure -Value of: x - Actual: 2 -Expected: 1 +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + x + Which is: 2 +Stack trace: (omitted) + [0;31m[ FAILED ] [mFatalFailureTest.FatalFailureInSubroutine [0;32m[ RUN ] [mFatalFailureTest.FatalFailureInNestedSubroutine (expecting a failure that x should be 1) -gtest_output_test_.cc:#: Failure -Value of: x - Actual: 2 -Expected: 1 +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + x + Which is: 2 +Stack trace: (omitted) + [0;31m[ FAILED ] [mFatalFailureTest.FatalFailureInNestedSubroutine [0;32m[ RUN ] [mFatalFailureTest.NonfatalFailureInSubroutine (expecting a failure on false) -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Value of: false Actual: false Expected: true +Stack trace: (omitted) + [0;31m[ FAILED ] [mFatalFailureTest.NonfatalFailureInSubroutine [0;32m[----------] [m1 test from LoggingTest [0;32m[ RUN ] [mLoggingTest.InterleavingLoggingAndAssertions (expecting 2 failures on (3) >= (a[i])) i == 0 i == 1 -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Expected: (3) >= (a[i]), actual: 3 vs 9 +Stack trace: (omitted) + i == 2 i == 3 -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Expected: (3) >= (a[i]), actual: 3 vs 6 +Stack trace: (omitted) + [0;31m[ FAILED ] [mLoggingTest.InterleavingLoggingAndAssertions -[0;32m[----------] [m6 tests from SCOPED_TRACETest +[0;32m[----------] [m7 tests from SCOPED_TRACETest +[0;32m[ RUN ] [mSCOPED_TRACETest.AcceptedValues +googletest-output-test_.cc:#: Failure +Failed +Just checking that all these values work fine. +Google Test trace: +googletest-output-test_.cc:#: (null) +googletest-output-test_.cc:#: 1337 +googletest-output-test_.cc:#: std::string +googletest-output-test_.cc:#: literal string +Stack trace: (omitted) + +[0;31m[ FAILED ] [mSCOPED_TRACETest.AcceptedValues [0;32m[ RUN ] [mSCOPED_TRACETest.ObeysScopes (expected to fail) -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Failed This failure is expected, and shouldn't have a trace. -gtest_output_test_.cc:#: Failure +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed This failure is expected, and should have a trace. Google Test trace: -gtest_output_test_.cc:#: Expected trace -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Expected trace +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed This failure is expected, and shouldn't have a trace. +Stack trace: (omitted) + [0;31m[ FAILED ] [mSCOPED_TRACETest.ObeysScopes [0;32m[ RUN ] [mSCOPED_TRACETest.WorksInLoop (expected to fail) -gtest_output_test_.cc:#: Failure -Value of: n - Actual: 1 -Expected: 2 +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 2 + n + Which is: 1 Google Test trace: -gtest_output_test_.cc:#: i = 1 -gtest_output_test_.cc:#: Failure -Value of: n - Actual: 2 -Expected: 1 +googletest-output-test_.cc:#: i = 1 +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + n + Which is: 2 Google Test trace: -gtest_output_test_.cc:#: i = 2 +googletest-output-test_.cc:#: i = 2 +Stack trace: (omitted) + [0;31m[ FAILED ] [mSCOPED_TRACETest.WorksInLoop [0;32m[ RUN ] [mSCOPED_TRACETest.WorksInSubroutine (expected to fail) -gtest_output_test_.cc:#: Failure -Value of: n - Actual: 1 -Expected: 2 +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 2 + n + Which is: 1 Google Test trace: -gtest_output_test_.cc:#: n = 1 -gtest_output_test_.cc:#: Failure -Value of: n - Actual: 2 -Expected: 1 +googletest-output-test_.cc:#: n = 1 +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + n + Which is: 2 Google Test trace: -gtest_output_test_.cc:#: n = 2 +googletest-output-test_.cc:#: n = 2 +Stack trace: (omitted) + [0;31m[ FAILED ] [mSCOPED_TRACETest.WorksInSubroutine [0;32m[ RUN ] [mSCOPED_TRACETest.CanBeNested (expected to fail) -gtest_output_test_.cc:#: Failure -Value of: n - Actual: 2 -Expected: 1 +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + n + Which is: 2 Google Test trace: -gtest_output_test_.cc:#: n = 2 -gtest_output_test_.cc:#: +googletest-output-test_.cc:#: n = 2 +googletest-output-test_.cc:#: +Stack trace: (omitted) + [0;31m[ FAILED ] [mSCOPED_TRACETest.CanBeNested [0;32m[ RUN ] [mSCOPED_TRACETest.CanBeRepeated (expected to fail) -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Failed This failure is expected, and should contain trace point A. Google Test trace: -gtest_output_test_.cc:#: A -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: A +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed This failure is expected, and should contain trace point A and B. Google Test trace: -gtest_output_test_.cc:#: B -gtest_output_test_.cc:#: A -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: B +googletest-output-test_.cc:#: A +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed This failure is expected, and should contain trace point A, B, and C. Google Test trace: -gtest_output_test_.cc:#: C -gtest_output_test_.cc:#: B -gtest_output_test_.cc:#: A -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: C +googletest-output-test_.cc:#: B +googletest-output-test_.cc:#: A +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed This failure is expected, and should contain trace point A, B, and D. Google Test trace: -gtest_output_test_.cc:#: D -gtest_output_test_.cc:#: B -gtest_output_test_.cc:#: A +googletest-output-test_.cc:#: D +googletest-output-test_.cc:#: B +googletest-output-test_.cc:#: A +Stack trace: (omitted) + [0;31m[ FAILED ] [mSCOPED_TRACETest.CanBeRepeated [0;32m[ RUN ] [mSCOPED_TRACETest.WorksConcurrently (expecting 6 failures) -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Failed Expected failure #1 (in thread B, only trace B alive). Google Test trace: -gtest_output_test_.cc:#: Trace B -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Trace B +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed Expected failure #2 (in thread A, trace A & B both alive). Google Test trace: -gtest_output_test_.cc:#: Trace A -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Trace A +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed Expected failure #3 (in thread B, trace A & B both alive). Google Test trace: -gtest_output_test_.cc:#: Trace B -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Trace B +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed Expected failure #4 (in thread B, only trace A alive). -gtest_output_test_.cc:#: Failure +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed Expected failure #5 (in thread A, only trace A alive). Google Test trace: -gtest_output_test_.cc:#: Trace A -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Trace A +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed Expected failure #6 (in thread A, no trace alive). +Stack trace: (omitted) + [0;31m[ FAILED ] [mSCOPED_TRACETest.WorksConcurrently +[0;32m[----------] [m1 test from ScopedTraceTest +[0;32m[ RUN ] [mScopedTraceTest.WithExplicitFileAndLine +googletest-output-test_.cc:#: Failure +Failed +Check that the trace is attached to a particular location. +Google Test trace: +explicit_file.cc:123: expected trace message +Stack trace: (omitted) + +[0;31m[ FAILED ] [mScopedTraceTest.WithExplicitFileAndLine [0;32m[----------] [m1 test from NonFatalFailureInFixtureConstructorTest [0;32m[ RUN ] [mNonFatalFailureInFixtureConstructorTest.FailureInConstructor (expecting 5 failures) -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Failed Expected failure #1, in the test fixture c'tor. -gtest_output_test_.cc:#: Failure +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed Expected failure #2, in SetUp(). -gtest_output_test_.cc:#: Failure +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed Expected failure #3, in the test body. -gtest_output_test_.cc:#: Failure +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed Expected failure #4, in TearDown. -gtest_output_test_.cc:#: Failure +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed Expected failure #5, in the test fixture d'tor. +Stack trace: (omitted) + [0;31m[ FAILED ] [mNonFatalFailureInFixtureConstructorTest.FailureInConstructor [0;32m[----------] [m1 test from FatalFailureInFixtureConstructorTest [0;32m[ RUN ] [mFatalFailureInFixtureConstructorTest.FailureInConstructor (expecting 2 failures) -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Failed Expected failure #1, in the test fixture c'tor. -gtest_output_test_.cc:#: Failure +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed Expected failure #2, in the test fixture d'tor. +Stack trace: (omitted) + [0;31m[ FAILED ] [mFatalFailureInFixtureConstructorTest.FailureInConstructor [0;32m[----------] [m1 test from NonFatalFailureInSetUpTest [0;32m[ RUN ] [mNonFatalFailureInSetUpTest.FailureInSetUp (expecting 4 failures) -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Failed Expected failure #1, in SetUp(). -gtest_output_test_.cc:#: Failure +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed Expected failure #2, in the test function. -gtest_output_test_.cc:#: Failure +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed Expected failure #3, in TearDown(). -gtest_output_test_.cc:#: Failure +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed Expected failure #4, in the test fixture d'tor. +Stack trace: (omitted) + [0;31m[ FAILED ] [mNonFatalFailureInSetUpTest.FailureInSetUp [0;32m[----------] [m1 test from FatalFailureInSetUpTest [0;32m[ RUN ] [mFatalFailureInSetUpTest.FailureInSetUp (expecting 3 failures) -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Failed Expected failure #1, in SetUp(). -gtest_output_test_.cc:#: Failure +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed Expected failure #2, in TearDown(). -gtest_output_test_.cc:#: Failure +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed Expected failure #3, in the test fixture d'tor. +Stack trace: (omitted) + [0;31m[ FAILED ] [mFatalFailureInSetUpTest.FailureInSetUp [0;32m[----------] [m1 test from AddFailureAtTest [0;32m[ RUN ] [mAddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber foo.cc:42: Failure Failed Expected failure in foo.cc +Stack trace: (omitted) + [0;31m[ FAILED ] [mAddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber [0;32m[----------] [m4 tests from MixedUpTestCaseTest [0;32m[ RUN ] [mMixedUpTestCaseTest.FirstTestFromNamespaceFoo @@ -280,6 +399,8 @@ using two different test fixture classes. This can happen if the two classes are from different namespaces or translation units and have the same name. You should probably rename one of the classes to put the tests into different test cases. +Stack trace: (omitted) + [0;31m[ FAILED ] [mMixedUpTestCaseTest.ThisShouldFail [0;32m[ RUN ] [mMixedUpTestCaseTest.ThisShouldFailToo gtest.cc:#: Failure @@ -291,6 +412,8 @@ using two different test fixture classes. This can happen if the two classes are from different namespaces or translation units and have the same name. You should probably rename one of the classes to put the tests into different test cases. +Stack trace: (omitted) + [0;31m[ FAILED ] [mMixedUpTestCaseTest.ThisShouldFailToo [0;32m[----------] [m2 tests from MixedUpTestCaseWithSameTestNameTest [0;32m[ RUN ] [mMixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail @@ -305,6 +428,8 @@ using two different test fixture classes. This can happen if the two classes are from different namespaces or translation units and have the same name. You should probably rename one of the classes to put the tests into different test cases. +Stack trace: (omitted) + [0;31m[ FAILED ] [mMixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail [0;32m[----------] [m2 tests from TEST_F_before_TEST_in_same_test_case [0;32m[ RUN ] [mTEST_F_before_TEST_in_same_test_case.DefinedUsingTEST_F @@ -319,6 +444,8 @@ test DefinedUsingTEST_F is defined using TEST_F but test DefinedUsingTESTAndShouldFail is defined using TEST. You probably want to change the TEST to TEST_F or move it to another test case. +Stack trace: (omitted) + [0;31m[ FAILED ] [mTEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail [0;32m[----------] [m2 tests from TEST_before_TEST_F_in_same_test_case [0;32m[ RUN ] [mTEST_before_TEST_F_in_same_test_case.DefinedUsingTEST @@ -333,6 +460,8 @@ test DefinedUsingTEST_FAndShouldFail is defined using TEST_F but test DefinedUsingTEST is defined using TEST. You probably want to change the TEST to TEST_F or move it to another test case. +Stack trace: (omitted) + [0;31m[ FAILED ] [mTEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail [0;32m[----------] [m8 tests from ExpectNonfatalFailureTest [0;32m[ RUN ] [mExpectNonfatalFailureTest.CanReferenceGlobalVariables @@ -346,19 +475,27 @@ case. gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: 0 failures +Stack trace: (omitted) + [0;31m[ FAILED ] [mExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure [0;32m[ RUN ] [mExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures (expecting a failure) gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: 2 failures -gtest_output_test_.cc:#: Non-fatal failure: +googletest-output-test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure 1. +Stack trace: (omitted) + -gtest_output_test_.cc:#: Non-fatal failure: +googletest-output-test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure 2. +Stack trace: (omitted) + + +Stack trace: (omitted) [0;31m[ FAILED ] [mExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures [0;32m[ RUN ] [mExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure @@ -366,9 +503,13 @@ Expected non-fatal failure 2. gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: -gtest_output_test_.cc:#: Fatal failure: +googletest-output-test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [0;31m[ FAILED ] [mExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure [0;32m[ RUN ] [mExpectNonfatalFailureTest.FailsWhenStatementReturns @@ -376,12 +517,16 @@ Expected fatal failure. gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: 0 failures +Stack trace: (omitted) + [0;31m[ FAILED ] [mExpectNonfatalFailureTest.FailsWhenStatementReturns [0;32m[ RUN ] [mExpectNonfatalFailureTest.FailsWhenStatementThrows (expecting a failure) gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: 0 failures +Stack trace: (omitted) + [0;31m[ FAILED ] [mExpectNonfatalFailureTest.FailsWhenStatementThrows [0;32m[----------] [m8 tests from ExpectFatalFailureTest [0;32m[ RUN ] [mExpectFatalFailureTest.CanReferenceGlobalVariables @@ -395,19 +540,27 @@ Expected: 1 non-fatal failure gtest.cc:#: Failure Expected: 1 fatal failure Actual: 0 failures +Stack trace: (omitted) + [0;31m[ FAILED ] [mExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure [0;32m[ RUN ] [mExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures (expecting a failure) gtest.cc:#: Failure Expected: 1 fatal failure Actual: 2 failures -gtest_output_test_.cc:#: Fatal failure: +googletest-output-test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) -gtest_output_test_.cc:#: Fatal failure: + +googletest-output-test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [0;31m[ FAILED ] [mExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures [0;32m[ RUN ] [mExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure @@ -415,9 +568,13 @@ Expected fatal failure. gtest.cc:#: Failure Expected: 1 fatal failure Actual: -gtest_output_test_.cc:#: Non-fatal failure: +googletest-output-test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [0;31m[ FAILED ] [mExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure [0;32m[ RUN ] [mExpectFatalFailureTest.FailsWhenStatementReturns @@ -425,69 +582,140 @@ Expected non-fatal failure. gtest.cc:#: Failure Expected: 1 fatal failure Actual: 0 failures +Stack trace: (omitted) + [0;31m[ FAILED ] [mExpectFatalFailureTest.FailsWhenStatementReturns [0;32m[ RUN ] [mExpectFatalFailureTest.FailsWhenStatementThrows (expecting a failure) gtest.cc:#: Failure Expected: 1 fatal failure Actual: 0 failures +Stack trace: (omitted) + [0;31m[ FAILED ] [mExpectFatalFailureTest.FailsWhenStatementThrows [0;32m[----------] [m2 tests from TypedTest/0, where TypeParam = int [0;32m[ RUN ] [mTypedTest/0.Success [0;32m[ OK ] [mTypedTest/0.Success [0;32m[ RUN ] [mTypedTest/0.Failure -gtest_output_test_.cc:#: Failure -Value of: TypeParam() - Actual: 0 -Expected: 1 +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + TypeParam() + Which is: 0 Expected failure +Stack trace: (omitted) + [0;31m[ FAILED ] [mTypedTest/0.Failure, where TypeParam = int +[0;32m[----------] [m2 tests from TypedTestWithNames/char0, where TypeParam = char +[0;32m[ RUN ] [mTypedTestWithNames/char0.Success +[0;32m[ OK ] [mTypedTestWithNames/char0.Success +[0;32m[ RUN ] [mTypedTestWithNames/char0.Failure +googletest-output-test_.cc:#: Failure +Failed +Stack trace: (omitted) + +[0;31m[ FAILED ] [mTypedTestWithNames/char0.Failure, where TypeParam = char +[0;32m[----------] [m2 tests from TypedTestWithNames/int1, where TypeParam = int +[0;32m[ RUN ] [mTypedTestWithNames/int1.Success +[0;32m[ OK ] [mTypedTestWithNames/int1.Success +[0;32m[ RUN ] [mTypedTestWithNames/int1.Failure +googletest-output-test_.cc:#: Failure +Failed +Stack trace: (omitted) + +[0;31m[ FAILED ] [mTypedTestWithNames/int1.Failure, where TypeParam = int [0;32m[----------] [m2 tests from Unsigned/TypedTestP/0, where TypeParam = unsigned char [0;32m[ RUN ] [mUnsigned/TypedTestP/0.Success [0;32m[ OK ] [mUnsigned/TypedTestP/0.Success [0;32m[ RUN ] [mUnsigned/TypedTestP/0.Failure -gtest_output_test_.cc:#: Failure -Value of: TypeParam() - Actual: '\0' -Expected: 1U -Which is: 1 +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1U + Which is: 1 + TypeParam() + Which is: '\0' Expected failure +Stack trace: (omitted) + [0;31m[ FAILED ] [mUnsigned/TypedTestP/0.Failure, where TypeParam = unsigned char [0;32m[----------] [m2 tests from Unsigned/TypedTestP/1, where TypeParam = unsigned int [0;32m[ RUN ] [mUnsigned/TypedTestP/1.Success [0;32m[ OK ] [mUnsigned/TypedTestP/1.Success [0;32m[ RUN ] [mUnsigned/TypedTestP/1.Failure -gtest_output_test_.cc:#: Failure -Value of: TypeParam() - Actual: 0 -Expected: 1U -Which is: 1 +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1U + Which is: 1 + TypeParam() + Which is: 0 Expected failure +Stack trace: (omitted) + [0;31m[ FAILED ] [mUnsigned/TypedTestP/1.Failure, where TypeParam = unsigned int +[0;32m[----------] [m2 tests from UnsignedCustomName/TypedTestP/unsignedChar0, where TypeParam = unsigned char +[0;32m[ RUN ] [mUnsignedCustomName/TypedTestP/unsignedChar0.Success +[0;32m[ OK ] [mUnsignedCustomName/TypedTestP/unsignedChar0.Success +[0;32m[ RUN ] [mUnsignedCustomName/TypedTestP/unsignedChar0.Failure +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1U + Which is: 1 + TypeParam() + Which is: '\0' +Expected failure +Stack trace: (omitted) + +[0;31m[ FAILED ] [mUnsignedCustomName/TypedTestP/unsignedChar0.Failure, where TypeParam = unsigned char +[0;32m[----------] [m2 tests from UnsignedCustomName/TypedTestP/unsignedInt1, where TypeParam = unsigned int +[0;32m[ RUN ] [mUnsignedCustomName/TypedTestP/unsignedInt1.Success +[0;32m[ OK ] [mUnsignedCustomName/TypedTestP/unsignedInt1.Success +[0;32m[ RUN ] [mUnsignedCustomName/TypedTestP/unsignedInt1.Failure +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1U + Which is: 1 + TypeParam() + Which is: 0 +Expected failure +Stack trace: (omitted) + +[0;31m[ FAILED ] [mUnsignedCustomName/TypedTestP/unsignedInt1.Failure, where TypeParam = unsigned int [0;32m[----------] [m4 tests from ExpectFailureTest [0;32m[ RUN ] [mExpectFailureTest.ExpectFatalFailure (expecting 1 failure) gtest.cc:#: Failure Expected: 1 fatal failure Actual: -gtest_output_test_.cc:#: Success: +googletest-output-test_.cc:#: Success: Succeeded +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure Expected: 1 fatal failure Actual: -gtest_output_test_.cc:#: Non-fatal failure: +googletest-output-test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure Expected: 1 fatal failure containing "Some other fatal failure expected." Actual: -gtest_output_test_.cc:#: Fatal failure: +googletest-output-test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [0;31m[ FAILED ] [mExpectFailureTest.ExpectFatalFailure [0;32m[ RUN ] [mExpectFailureTest.ExpectNonFatalFailure @@ -495,24 +723,36 @@ Expected fatal failure. gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: -gtest_output_test_.cc:#: Success: +googletest-output-test_.cc:#: Success: Succeeded +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: -gtest_output_test_.cc:#: Fatal failure: +googletest-output-test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure Expected: 1 non-fatal failure containing "Some other non-fatal failure." Actual: -gtest_output_test_.cc:#: Non-fatal failure: +googletest-output-test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [0;31m[ FAILED ] [mExpectFailureTest.ExpectNonFatalFailure [0;32m[ RUN ] [mExpectFailureTest.ExpectFatalFailureOnAllThreads @@ -520,24 +760,36 @@ Expected non-fatal failure. gtest.cc:#: Failure Expected: 1 fatal failure Actual: -gtest_output_test_.cc:#: Success: +googletest-output-test_.cc:#: Success: Succeeded +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure Expected: 1 fatal failure Actual: -gtest_output_test_.cc:#: Non-fatal failure: +googletest-output-test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure Expected: 1 fatal failure containing "Some other fatal failure expected." Actual: -gtest_output_test_.cc:#: Fatal failure: +googletest-output-test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [0;31m[ FAILED ] [mExpectFailureTest.ExpectFatalFailureOnAllThreads [0;32m[ RUN ] [mExpectFailureTest.ExpectNonFatalFailureOnAllThreads @@ -545,86 +797,132 @@ Expected fatal failure. gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: -gtest_output_test_.cc:#: Success: +googletest-output-test_.cc:#: Success: Succeeded +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: -gtest_output_test_.cc:#: Fatal failure: +googletest-output-test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure Expected: 1 non-fatal failure containing "Some other non-fatal failure." Actual: -gtest_output_test_.cc:#: Non-fatal failure: +googletest-output-test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [0;31m[ FAILED ] [mExpectFailureTest.ExpectNonFatalFailureOnAllThreads [0;32m[----------] [m2 tests from ExpectFailureWithThreadsTest [0;32m[ RUN ] [mExpectFailureWithThreadsTest.ExpectFatalFailure (expecting 2 failures) -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Failed Expected fatal failure. +Stack trace: (omitted) + gtest.cc:#: Failure Expected: 1 fatal failure Actual: 0 failures +Stack trace: (omitted) + [0;31m[ FAILED ] [mExpectFailureWithThreadsTest.ExpectFatalFailure [0;32m[ RUN ] [mExpectFailureWithThreadsTest.ExpectNonFatalFailure (expecting 2 failures) -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Failed Expected non-fatal failure. +Stack trace: (omitted) + gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: 0 failures +Stack trace: (omitted) + [0;31m[ FAILED ] [mExpectFailureWithThreadsTest.ExpectNonFatalFailure [0;32m[----------] [m1 test from ScopedFakeTestPartResultReporterTest [0;32m[ RUN ] [mScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread (expecting 2 failures) -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Failed Expected fatal failure. -gtest_output_test_.cc:#: Failure +Stack trace: (omitted) + +googletest-output-test_.cc:#: Failure Failed Expected non-fatal failure. +Stack trace: (omitted) + [0;31m[ FAILED ] [mScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread [0;32m[----------] [m1 test from PrintingFailingParams/FailingParamTest [0;32m[ RUN ] [mPrintingFailingParams/FailingParamTest.Fails/0 -gtest_output_test_.cc:#: Failure -Value of: GetParam() - Actual: 2 -Expected: 1 +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + GetParam() + Which is: 2 +Stack trace: (omitted) + [0;31m[ FAILED ] [mPrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 +[0;32m[----------] [m2 tests from PrintingStrings/ParamTest +[0;32m[ RUN ] [mPrintingStrings/ParamTest.Success/a +[0;32m[ OK ] [mPrintingStrings/ParamTest.Success/a +[0;32m[ RUN ] [mPrintingStrings/ParamTest.Failure/a +googletest-output-test_.cc:#: Failure +Expected equality of these values: + "b" + GetParam() + Which is: "a" +Expected failure +Stack trace: (omitted) + +[0;31m[ FAILED ] [mPrintingStrings/ParamTest.Failure/a, where GetParam() = "a" [0;32m[----------] [mGlobal test environment tear-down BarEnvironment::TearDown() called. -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Failed Expected non-fatal failure. +Stack trace: (omitted) + FooEnvironment::TearDown() called. -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Failed Expected fatal failure. -[0;32m[==========] [m64 tests from 28 test cases ran. -[0;32m[ PASSED ] [m21 tests. -[0;31m[ FAILED ] [m43 tests, listed below: +Stack trace: (omitted) + +[0;32m[==========] [m76 tests from 34 test cases ran. +[0;32m[ PASSED ] [m26 tests. +[0;31m[ FAILED ] [m50 tests, listed below: [0;31m[ FAILED ] [mNonfatalFailureTest.EscapesStringOperands [0;31m[ FAILED ] [mNonfatalFailureTest.DiffForLongStrings [0;31m[ FAILED ] [mFatalFailureTest.FatalFailureInSubroutine [0;31m[ FAILED ] [mFatalFailureTest.FatalFailureInNestedSubroutine [0;31m[ FAILED ] [mFatalFailureTest.NonfatalFailureInSubroutine [0;31m[ FAILED ] [mLoggingTest.InterleavingLoggingAndAssertions +[0;31m[ FAILED ] [mSCOPED_TRACETest.AcceptedValues [0;31m[ FAILED ] [mSCOPED_TRACETest.ObeysScopes [0;31m[ FAILED ] [mSCOPED_TRACETest.WorksInLoop [0;31m[ FAILED ] [mSCOPED_TRACETest.WorksInSubroutine [0;31m[ FAILED ] [mSCOPED_TRACETest.CanBeNested [0;31m[ FAILED ] [mSCOPED_TRACETest.CanBeRepeated [0;31m[ FAILED ] [mSCOPED_TRACETest.WorksConcurrently +[0;31m[ FAILED ] [mScopedTraceTest.WithExplicitFileAndLine [0;31m[ FAILED ] [mNonFatalFailureInFixtureConstructorTest.FailureInConstructor [0;31m[ FAILED ] [mFatalFailureInFixtureConstructorTest.FailureInConstructor [0;31m[ FAILED ] [mNonFatalFailureInSetUpTest.FailureInSetUp @@ -646,8 +944,12 @@ Expected fatal failure. [0;31m[ FAILED ] [mExpectFatalFailureTest.FailsWhenStatementReturns [0;31m[ FAILED ] [mExpectFatalFailureTest.FailsWhenStatementThrows [0;31m[ FAILED ] [mTypedTest/0.Failure, where TypeParam = int +[0;31m[ FAILED ] [mTypedTestWithNames/char0.Failure, where TypeParam = char +[0;31m[ FAILED ] [mTypedTestWithNames/int1.Failure, where TypeParam = int [0;31m[ FAILED ] [mUnsigned/TypedTestP/0.Failure, where TypeParam = unsigned char [0;31m[ FAILED ] [mUnsigned/TypedTestP/1.Failure, where TypeParam = unsigned int +[0;31m[ FAILED ] [mUnsignedCustomName/TypedTestP/unsignedChar0.Failure, where TypeParam = unsigned char +[0;31m[ FAILED ] [mUnsignedCustomName/TypedTestP/unsignedInt1.Failure, where TypeParam = unsigned int [0;31m[ FAILED ] [mExpectFailureTest.ExpectFatalFailure [0;31m[ FAILED ] [mExpectFailureTest.ExpectNonFatalFailure [0;31m[ FAILED ] [mExpectFailureTest.ExpectFatalFailureOnAllThreads @@ -656,8 +958,9 @@ Expected fatal failure. [0;31m[ FAILED ] [mExpectFailureWithThreadsTest.ExpectNonFatalFailure [0;31m[ FAILED ] [mScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread [0;31m[ FAILED ] [mPrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 +[0;31m[ FAILED ] [mPrintingStrings/ParamTest.Failure/a, where GetParam() = "a" -43 FAILED TESTS +50 FAILED TESTS [0;33m YOU HAVE 1 DISABLED TEST [mNote: Google Test filter = FatalFailureTest.*:LoggingTest.* @@ -666,24 +969,32 @@ Expected fatal failure. [----------] 3 tests from FatalFailureTest [ RUN ] FatalFailureTest.FatalFailureInSubroutine (expecting a failure that x should be 1) -gtest_output_test_.cc:#: Failure -Value of: x - Actual: 2 -Expected: 1 +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + x + Which is: 2 +Stack trace: (omitted) + [ FAILED ] FatalFailureTest.FatalFailureInSubroutine (? ms) [ RUN ] FatalFailureTest.FatalFailureInNestedSubroutine (expecting a failure that x should be 1) -gtest_output_test_.cc:#: Failure -Value of: x - Actual: 2 -Expected: 1 +googletest-output-test_.cc:#: Failure +Expected equality of these values: + 1 + x + Which is: 2 +Stack trace: (omitted) + [ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine (? ms) [ RUN ] FatalFailureTest.NonfatalFailureInSubroutine (expecting a failure on false) -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Value of: false Actual: false Expected: true +Stack trace: (omitted) + [ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine (? ms) [----------] 3 tests from FatalFailureTest (? ms total) @@ -692,12 +1003,16 @@ Expected: true (expecting 2 failures on (3) >= (a[i])) i == 0 i == 1 -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Expected: (3) >= (a[i]), actual: 3 vs 9 +Stack trace: (omitted) + i == 2 i == 3 -gtest_output_test_.cc:#: Failure +googletest-output-test_.cc:#: Failure Expected: (3) >= (a[i]), actual: 3 vs 6 +Stack trace: (omitted) + [ FAILED ] LoggingTest.InterleavingLoggingAndAssertions (? ms) [----------] 1 test from LoggingTest (? ms total) diff --git a/security/nss/gtests/google_test/gtest/test/gtest_output_test.py b/security/nss/gtests/google_test/gtest/test/googletest-output-test.py index fa1a31172..2d69e353a 100755..100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_output_test.py +++ b/security/nss/gtests/google_test/gtest/test/googletest-output-test.py @@ -29,17 +29,16 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -"""Tests the text output of Google C++ Testing Framework. +"""Tests the text output of Google C++ Testing and Mocking Framework. -SYNOPSIS - gtest_output_test.py --build_dir=BUILD/DIR --gengolden - # where BUILD/DIR contains the built gtest_output_test_ file. - gtest_output_test.py --gengolden - gtest_output_test.py +To update the golden file: +googletest_output_test.py --build_dir=BUILD/DIR --gengolden +where BUILD/DIR contains the built googletest-output-test_ file. +googletest_output_test.py --gengolden +googletest_output_test.py """ -__author__ = 'wan@google.com (Zhanyong Wan)' - +import difflib import os import re import sys @@ -50,30 +49,34 @@ import gtest_test_utils GENGOLDEN_FLAG = '--gengolden' CATCH_EXCEPTIONS_ENV_VAR_NAME = 'GTEST_CATCH_EXCEPTIONS' +# The flag indicating stacktraces are not supported +NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support' + +IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' IS_WINDOWS = os.name == 'nt' -# TODO(vladl@google.com): remove the _lin suffix. -GOLDEN_NAME = 'gtest_output_test_golden_lin.txt' +# FIXME: remove the _lin suffix. +GOLDEN_NAME = 'googletest-output-test-golden-lin.txt' -PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_output_test_') +PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('googletest-output-test_') # At least one command we exercise must not have the -# --gtest_internal_skip_environment_and_ad_hoc_tests flag. +# 'internal_skip_environment_and_ad_hoc_tests' argument. COMMAND_LIST_TESTS = ({}, [PROGRAM_PATH, '--gtest_list_tests']) COMMAND_WITH_COLOR = ({}, [PROGRAM_PATH, '--gtest_color=yes']) COMMAND_WITH_TIME = ({}, [PROGRAM_PATH, '--gtest_print_time', - '--gtest_internal_skip_environment_and_ad_hoc_tests', + 'internal_skip_environment_and_ad_hoc_tests', '--gtest_filter=FatalFailureTest.*:LoggingTest.*']) COMMAND_WITH_DISABLED = ( {}, [PROGRAM_PATH, '--gtest_also_run_disabled_tests', - '--gtest_internal_skip_environment_and_ad_hoc_tests', + 'internal_skip_environment_and_ad_hoc_tests', '--gtest_filter=*DISABLED_*']) COMMAND_WITH_SHARDING = ( {'GTEST_SHARD_INDEX': '1', 'GTEST_TOTAL_SHARDS': '2'}, [PROGRAM_PATH, - '--gtest_internal_skip_environment_and_ad_hoc_tests', + 'internal_skip_environment_and_ad_hoc_tests', '--gtest_filter=PassingTest.*']) GOLDEN_PATH = os.path.join(gtest_test_utils.GetSourceDir(), GOLDEN_NAME) @@ -98,7 +101,8 @@ def RemoveLocations(test_output): 'FILE_NAME:#: '. """ - return re.sub(r'.*[/\\](.+)(\:\d+|\(\d+\))\: ', r'\1:#: ', test_output) + return re.sub(r'.*[/\\]((googletest-output-test_|gtest).cc)(\:\d+|\(\d+\))\: ', + r'\1:#: ', test_output) def RemoveStackTraceDetails(output): @@ -188,7 +192,7 @@ def RemoveMatchingTests(test_output, pattern): def NormalizeOutput(output): - """Normalizes output (the output of gtest_output_test_.exe).""" + """Normalizes output (the output of googletest-output-test_.exe).""" output = ToUnixLineEnding(output) output = RemoveLocations(output) @@ -248,12 +252,12 @@ test_list = GetShellCommandOutput(COMMAND_LIST_TESTS) SUPPORTS_DEATH_TESTS = 'DeathTest' in test_list SUPPORTS_TYPED_TESTS = 'TypedTest' in test_list SUPPORTS_THREADS = 'ExpectFailureWithThreadsTest' in test_list -SUPPORTS_STACK_TRACES = False +SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv CAN_GENERATE_GOLDEN_FILE = (SUPPORTS_DEATH_TESTS and SUPPORTS_TYPED_TESTS and SUPPORTS_THREADS and - not IS_WINDOWS) + SUPPORTS_STACK_TRACES) class GTestOutputTest(gtest_test_utils.TestCase): def RemoveUnsupportedTests(self, test_output): @@ -294,7 +298,11 @@ class GTestOutputTest(gtest_test_utils.TestCase): normalized_golden = RemoveTypeInfoDetails(golden) if CAN_GENERATE_GOLDEN_FILE: - self.assertEqual(normalized_golden, normalized_actual) + self.assertEqual(normalized_golden, normalized_actual, + '\n'.join(difflib.unified_diff( + normalized_golden.split('\n'), + normalized_actual.split('\n'), + 'golden', 'actual'))) else: normalized_actual = NormalizeToCurrentPlatform( RemoveTestCounts(normalized_actual)) @@ -305,18 +313,22 @@ class GTestOutputTest(gtest_test_utils.TestCase): if os.getenv('DEBUG_GTEST_OUTPUT_TEST'): open(os.path.join( gtest_test_utils.GetSourceDir(), - '_gtest_output_test_normalized_actual.txt'), 'wb').write( + '_googletest-output-test_normalized_actual.txt'), 'wb').write( normalized_actual) open(os.path.join( gtest_test_utils.GetSourceDir(), - '_gtest_output_test_normalized_golden.txt'), 'wb').write( + '_googletest-output-test_normalized_golden.txt'), 'wb').write( normalized_golden) self.assertEqual(normalized_golden, normalized_actual) if __name__ == '__main__': - if sys.argv[1:] == [GENGOLDEN_FLAG]: + if NO_STACKTRACE_SUPPORT_FLAG in sys.argv: + # unittest.main() can't handle unknown flags + sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG) + + if GENGOLDEN_FLAG in sys.argv: if CAN_GENERATE_GOLDEN_FILE: output = GetOutputOfAllCommands() golden_file = open(GOLDEN_PATH, 'wb') @@ -325,9 +337,9 @@ if __name__ == '__main__': else: message = ( """Unable to write a golden file when compiled in an environment -that does not support all the required features (death tests, typed tests, -and multiple threads). Please generate the golden file using a binary built -with those features enabled.""") +that does not support all the required features (death tests, +typed tests, stack traces, and multiple threads). +Please build this test and generate the golden file using Blaze on Linux.""") sys.stderr.write(message) sys.exit(1) diff --git a/security/nss/gtests/google_test/gtest/test/gtest_output_test_.cc b/security/nss/gtests/google_test/gtest/test/googletest-output-test_.cc index 5361d8d87..f6525ec97 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_output_test_.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-output-test_.cc @@ -29,26 +29,20 @@ // // The purpose of this file is to generate Google Test output under // various conditions. The output will then be verified by -// gtest_output_test.py to ensure that Google Test generates the +// googletest-output-test.py to ensure that Google Test generates the // desired messages. Therefore, most tests in this file are MEANT TO // FAIL. -// -// Author: wan@google.com (Zhanyong Wan) #include "gtest/gtest-spi.h" #include "gtest/gtest.h" - -// Indicates that this translation unit is part of Google Test's -// implementation. It must come before gtest-internal-inl.h is -// included, or there will be a compiler error. This trick is to -// prevent a user from accidentally including gtest-internal-inl.h in -// his code. -#define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" -#undef GTEST_IMPLEMENTATION_ #include <stdlib.h> +#if _MSC_VER +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */) +#endif // _MSC_VER + #if GTEST_IS_THREADSAFE using testing::ScopedFakeTestPartResultReporter; using testing::TestPartResultArray; @@ -58,7 +52,6 @@ using testing::internal::ThreadWithParam; #endif namespace posix = ::testing::internal::posix; -using testing::internal::scoped_ptr; // Tests catching fatal failures. @@ -177,6 +170,16 @@ void SubWithTrace(int n) { SubWithoutTrace(n); } +TEST(SCOPED_TRACETest, AcceptedValues) { + SCOPED_TRACE("literal string"); + SCOPED_TRACE(std::string("std::string")); + SCOPED_TRACE(1337); // streamable type + const char* null_value = NULL; + SCOPED_TRACE(null_value); + + ADD_FAILURE() << "Just checking that all these values work fine."; +} + // Tests that SCOPED_TRACE() obeys lexical scopes. TEST(SCOPED_TRACETest, ObeysScopes) { printf("(expected to fail)\n"); @@ -324,6 +327,13 @@ TEST(SCOPED_TRACETest, WorksConcurrently) { } #endif // GTEST_IS_THREADSAFE +// Tests basic functionality of the ScopedTrace utility (most of its features +// are already tested in SCOPED_TRACETest). +TEST(ScopedTraceTest, WithExplicitFileAndLine) { + testing::ScopedTrace trace("explicit_file.cc", 123, "expected trace message"); + ADD_FAILURE() << "Check that the trace is attached to a particular location."; +} + TEST(DisabledTestsWarningTest, DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning) { // This test body is intentionally empty. Its sole purpose is for @@ -515,7 +525,8 @@ class DeathTestAndMultiThreadsTest : public testing::Test { private: SpawnThreadNotifications notifications_; - scoped_ptr<ThreadWithParam<SpawnThreadNotifications*> > thread_; + testing::internal::scoped_ptr<ThreadWithParam<SpawnThreadNotifications*> > + thread_; }; #endif // GTEST_IS_THREADSAFE @@ -755,6 +766,28 @@ TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) { #endif // GTEST_HAS_EXCEPTIONS +// This #ifdef block tests the output of value-parameterized tests. + +std::string ParamNameFunc(const testing::TestParamInfo<std::string>& info) { + return info.param; +} + +class ParamTest : public testing::TestWithParam<std::string> { +}; + +TEST_P(ParamTest, Success) { + EXPECT_EQ("a", GetParam()); +} + +TEST_P(ParamTest, Failure) { + EXPECT_EQ("b", GetParam()) << "Expected failure"; +} + +INSTANTIATE_TEST_CASE_P(PrintingStrings, + ParamTest, + testing::Values(std::string("a")), + ParamNameFunc); + // This #ifdef block tests the output of typed tests. #if GTEST_HAS_TYPED_TEST @@ -772,6 +805,28 @@ TYPED_TEST(TypedTest, Failure) { EXPECT_EQ(1, TypeParam()) << "Expected failure"; } +typedef testing::Types<char, int> TypesForTestWithNames; + +template <typename T> +class TypedTestWithNames : public testing::Test {}; + +class TypedTestNames { + public: + template <typename T> + static std::string GetName(int i) { + if (testing::internal::IsSame<T, char>::value) + return std::string("char") + ::testing::PrintToString(i); + if (testing::internal::IsSame<T, int>::value) + return std::string("int") + ::testing::PrintToString(i); + } +}; + +TYPED_TEST_CASE(TypedTestWithNames, TypesForTestWithNames, TypedTestNames); + +TYPED_TEST(TypedTestWithNames, Success) {} + +TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); } + #endif // GTEST_HAS_TYPED_TEST // This #ifdef block tests the output of type-parameterized tests. @@ -796,6 +851,22 @@ REGISTER_TYPED_TEST_CASE_P(TypedTestP, Success, Failure); typedef testing::Types<unsigned char, unsigned int> UnsignedTypes; INSTANTIATE_TYPED_TEST_CASE_P(Unsigned, TypedTestP, UnsignedTypes); +class TypedTestPNames { + public: + template <typename T> + static std::string GetName(int i) { + if (testing::internal::IsSame<T, unsigned char>::value) { + return std::string("unsignedChar") + ::testing::PrintToString(i); + } + if (testing::internal::IsSame<T, unsigned int>::value) { + return std::string("unsignedInt") + ::testing::PrintToString(i); + } + } +}; + +INSTANTIATE_TYPED_TEST_CASE_P(UnsignedCustomName, TypedTestP, UnsignedTypes, + TypedTestPNames); + #endif // GTEST_HAS_TYPED_TEST_P #if GTEST_HAS_DEATH_TEST @@ -990,8 +1061,6 @@ class BarEnvironment : public testing::Environment { } }; -bool GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests) = false; - // The main function. // // The idea is to use Google Test to run all the tests we have defined (some @@ -1008,10 +1077,9 @@ int main(int argc, char **argv) { // global side effects. The following line serves as a sanity test // for it. testing::InitGoogleTest(&argc, argv); - if (argc >= 2 && - (std::string(argv[1]) == - "--gtest_internal_skip_environment_and_ad_hoc_tests")) - GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests) = true; + bool internal_skip_environment_and_ad_hoc_tests = + std::count(argv, argv + argc, + std::string("internal_skip_environment_and_ad_hoc_tests")) > 0; #if GTEST_HAS_DEATH_TEST if (testing::internal::GTEST_FLAG(internal_run_death_test) != "") { @@ -1026,7 +1094,7 @@ int main(int argc, char **argv) { } #endif // GTEST_HAS_DEATH_TEST - if (GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests)) + if (internal_skip_environment_and_ad_hoc_tests) return RUN_ALL_TESTS(); // Registers two global test environments. @@ -1034,6 +1102,8 @@ int main(int argc, char **argv) { // are registered, and torn down in the reverse order. testing::AddGlobalTestEnvironment(new FooEnvironment); testing::AddGlobalTestEnvironment(new BarEnvironment); - +#if _MSC_VER +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127 +#endif // _MSC_VER return RunAllTests(); } diff --git a/security/nss/gtests/google_test/gtest/test/googletest-param-test-invalid-name1-test.py b/security/nss/gtests/google_test/gtest/test/googletest-param-test-invalid-name1-test.py new file mode 100644 index 000000000..2a08477a7 --- /dev/null +++ b/security/nss/gtests/google_test/gtest/test/googletest-param-test-invalid-name1-test.py @@ -0,0 +1,63 @@ +#!/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.""" + +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/security/nss/gtests/google_test/gtest/test/googletest-param-test-invalid-name1-test_.cc b/security/nss/gtests/google_test/gtest/test/googletest-param-test-invalid-name1-test_.cc new file mode 100644 index 000000000..5a95155b2 --- /dev/null +++ b/security/nss/gtests/google_test/gtest/test/googletest-param-test-invalid-name1-test_.cc @@ -0,0 +1,50 @@ +// 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. + + +#include "gtest/gtest.h" + +namespace { +class DummyTest : public ::testing::TestWithParam<const char *> {}; + +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/security/nss/gtests/google_test/gtest/test/googletest-param-test-invalid-name2-test.py b/security/nss/gtests/google_test/gtest/test/googletest-param-test-invalid-name2-test.py new file mode 100644 index 000000000..ab838f463 --- /dev/null +++ b/security/nss/gtests/google_test/gtest/test/googletest-param-test-invalid-name2-test.py @@ -0,0 +1,62 @@ +#!/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.""" + +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/security/nss/gtests/google_test/gtest/test/googletest-param-test-invalid-name2-test_.cc b/security/nss/gtests/google_test/gtest/test/googletest-param-test-invalid-name2-test_.cc new file mode 100644 index 000000000..ef093490e --- /dev/null +++ b/security/nss/gtests/google_test/gtest/test/googletest-param-test-invalid-name2-test_.cc @@ -0,0 +1,55 @@ +// 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. + + +#include "gtest/gtest.h" + +namespace { +class DummyTest : public ::testing::TestWithParam<const char *> {}; + +std::string StringParamTestSuffix( + const testing::TestParamInfo<const char*>& 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/security/nss/gtests/google_test/gtest/test/gtest-param-test_test.cc b/security/nss/gtests/google_test/gtest/test/googletest-param-test-test.cc index cc1dc65fb..f789cab27 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-param-test_test.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-param-test-test.cc @@ -26,8 +26,7 @@ // 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 @@ -35,8 +34,6 @@ #include "gtest/gtest.h" -#if GTEST_HAS_PARAM_TEST - # include <algorithm> # include <iostream> # include <list> @@ -44,12 +41,8 @@ # include <string> # include <vector> -// To include gtest-internal-inl.h. -# define GTEST_IMPLEMENTATION_ 1 # include "src/gtest-internal-inl.h" // for UnitTestOptions -# undef GTEST_IMPLEMENTATION_ - -# include "test/gtest-param-test_test.h" +# include "test/googletest-param-test-test.h" using ::std::vector; using ::std::sort; @@ -74,7 +67,7 @@ using ::testing::internal::UnitTestOptions; // Prints a value to a string. // -// TODO(wan@google.com): remove PrintValue() when we move matchers and +// FIXME: 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. @@ -141,7 +134,7 @@ void VerifyGenerator(const ParamGenerator<T>& generator, << ", expected_values[i] is " << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it) << ", and 'it' is an iterator created with the copy constructor.\n"; - it++; + ++it; } EXPECT_TRUE(it == generator.end()) << "At the presumed end of sequence when accessing via an iterator " @@ -161,7 +154,7 @@ void VerifyGenerator(const ParamGenerator<T>& generator, << ", expected_values[i] is " << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it) << ", and 'it' is an iterator created with the copy constructor.\n"; - it++; + ++it; } EXPECT_TRUE(it == generator.end()) << "At the presumed end of sequence when accessing via an iterator " @@ -196,7 +189,7 @@ TEST(IteratorTest, ParamIteratorConformsToForwardIteratorConcept) { << "element same as its source points to"; // Verifies that iterator assignment works as expected. - it++; + ++it; EXPECT_FALSE(*it == *it2); it2 = it; EXPECT_TRUE(*it == *it2) << "Assigned iterators must point to the " @@ -215,7 +208,7 @@ TEST(IteratorTest, ParamIteratorConformsToForwardIteratorConcept) { // Verifies that prefix and postfix operator++() advance an iterator // all the same. it2 = it; - it++; + ++it; ++it2; EXPECT_TRUE(*it == *it2); } @@ -542,6 +535,51 @@ TEST(CombineTest, CombineWithMaxNumberOfParameters) { 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<tuple<int, NonDefaultConstructAssignString> > gen = + Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"), + NonDefaultConstructAssignString("B"))); + + ParamGenerator<tuple<int, NonDefaultConstructAssignString> >::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 @@ -809,6 +847,184 @@ TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) { INSTANTIATE_TEST_CASE_P(ZeroToFiveSequence, NamingTest, Range(0, 5)); +// Tests that macros in test names are expanded correctly. +class MacroNamingTest : public TestWithParam<int> {}; + +#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<std::string> {}; +TEST_P(CustomFunctorNamingTest, CustomTestNames) {} + +struct CustomParamNameFunctor { + std::string operator()(const ::testing::TestParamInfo<std::string>& 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<std::string>& inf) { + return inf.param; +} + +class CustomFunctionNamingTest : public TestWithParam<std::string> {}; +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<std::string> {}; +TEST_P(CustomLambdaNamingTest, CustomTestNames) {} + +INSTANTIATE_TEST_CASE_P(CustomParamNameLambda, CustomLambdaNamingTest, + Values(std::string("LambdaName")), + [](const ::testing::TestParamInfo<std::string>& inf) { + return inf.param; + }); + +#endif // GTEST_LANG_CXX11 + +TEST(CustomNamingTest, CheckNameRegistry) { + ::testing::UnitTest* unit_test = ::testing::UnitTest::GetInstance(); + std::set<std::string> 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<int> {}; + +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<CustomStruct> {}; + +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<int>& info) { + int value = info.param + sum; + sum += info.param; + return ::testing::PrintToString(value); + } + int sum; +}; + +class StatefulNamingTest : public ::testing::TestWithParam<int> { + 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 @@ -874,31 +1090,20 @@ TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) { INSTANTIATE_TEST_CASE_P(RangeZeroToFive, ParameterizedDerivedTest, Range(0, 5)); -#endif // GTEST_HAS_PARAM_TEST - -TEST(CompileTest, CombineIsDefinedOnlyWhenGtestHasParamTestIsDefined) { -#if GTEST_HAS_COMBINE && !GTEST_HAS_PARAM_TEST - FAIL() << "GTEST_HAS_COMBINE is defined while GTEST_HAS_PARAM_TEST is not\n" -#endif -} int main(int argc, char **argv) { -#if GTEST_HAS_PARAM_TEST // 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); -#endif // GTEST_HAS_PARAM_TEST ::testing::InitGoogleTest(&argc, argv); -#if GTEST_HAS_PARAM_TEST // Used in GeneratorEvaluationTest test case. Tests that value updated // here will NOT be used for instantiating tests in // GeneratorEvaluationTest. GeneratorEvaluationTest::set_param_value(2); -#endif // GTEST_HAS_PARAM_TEST return RUN_ALL_TESTS(); } diff --git a/security/nss/gtests/google_test/gtest/test/gtest-param-test_test.h b/security/nss/gtests/google_test/gtest/test/googletest-param-test-test.h index 26ea122b1..632a61f49 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-param-test_test.h +++ b/security/nss/gtests/google_test/gtest/test/googletest-param-test-test.h @@ -27,9 +27,7 @@ // (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 Framework (Google Test) +// The Google C++ Testing and Mocking Framework (Google Test) // // This header file provides classes and functions used internally // for testing Google Test itself. @@ -39,8 +37,6 @@ #include "gtest/gtest.h" -#if GTEST_HAS_PARAM_TEST - // Test fixture for testing definition and instantiation of a test // in separate translation units. class ExternalInstantiationTest : public ::testing::TestWithParam<int> { @@ -52,6 +48,4 @@ class InstantiationInMultipleTranslaionUnitsTest : public ::testing::TestWithParam<int> { }; -#endif // GTEST_HAS_PARAM_TEST - #endif // GTEST_TEST_GTEST_PARAM_TEST_TEST_H_ diff --git a/security/nss/gtests/google_test/gtest/test/gtest-param-test2_test.cc b/security/nss/gtests/google_test/gtest/test/googletest-param-test2-test.cc index 4a782fe70..25bb945c2 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-param-test2_test.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-param-test2-test.cc @@ -26,40 +26,36 @@ // 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 "test/gtest-param-test_test.h" - -#if GTEST_HAS_PARAM_TEST +#include "test/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. +// in googletest-param-test-test.cc. ParamGenerator<int> 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. +// and instantiated in another. The test is defined in +// googletest-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 +// in googletest-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)); -#endif // GTEST_HAS_PARAM_TEST diff --git a/security/nss/gtests/google_test/gtest/test/gtest-port_test.cc b/security/nss/gtests/google_test/gtest/test/googletest-port-test.cc index 370c952b2..399316f95 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-port_test.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-port-test.cc @@ -27,14 +27,11 @@ // (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), wan@google.com (Zhanyong Wan) -// // This file tests the internal cross-platform support utilities. +#include <stdio.h> #include "gtest/internal/gtest-port.h" -#include <stdio.h> - #if GTEST_OS_MAC # include <time.h> #endif // GTEST_OS_MAC @@ -45,15 +42,7 @@ #include "gtest/gtest.h" #include "gtest/gtest-spi.h" - -// Indicates that this translation unit is part of Google Test's -// implementation. It must come before gtest-internal-inl.h is -// included, or there will be a compiler error. This trick is to -// prevent a user from accidentally including gtest-internal-inl.h in -// his code. -#define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" -#undef GTEST_IMPLEMENTATION_ using std::make_pair; using std::pair; @@ -75,8 +64,8 @@ TEST(IsXDigitTest, WorksForNarrowAscii) { } TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) { - EXPECT_FALSE(IsXDigit(static_cast<char>(0x80))); - EXPECT_FALSE(IsXDigit(static_cast<char>('0' | 0x80))); + EXPECT_FALSE(IsXDigit(static_cast<char>('\x80'))); + EXPECT_FALSE(IsXDigit(static_cast<char>('0' | '\x80'))); } TEST(IsXDigitTest, WorksForWideAscii) { @@ -235,7 +224,7 @@ TEST(ScopedPtrTest, DefinesElementType) { StaticAssertTypeEq<int, ::testing::internal::scoped_ptr<int>::element_type>(); } -// TODO(vladl@google.com): Implement THE REST of scoped_ptr tests. +// FIXME: Implement THE REST of scoped_ptr tests. TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) { if (AlwaysFalse()) @@ -304,68 +293,61 @@ TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) { EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(NULL, -1)); } -#if GTEST_OS_MAC || GTEST_OS_QNX +#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA void* ThreadFunc(void* data) { - pthread_mutex_t* mutex = static_cast<pthread_mutex_t*>(data); - pthread_mutex_lock(mutex); - pthread_mutex_unlock(mutex); + internal::Mutex* mutex = static_cast<internal::Mutex*>(data); + mutex->Lock(); + mutex->Unlock(); return NULL; } TEST(GetThreadCountTest, ReturnsCorrectValue) { - EXPECT_EQ(1U, GetThreadCount()); - pthread_mutex_t mutex; - pthread_attr_t attr; + const size_t starting_count = GetThreadCount(); pthread_t thread_id; - // TODO(vladl@google.com): turn mutex into internal::Mutex for automatic - // destruction. - pthread_mutex_init(&mutex, NULL); - pthread_mutex_lock(&mutex); - ASSERT_EQ(0, pthread_attr_init(&attr)); - ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)); - - const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex); - ASSERT_EQ(0, pthread_attr_destroy(&attr)); - ASSERT_EQ(0, status); - EXPECT_EQ(2U, GetThreadCount()); - pthread_mutex_unlock(&mutex); + internal::Mutex mutex; + { + internal::MutexLock lock(&mutex); + pthread_attr_t attr; + ASSERT_EQ(0, pthread_attr_init(&attr)); + ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)); + + const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex); + ASSERT_EQ(0, pthread_attr_destroy(&attr)); + ASSERT_EQ(0, status); + EXPECT_EQ(starting_count + 1, GetThreadCount()); + } void* dummy; ASSERT_EQ(0, pthread_join(thread_id, &dummy)); -# if GTEST_OS_MAC - - // MacOS X may not immediately report the updated thread count after + // The OS may not immediately report the updated thread count after // joining a thread, causing flakiness in this test. To counter that, we // wait for up to .5 seconds for the OS to report the correct value. for (int i = 0; i < 5; ++i) { - if (GetThreadCount() == 1) + if (GetThreadCount() == starting_count) break; SleepMilliseconds(100); } -# endif // GTEST_OS_MAC - - EXPECT_EQ(1U, GetThreadCount()); - pthread_mutex_destroy(&mutex); + EXPECT_EQ(starting_count, GetThreadCount()); } #else TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) { EXPECT_EQ(0U, GetThreadCount()); } -#endif // GTEST_OS_MAC || GTEST_OS_QNX +#endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) { const bool a_false_condition = false; const char regex[] = #ifdef _MSC_VER - "gtest-port_test\\.cc\\(\\d+\\):" + "googletest-port-test\\.cc\\(\\d+\\):" #elif GTEST_USES_POSIX_RE - "gtest-port_test\\.cc:[0-9]+" + "googletest-port-test\\.cc:[0-9]+" #else - "gtest-port_test\\.cc:\\d+" + "googletest-port-test\\.cc:\\d+" #endif // _MSC_VER ".*a_false_condition.*Extra info.*"; @@ -389,15 +371,17 @@ TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) { // the platform. The test will produce compiler errors in case of failure. // For simplicity, we only cover the most important platforms here. TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) { -#if GTEST_HAS_POSIX_RE +#if !GTEST_USES_PCRE +# if GTEST_HAS_POSIX_RE EXPECT_TRUE(GTEST_USES_POSIX_RE); -#else +# else EXPECT_TRUE(GTEST_USES_SIMPLE_RE); -#endif +# endif +#endif // !GTEST_USES_PCRE } #if GTEST_USES_POSIX_RE @@ -1214,16 +1198,16 @@ class DestructorTracker { : index_(GetNewIndex()) {} ~DestructorTracker() { // We never access DestructorCall::List() concurrently, so we don't need - // to protect this acccess with a mutex. + // to protect this access with a mutex. DestructorCall::List()[index_]->ReportDestroyed(); } private: - static int GetNewIndex() { + static size_t GetNewIndex() { DestructorCall::List().push_back(new DestructorCall); return DestructorCall::List().size() - 1; } - const int index_; + const size_t index_; GTEST_DISALLOW_ASSIGN_(DestructorTracker); }; @@ -1240,25 +1224,18 @@ TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) { DestructorCall::ResetList(); { - // The next line default constructs a DestructorTracker object as - // the default value of objects managed by thread_local_tracker. ThreadLocal<DestructorTracker> thread_local_tracker; - ASSERT_EQ(1U, DestructorCall::List().size()); - ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed()); + ASSERT_EQ(0U, DestructorCall::List().size()); // This creates another DestructorTracker object for the main thread. thread_local_tracker.get(); - ASSERT_EQ(2U, DestructorCall::List().size()); + ASSERT_EQ(1U, DestructorCall::List().size()); ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed()); - ASSERT_FALSE(DestructorCall::List()[1]->CheckDestroyed()); } - // Now thread_local_tracker has died. It should have destroyed both the - // default value shared by all threads and the value for the main - // thread. - ASSERT_EQ(2U, DestructorCall::List().size()); + // Now thread_local_tracker has died. + ASSERT_EQ(1U, DestructorCall::List().size()); EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed()); - EXPECT_TRUE(DestructorCall::List()[1]->CheckDestroyed()); DestructorCall::ResetList(); } @@ -1269,29 +1246,22 @@ TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) { DestructorCall::ResetList(); { - // The next line default constructs a DestructorTracker object as - // the default value of objects managed by thread_local_tracker. ThreadLocal<DestructorTracker> thread_local_tracker; - ASSERT_EQ(1U, DestructorCall::List().size()); - ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed()); + ASSERT_EQ(0U, DestructorCall::List().size()); // This creates another DestructorTracker object in the new thread. ThreadWithParam<ThreadParam> thread( &CallThreadLocalGet, &thread_local_tracker, NULL); thread.Join(); - // The thread has exited, and we should have another DestroyedTracker + // The thread has exited, and we should have a DestroyedTracker // instance created for it. But it may not have been destroyed yet. - // The instance for the main thread should still persist. - ASSERT_EQ(2U, DestructorCall::List().size()); - ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed()); + ASSERT_EQ(1U, DestructorCall::List().size()); } - // The thread has exited and thread_local_tracker has died. The default - // value should have been destroyed too. - ASSERT_EQ(2U, DestructorCall::List().size()); + // The thread has exited and thread_local_tracker has died. + ASSERT_EQ(1U, DestructorCall::List().size()); EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed()); - EXPECT_TRUE(DestructorCall::List()[1]->CheckDestroyed()); DestructorCall::ResetList(); } @@ -1314,9 +1284,16 @@ TEST(WindowsTypesTest, HANDLEIsVoidStar) { StaticAssertTypeEq<HANDLE, void*>(); } +#if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR) +TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) { + StaticAssertTypeEq<CRITICAL_SECTION, _CRITICAL_SECTION>(); +} +#else TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) { StaticAssertTypeEq<CRITICAL_SECTION, _RTL_CRITICAL_SECTION>(); } +#endif + #endif // GTEST_OS_WINDOWS } // namespace internal diff --git a/security/nss/gtests/google_test/gtest/test/gtest-printers_test.cc b/security/nss/gtests/google_test/gtest/test/googletest-printers-test.cc index 7b07fd105..ea8369d27 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-printers_test.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-printers-test.cc @@ -26,15 +26,12 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) -// Google Test - The Google C++ Testing Framework + +// Google Test - The Google C++ Testing and Mocking Framework // // This file tests the universal value printer. -#include "gtest/gtest-printers.h" - #include <ctype.h> #include <limits.h> #include <string.h> @@ -48,15 +45,20 @@ #include <utility> #include <vector> +#include "gtest/gtest-printers.h" #include "gtest/gtest.h" -// hash_map and hash_set are available under Visual C++. -#if _MSC_VER -# define GTEST_HAS_HASH_MAP_ 1 // Indicates that hash_map is available. -# include <hash_map> // NOLINT -# define GTEST_HAS_HASH_SET_ 1 // Indicates that hash_set is available. -# include <hash_set> // NOLINT -#endif // GTEST_OS_WINDOWS +#if GTEST_HAS_UNORDERED_MAP_ +# include <unordered_map> // NOLINT +#endif // GTEST_HAS_UNORDERED_MAP_ + +#if GTEST_HAS_UNORDERED_SET_ +# include <unordered_set> // NOLINT +#endif // GTEST_HAS_UNORDERED_SET_ + +#if GTEST_HAS_STD_FORWARD_LIST_ +# include <forward_list> // NOLINT +#endif // GTEST_HAS_STD_FORWARD_LIST_ // Some user-defined types for testing the universal value printer. @@ -183,6 +185,25 @@ inline ::std::ostream& operator<<(::std::ostream& os, return os << "StreamableTemplateInFoo: " << x.value(); } +// A user-defined streamable but recursivly-defined container type in +// a user namespace, it mimics therefore std::filesystem::path or +// boost::filesystem::path. +class PathLike { + public: + struct iterator { + typedef PathLike value_type; + }; + + PathLike() {} + + iterator begin() const { return iterator(); } + iterator end() const { return iterator(); } + + friend ::std::ostream& operator<<(::std::ostream& os, const PathLike&) { + return os << "Streamable-PathLike"; + } +}; + } // namespace foo namespace testing { @@ -207,28 +228,14 @@ using ::testing::internal::Strings; using ::testing::internal::UniversalPrint; using ::testing::internal::UniversalPrinter; using ::testing::internal::UniversalTersePrint; +#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ using ::testing::internal::UniversalTersePrintTupleFieldsToStrings; -using ::testing::internal::string; - -// The hash_* classes are not part of the C++ standard. STLport -// defines them in namespace std. MSVC defines them in ::stdext. GCC -// defines them in ::. -#ifdef _STLP_HASH_MAP // We got <hash_map> from STLport. -using ::std::hash_map; -using ::std::hash_set; -using ::std::hash_multimap; -using ::std::hash_multiset; -#elif _MSC_VER -using ::stdext::hash_map; -using ::stdext::hash_set; -using ::stdext::hash_multimap; -using ::stdext::hash_multiset; #endif // Prints a value to a string using the universal value printer. This // is a helper for testing UniversalPrinter<T>::Print() for various types. template <typename T> -string Print(const T& value) { +std::string Print(const T& value) { ::std::stringstream ss; UniversalPrinter<T>::Print(value, &ss); return ss.str(); @@ -238,7 +245,7 @@ string Print(const T& value) { // value printer. This is a helper for testing // UniversalPrinter<T&>::Print() for various types. template <typename T> -string PrintByRef(const T& value) { +std::string PrintByRef(const T& value) { ::std::stringstream ss; UniversalPrinter<T&>::Print(value, &ss); return ss.str(); @@ -375,7 +382,7 @@ TEST(PrintBuiltInTypeTest, FloatingPoints) { // Since ::std::stringstream::operator<<(const void *) formats the pointer // output differently with different compilers, we have to create the expected // output first and use it as our expectation. -static string PrintPointer(const void *p) { +static std::string PrintPointer(const void* p) { ::std::stringstream expected_result_stream; expected_result_stream << p; return expected_result_stream.str(); @@ -563,7 +570,7 @@ struct Foo { TEST(PrintPointerTest, MemberVariablePointer) { EXPECT_TRUE(HasPrefix(Print(&Foo::value), Print(sizeof(&Foo::value)) + "-byte object ")); - int (Foo::*p) = NULL; // NOLINT + int Foo::*p = NULL; // NOLINT EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object ")); } @@ -588,7 +595,7 @@ TEST(PrintPointerTest, MemberFunctionPointer) { // The difference between this and Print() is that it ensures that the // argument is a reference to an array. template <typename T, size_t N> -string PrintArrayHelper(T (&a)[N]) { +std::string PrintArrayHelper(T (&a)[N]) { return Print(a); } @@ -641,7 +648,7 @@ TEST(PrintArrayTest, WConstCharArrayWithTerminatingNul) { // Array of objects. TEST(PrintArrayTest, ObjectArray) { - string a[3] = { "Hi", "Hello", "Ni hao" }; + std::string a[3] = {"Hi", "Hello", "Ni hao"}; EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a)); } @@ -778,22 +785,22 @@ TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) { EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a)); } -#if GTEST_HAS_STRING_PIECE_ +#if GTEST_HAS_ABSL -// Tests printing StringPiece. +// Tests printing ::absl::string_view. -TEST(PrintStringPieceTest, SimpleStringPiece) { - const StringPiece sp = "Hello"; +TEST(PrintStringViewTest, SimpleStringView) { + const ::absl::string_view sp = "Hello"; EXPECT_EQ("\"Hello\"", Print(sp)); } -TEST(PrintStringPieceTest, UnprintableCharacters) { +TEST(PrintStringViewTest, UnprintableCharacters) { const char str[] = "NUL (\0) and \r\t"; - const StringPiece sp(str, sizeof(str) - 1); + const ::absl::string_view sp(str, sizeof(str) - 1); EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp)); } -#endif // GTEST_HAS_STRING_PIECE_ +#endif // GTEST_HAS_ABSL // Tests printing STL containers. @@ -809,44 +816,44 @@ TEST(PrintStlContainerTest, NonEmptyDeque) { EXPECT_EQ("{ 1, 3 }", Print(non_empty)); } -#if GTEST_HAS_HASH_MAP_ +#if GTEST_HAS_UNORDERED_MAP_ TEST(PrintStlContainerTest, OneElementHashMap) { - hash_map<int, char> map1; + ::std::unordered_map<int, char> map1; map1[1] = 'a'; EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1)); } TEST(PrintStlContainerTest, HashMultiMap) { - hash_multimap<int, bool> map1; + ::std::unordered_multimap<int, bool> map1; map1.insert(make_pair(5, true)); map1.insert(make_pair(5, false)); // Elements of hash_multimap can be printed in any order. - const string result = Print(map1); + const std::string result = Print(map1); EXPECT_TRUE(result == "{ (5, true), (5, false) }" || result == "{ (5, false), (5, true) }") << " where Print(map1) returns \"" << result << "\"."; } -#endif // GTEST_HAS_HASH_MAP_ +#endif // GTEST_HAS_UNORDERED_MAP_ -#if GTEST_HAS_HASH_SET_ +#if GTEST_HAS_UNORDERED_SET_ TEST(PrintStlContainerTest, HashSet) { - hash_set<string> set1; - set1.insert("hello"); - EXPECT_EQ("{ \"hello\" }", Print(set1)); + ::std::unordered_set<int> set1; + set1.insert(1); + EXPECT_EQ("{ 1 }", Print(set1)); } TEST(PrintStlContainerTest, HashMultiSet) { const int kSize = 5; int a[kSize] = { 1, 1, 2, 5, 1 }; - hash_multiset<int> set1(a, a + kSize); + ::std::unordered_multiset<int> set1(a, a + kSize); // Elements of hash_multiset can be printed in any order. - const string result = Print(set1); - const string expected_pattern = "{ d, d, d, d, d }"; // d means a digit. + const std::string result = Print(set1); + const std::string expected_pattern = "{ d, d, d, d, d }"; // d means a digit. // Verifies the result matches the expected pattern; also extracts // the numbers in the result. @@ -868,14 +875,11 @@ TEST(PrintStlContainerTest, HashMultiSet) { EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin())); } -#endif // GTEST_HAS_HASH_SET_ +#endif // GTEST_HAS_UNORDERED_SET_ TEST(PrintStlContainerTest, List) { - const string a[] = { - "hello", - "world" - }; - const list<string> strings(a, a + 2); + const std::string a[] = {"hello", "world"}; + const list<std::string> strings(a, a + 2); EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings)); } @@ -913,6 +917,15 @@ TEST(PrintStlContainerTest, MultiSet) { EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1)); } +#if GTEST_HAS_STD_FORWARD_LIST_ + +TEST(PrintStlContainerTest, SinglyLinkedList) { + int a[] = { 9, 2, 8 }; + const std::forward_list<int> ints(a, a + 3); + EXPECT_EQ("{ 9, 2, 8 }", Print(ints)); +} +#endif // GTEST_HAS_STD_FORWARD_LIST_ + TEST(PrintStlContainerTest, Pair) { pair<const bool, int> p(true, 5); EXPECT_EQ("(true, 5)", Print(p)); @@ -1020,8 +1033,9 @@ TEST(PrintTr1TupleTest, VariousSizes) { // VC++ 2010's implementation of tuple of C++0x is deficient, requiring // an explicit type cast of NULL to be used. ::std::tr1::tuple<bool, char, short, testing::internal::Int32, // NOLINT - testing::internal::Int64, float, double, const char*, void*, string> - t10(false, 'a', 3, 4, 5, 1.5F, -2.5, str, + testing::internal::Int64, float, double, const char*, void*, + std::string> + t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT ImplicitCast_<void*>(NULL), "10"); EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + " pointing to \"8\", NULL, \"10\")", @@ -1037,7 +1051,7 @@ TEST(PrintTr1TupleTest, NestedTuple) { #endif // GTEST_HAS_TR1_TUPLE -#if GTEST_LANG_CXX11 +#if GTEST_HAS_STD_TUPLE_ // Tests printing ::std::tuples. // Tuples of various arities. @@ -1079,8 +1093,9 @@ TEST(PrintStdTupleTest, VariousSizes) { // VC++ 2010's implementation of tuple of C++0x is deficient, requiring // an explicit type cast of NULL to be used. ::std::tuple<bool, char, short, testing::internal::Int32, // NOLINT - testing::internal::Int64, float, double, const char*, void*, string> - t10(false, 'a', 3, 4, 5, 1.5F, -2.5, str, + testing::internal::Int64, float, double, const char*, void*, + std::string> + t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT ImplicitCast_<void*>(NULL), "10"); EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + " pointing to \"8\", NULL, \"10\")", @@ -1096,6 +1111,12 @@ TEST(PrintStdTupleTest, NestedTuple) { #endif // GTEST_LANG_CXX11 +#if GTEST_LANG_CXX11 +TEST(PrintNullptrT, Basic) { + EXPECT_EQ("(nullptr)", Print(nullptr)); +} +#endif // GTEST_LANG_CXX11 + // Tests printing user-defined unprintable types. // Unprintable types in the global namespace. @@ -1143,6 +1164,15 @@ TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) { Print(::foo::StreamableTemplateInFoo<int>())); } +// Tests printing a user-defined recursive container type that has a << +// operator. +TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) { + ::foo::PathLike x; + EXPECT_EQ("Streamable-PathLike", Print(x)); + const ::foo::PathLike cx; + EXPECT_EQ("Streamable-PathLike", Print(cx)); +} + // Tests printing user-defined types that have a PrintTo() function. TEST(PrintPrintableTypeTest, InUserNamespace) { EXPECT_EQ("PrintableViaPrintTo: 0", @@ -1162,37 +1192,6 @@ TEST(PrintPrintableTypeTest, TemplateInUserNamespace) { Print(::foo::PrintableViaPrintToTemplate<int>(5))); } -#if GTEST_HAS_PROTOBUF_ - -// Tests printing a short proto2 message. -TEST(PrintProto2MessageTest, PrintsShortDebugStringWhenItIsShort) { - testing::internal::FooMessage msg; - msg.set_int_field(2); - msg.set_string_field("hello"); - EXPECT_PRED2(RE::FullMatch, Print(msg), - "<int_field:\\s*2\\s+string_field:\\s*\"hello\">"); -} - -// Tests printing a long proto2 message. -TEST(PrintProto2MessageTest, PrintsDebugStringWhenItIsLong) { - testing::internal::FooMessage msg; - msg.set_int_field(2); - msg.set_string_field("hello"); - msg.add_names("peter"); - msg.add_names("paul"); - msg.add_names("mary"); - EXPECT_PRED2(RE::FullMatch, Print(msg), - "<\n" - "int_field:\\s*2\n" - "string_field:\\s*\"hello\"\n" - "names:\\s*\"peter\"\n" - "names:\\s*\"paul\"\n" - "names:\\s*\"mary\"\n" - ">"); -} - -#endif // GTEST_HAS_PROTOBUF_ - // Tests that the universal printer prints both the address and the // value of a reference. TEST(PrintReferenceTest, PrintsAddressAndValue) { @@ -1216,13 +1215,13 @@ TEST(PrintReferenceTest, PrintsAddressAndValue) { // reference. TEST(PrintReferenceTest, HandlesFunctionPointer) { void (*fp)(int n) = &MyFunction; - const string fp_pointer_string = + const std::string fp_pointer_string = PrintPointer(reinterpret_cast<const void*>(&fp)); // We cannot directly cast &MyFunction to const void* because the // standard disallows casting between pointers to functions and // pointers to objects, and some compilers (e.g. GCC 3.4) enforce // this limitation. - const string fp_string = PrintPointer(reinterpret_cast<const void*>( + const std::string fp_string = PrintPointer(reinterpret_cast<const void*>( reinterpret_cast<internal::BiggestInt>(fp))); EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, PrintByRef(fp)); @@ -1247,7 +1246,7 @@ TEST(PrintReferenceTest, HandlesMemberFunctionPointer) { // Tests that the universal printer prints a member variable pointer // passed by reference. TEST(PrintReferenceTest, HandlesMemberVariablePointer) { - int (Foo::*p) = &Foo::value; // NOLINT + int Foo::*p = &Foo::value; // NOLINT EXPECT_TRUE(HasPrefix( PrintByRef(p), "@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object ")); @@ -1280,7 +1279,7 @@ TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) { } // Tests formatting a char pointer when it's compared with another pointer. -// In this case we want to print it as a raw pointer, as the comparision is by +// In this case we want to print it as a raw pointer, as the comparison is by // pointer. // char pointer vs pointer @@ -1505,6 +1504,78 @@ TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) { EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\""); } + TEST(PrintToStringTest, ContainsNonLatin) { + // Sanity test with valid UTF-8. Prints both in hex and as text. + std::string non_ascii_str = ::std::string("ì˜¤ì „ 4:30"); + EXPECT_PRINT_TO_STRING_(non_ascii_str, + "\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n" + " As Text: \"ì˜¤ì „ 4:30\""); + non_ascii_str = ::std::string("From ä — ẑ"); + EXPECT_PRINT_TO_STRING_(non_ascii_str, + "\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\"" + "\n As Text: \"From ä — ẑ\""); +} + +TEST(IsValidUTF8Test, IllFormedUTF8) { + // The following test strings are ill-formed UTF-8 and are printed + // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is + // expected to fail, thus output does not contain "As Text:". + + static const char *const kTestdata[][2] = { + // 2-byte lead byte followed by a single-byte character. + {"\xC3\x74", "\"\\xC3t\""}, + // Valid 2-byte character followed by an orphan trail byte. + {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""}, + // Lead byte without trail byte. + {"abc\xC3", "\"abc\\xC3\""}, + // 3-byte lead byte, single-byte character, orphan trail byte. + {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""}, + // Truncated 3-byte character. + {"\xE2\x80", "\"\\xE2\\x80\""}, + // Truncated 3-byte character followed by valid 2-byte char. + {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""}, + // Truncated 3-byte character followed by a single-byte character. + {"\xE2\x80\x7A", "\"\\xE2\\x80z\""}, + // 3-byte lead byte followed by valid 3-byte character. + {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""}, + // 4-byte lead byte followed by valid 3-byte character. + {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""}, + // Truncated 4-byte character. + {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""}, + // Invalid UTF-8 byte sequences embedded in other chars. + {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""}, + {"abc\xC3\x84\xE2\x80\xC3\x84xyz", + "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""}, + // Non-shortest UTF-8 byte sequences are also ill-formed. + // The classics: xC0, xC1 lead byte. + {"\xC0\x80", "\"\\xC0\\x80\""}, + {"\xC1\x81", "\"\\xC1\\x81\""}, + // Non-shortest sequences. + {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""}, + {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""}, + // Last valid code point before surrogate range, should be printed as text, + // too. + {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n As Text: \"퟿\""}, + // Start of surrogate lead. Surrogates are not printed as text. + {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""}, + // Last non-private surrogate lead. + {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""}, + // First private-use surrogate lead. + {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""}, + // Last private-use surrogate lead. + {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""}, + // Mid-point of surrogate trail. + {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""}, + // First valid code point after surrogate range, should be printed as text, + // too. + {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""} + }; + + for (int i = 0; i < int(sizeof(kTestdata)/sizeof(kTestdata[0])); ++i) { + EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]); + } +} + #undef EXPECT_PRINT_TO_STRING_ TEST(UniversalTersePrintTest, WorksForNonReference) { @@ -1554,12 +1625,12 @@ TEST(UniversalPrintTest, WorksForCString) { const char* s1 = "abc"; ::std::stringstream ss1; UniversalPrint(s1, &ss1); - EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", string(ss1.str())); + EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", std::string(ss1.str())); char* s2 = const_cast<char*>(s1); ::std::stringstream ss2; UniversalPrint(s2, &ss2); - EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", string(ss2.str())); + EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", std::string(ss2.str())); const char* s3 = NULL; ::std::stringstream ss3; @@ -1646,6 +1717,32 @@ TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) { #endif // GTEST_HAS_STD_TUPLE_ +#if GTEST_HAS_ABSL + +TEST(PrintOptionalTest, Basic) { + absl::optional<int> value; + EXPECT_EQ("(nullopt)", PrintToString(value)); + value = {7}; + EXPECT_EQ("(7)", PrintToString(value)); + EXPECT_EQ("(1.1)", PrintToString(absl::optional<double>{1.1})); + EXPECT_EQ("(\"A\")", PrintToString(absl::optional<std::string>{"A"})); +} + +struct NonPrintable { + unsigned char contents = 17; +}; + +TEST(PrintOneofTest, Basic) { + using Type = absl::variant<int, StreamableInGlobal, NonPrintable>; + EXPECT_EQ("('int' with value 7)", PrintToString(Type(7))); + EXPECT_EQ("('StreamableInGlobal' with value StreamableInGlobal)", + PrintToString(Type(StreamableInGlobal{}))); + EXPECT_EQ( + "('testing::gtest_printers_test::NonPrintable' with value 1-byte object " + "<11>)", + PrintToString(Type(NonPrintable{}))); +} +#endif // GTEST_HAS_ABSL + } // namespace gtest_printers_test } // namespace testing - diff --git a/security/nss/gtests/google_test/gtest/test/gtest_shuffle_test.py b/security/nss/gtests/google_test/gtest/test/googletest-shuffle-test.py index 30d0303d1..573cc5eca 100755..100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_shuffle_test.py +++ b/security/nss/gtests/google_test/gtest/test/googletest-shuffle-test.py @@ -30,13 +30,11 @@ """Verifies that test shuffling works.""" -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import gtest_test_utils -# Command to run the gtest_shuffle_test_ program. -COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_shuffle_test_') +# Command to run the googletest-shuffle-test_ program. +COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-shuffle-test_') # The environment variables for test sharding. TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS' @@ -89,7 +87,7 @@ def GetTestsForAllIterations(extra_env, args): Args: extra_env: a map from environment variables to their values - args: command line flags to pass to gtest_shuffle_test_ + args: command line flags to pass to googletest-shuffle-test_ Returns: A list where the i-th element is the list of tests run in the i-th diff --git a/security/nss/gtests/google_test/gtest/test/gtest_shuffle_test_.cc b/security/nss/gtests/google_test/gtest/test/googletest-shuffle-test_.cc index 6fb441bd4..1fe5f6aba 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_shuffle_test_.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-shuffle-test_.cc @@ -26,8 +26,7 @@ // 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) + // Verifies that test shuffling works. diff --git a/security/nss/gtests/google_test/gtest/test/gtest-test-part_test.cc b/security/nss/gtests/google_test/gtest/test/googletest-test-part-test.cc index ca8ba933a..cd2d6f9e8 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-test-part_test.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-test-part-test.cc @@ -26,9 +26,6 @@ // 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" @@ -203,6 +200,6 @@ TEST_F(TestPartResultArrayDeathTest, DiesWhenIndexIsOutOfBound) { EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(1), ""); } -// TODO(mheule@google.com): Add a test for the class HasNewFatalFailureHelper. +// FIXME: Add a test for the class HasNewFatalFailureHelper. } // namespace diff --git a/security/nss/gtests/google_test/gtest/test/googletest-test2_test.cc b/security/nss/gtests/google_test/gtest/test/googletest-test2_test.cc new file mode 100644 index 000000000..c2f98dc7d --- /dev/null +++ b/security/nss/gtests/google_test/gtest/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. + +// +// 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 googletest-param-test-test.cc. +ParamGenerator<int> 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 +// googletest-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 googletest-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/security/nss/gtests/google_test/gtest/test/gtest_throw_on_failure_test.py b/security/nss/gtests/google_test/gtest/test/googletest-throw-on-failure-test.py index 5678ffeaf..46cb9f6da 100755..100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_throw_on_failure_test.py +++ b/security/nss/gtests/google_test/gtest/test/googletest-throw-on-failure-test.py @@ -31,12 +31,10 @@ """Tests Google Test's throw-on-failure mode with exceptions disabled. -This script invokes gtest_throw_on_failure_test_ (a program written with +This script invokes googletest-throw-on-failure-test_ (a program written with Google Test) with different environments and command line flags. """ -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import gtest_test_utils @@ -46,10 +44,10 @@ import gtest_test_utils # The command line flag for enabling/disabling the throw-on-failure mode. THROW_ON_FAILURE = 'gtest_throw_on_failure' -# Path to the gtest_throw_on_failure_test_ program, compiled with +# Path to the googletest-throw-on-failure-test_ program, compiled with # exceptions disabled. EXE_PATH = gtest_test_utils.GetTestExecutablePath( - 'gtest_throw_on_failure_test_') + 'googletest-throw-on-failure-test_') # Utilities. @@ -75,13 +73,13 @@ def Run(command): return p.exited and p.exit_code == 0 -# The tests. TODO(wan@google.com): refactor the class to share common -# logic with code in gtest_break_on_failure_unittest.py. +# The tests. FIXME: refactor the class to share common +# logic with code in googletest-break-on-failure-unittest.py. class ThrowOnFailureTest(gtest_test_utils.TestCase): """Tests the throw-on-failure mode.""" def RunAndVerify(self, env_var_value, flag_value, should_fail): - """Runs gtest_throw_on_failure_test_ and verifies that it does + """Runs googletest-throw-on-failure-test_ and verifies that it does (or does not) exit with a non-zero code. Args: diff --git a/security/nss/gtests/google_test/gtest/test/gtest_throw_on_failure_test_.cc b/security/nss/gtests/google_test/gtest/test/googletest-throw-on-failure-test_.cc index 2b88fe3d9..f9a2c6448 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_throw_on_failure_test_.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-throw-on-failure-test_.cc @@ -26,13 +26,12 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests Google Test's throw-on-failure mode with exceptions disabled. // // This program must be compiled with exceptions disabled. It will be -// invoked by gtest_throw_on_failure_test.py, and is expected to exit +// invoked by googletest-throw-on-failure-test.py, and is expected to exit // with non-zero in the throw-on-failure mode or 0 otherwise. #include "gtest/gtest.h" diff --git a/security/nss/gtests/google_test/gtest/test/gtest-tuple_test.cc b/security/nss/gtests/google_test/gtest/test/googletest-tuple-test.cc index bfaa3e0ac..dd82c160f 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-tuple_test.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-tuple-test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + #include "gtest/internal/gtest-tuple.h" #include <utility> diff --git a/security/nss/gtests/google_test/gtest/test/gtest_uninitialized_test.py b/security/nss/gtests/google_test/gtest/test/googletest-uninitialized-test.py index 6ae57eeed..5b7d1e74f 100755..100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_uninitialized_test.py +++ b/security/nss/gtests/google_test/gtest/test/googletest-uninitialized-test.py @@ -31,12 +31,9 @@ """Verifies that Google Test warns the user when not initialized properly.""" -__author__ = 'wan@google.com (Zhanyong Wan)' - import gtest_test_utils - -COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_uninitialized_test_') +COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-uninitialized-test_') def Assert(condition): @@ -56,8 +53,8 @@ def TestExitCodeAndOutput(command): # Verifies that 'command' exits with code 1. p = gtest_test_utils.Subprocess(command) - Assert(p.exited) - AssertEq(1, p.exit_code) + if p.exited and p.exit_code == 0: + Assert('IMPORTANT NOTICE' in p.output); Assert('InitGoogleTest' in p.output) diff --git a/security/nss/gtests/google_test/gtest/test/gtest_uninitialized_test_.cc b/security/nss/gtests/google_test/gtest/test/googletest-uninitialized-test_.cc index 44316987f..b4434d51e 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_uninitialized_test_.cc +++ b/security/nss/gtests/google_test/gtest/test/googletest-uninitialized-test_.cc @@ -26,16 +26,15 @@ // 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. + // RUN_ALL_TESTS() is called without + // testing::InitGoogleTest() being called first. } int main() { diff --git a/security/nss/gtests/google_test/gtest/test/gtest-typed-test2_test.cc b/security/nss/gtests/google_test/gtest/test/gtest-typed-test2_test.cc index c284700b0..ed96421c6 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-typed-test2_test.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest-typed-test2_test.cc @@ -26,8 +26,7 @@ // 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 <vector> diff --git a/security/nss/gtests/google_test/gtest/test/gtest-typed-test_test.cc b/security/nss/gtests/google_test/gtest/test/gtest-typed-test_test.cc index c3e66c2db..4e398697d 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-typed-test_test.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest-typed-test_test.cc @@ -26,8 +26,7 @@ // 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 "test/gtest-typed-test_test.h" @@ -36,6 +35,10 @@ #include "gtest/gtest.h" +#if _MSC_VER +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */) +#endif // _MSC_VER + using testing::Test; // Used for testing that SetUpTestCase()/TearDownTestCase(), fixture @@ -166,6 +169,40 @@ TYPED_TEST(NumericTest, DefaultIsZero) { } // namespace library1 +// Tests that custom names work. +template <typename T> +class TypedTestWithNames : public Test {}; + +class TypedTestNames { + public: + template <typename T> + static std::string GetName(int i) { + if (testing::internal::IsSame<T, char>::value) { + return std::string("char") + ::testing::PrintToString(i); + } + if (testing::internal::IsSame<T, int>::value) { + return std::string("int") + ::testing::PrintToString(i); + } + } +}; + +TYPED_TEST_CASE(TypedTestWithNames, TwoTypes, TypedTestNames); + +TYPED_TEST(TypedTestWithNames, TestCaseName) { + if (testing::internal::IsSame<TypeParam, char>::value) { + EXPECT_STREQ(::testing::UnitTest::GetInstance() + ->current_test_info() + ->test_case_name(), + "TypedTestWithNames/char0"); + } + if (testing::internal::IsSame<TypeParam, int>::value) { + EXPECT_STREQ(::testing::UnitTest::GetInstance() + ->current_test_info() + ->test_case_name(), + "TypedTestWithNames/int1"); + } +} + #endif // GTEST_HAS_TYPED_TEST // This #ifdef block tests type-parameterized tests. @@ -266,6 +303,46 @@ REGISTER_TYPED_TEST_CASE_P(DerivedTest, typedef Types<short, long> MyTwoTypes; INSTANTIATE_TYPED_TEST_CASE_P(My, DerivedTest, MyTwoTypes); +// Tests that custom names work with type parametrized tests. We reuse the +// TwoTypes from above here. +template <typename T> +class TypeParametrizedTestWithNames : public Test {}; + +TYPED_TEST_CASE_P(TypeParametrizedTestWithNames); + +TYPED_TEST_P(TypeParametrizedTestWithNames, TestCaseName) { + if (testing::internal::IsSame<TypeParam, char>::value) { + EXPECT_STREQ(::testing::UnitTest::GetInstance() + ->current_test_info() + ->test_case_name(), + "CustomName/TypeParametrizedTestWithNames/parChar0"); + } + if (testing::internal::IsSame<TypeParam, int>::value) { + EXPECT_STREQ(::testing::UnitTest::GetInstance() + ->current_test_info() + ->test_case_name(), + "CustomName/TypeParametrizedTestWithNames/parInt1"); + } +} + +REGISTER_TYPED_TEST_CASE_P(TypeParametrizedTestWithNames, TestCaseName); + +class TypeParametrizedTestNames { + public: + template <typename T> + static std::string GetName(int i) { + if (testing::internal::IsSame<T, char>::value) { + return std::string("parChar") + ::testing::PrintToString(i); + } + if (testing::internal::IsSame<T, int>::value) { + return std::string("parInt") + ::testing::PrintToString(i); + } + } +}; + +INSTANTIATE_TYPED_TEST_CASE_P(CustomName, TypeParametrizedTestWithNames, + TwoTypes, TypeParametrizedTestNames); + // Tests that multiple TYPED_TEST_CASE_P's can be defined in the same // translation unit. @@ -344,6 +421,25 @@ REGISTER_TYPED_TEST_CASE_P(NumericTest, typedef Types<int, double> NumericTypes; INSTANTIATE_TYPED_TEST_CASE_P(My, NumericTest, NumericTypes); +static const char* GetTestName() { + return testing::UnitTest::GetInstance()->current_test_info()->name(); +} +// Test the stripping of space from test names +template <typename T> class TrimmedTest : public Test { }; +TYPED_TEST_CASE_P(TrimmedTest); +TYPED_TEST_P(TrimmedTest, Test1) { EXPECT_STREQ("Test1", GetTestName()); } +TYPED_TEST_P(TrimmedTest, Test2) { EXPECT_STREQ("Test2", GetTestName()); } +TYPED_TEST_P(TrimmedTest, Test3) { EXPECT_STREQ("Test3", GetTestName()); } +TYPED_TEST_P(TrimmedTest, Test4) { EXPECT_STREQ("Test4", GetTestName()); } +TYPED_TEST_P(TrimmedTest, Test5) { EXPECT_STREQ("Test5", GetTestName()); } +REGISTER_TYPED_TEST_CASE_P( + TrimmedTest, + Test1, Test2,Test3 , Test4 ,Test5 ); // NOLINT +template <typename T1, typename T2> struct MyPair {}; +// Be sure to try a type with a comma in its name just in case it matters. +typedef Types<int, double, MyPair<int, int> > TrimTypes; +INSTANTIATE_TYPED_TEST_CASE_P(My, TrimmedTest, TrimTypes); + } // namespace library2 #endif // GTEST_HAS_TYPED_TEST_P @@ -358,4 +454,8 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, NumericTest, NumericTypes); // must be defined). This dummy test keeps gtest_main linked in. TEST(DummyTest, TypedTestsAreNotSupportedOnThisPlatform) {} +#if _MSC_VER +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127 +#endif // _MSC_VER + #endif // #if !defined(GTEST_HAS_TYPED_TEST) && !defined(GTEST_HAS_TYPED_TEST_P) diff --git a/security/nss/gtests/google_test/gtest/test/gtest-typed-test_test.h b/security/nss/gtests/google_test/gtest/test/gtest-typed-test_test.h index 41d75704c..2cce67c82 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-typed-test_test.h +++ b/security/nss/gtests/google_test/gtest/test/gtest-typed-test_test.h @@ -26,8 +26,7 @@ // 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) + #ifndef GTEST_TEST_GTEST_TYPED_TEST_TEST_H_ #define GTEST_TEST_GTEST_TYPED_TEST_TEST_H_ diff --git a/security/nss/gtests/google_test/gtest/test/gtest-unittest-api_test.cc b/security/nss/gtests/google_test/gtest/test/gtest-unittest-api_test.cc index b1f51688a..f3ea03a59 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest-unittest-api_test.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest-unittest-api_test.cc @@ -25,10 +25,9 @@ // 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) -// -// The Google C++ Testing Framework (Google Test) +// The Google C++ Testing and Mocking Framework (Google Test) // // This file contains tests verifying correctness of data provided via // UnitTest's public methods. diff --git a/security/nss/gtests/google_test/gtest/test/gtest_all_test.cc b/security/nss/gtests/google_test/gtest/test/gtest_all_test.cc index 955aa6282..e61e36b1d 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_all_test.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest_all_test.cc @@ -26,21 +26,20 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + // -// Author: wan@google.com (Zhanyong Wan) -// -// Tests for Google C++ Testing Framework (Google Test) +// Tests for Google C++ Testing and Mocking Framework (Google Test) // // Sometimes it's desirable to build most of Google Test's own tests // by compiling a single file. This file serves this purpose. -#include "test/gtest-filepath_test.cc" -#include "test/gtest-linked_ptr_test.cc" -#include "test/gtest-message_test.cc" -#include "test/gtest-options_test.cc" -#include "test/gtest-port_test.cc" +#include "test/googletest-filepath-test.cc" +#include "test/googletest-linked-ptr-test.cc" +#include "test/googletest-message-test.cc" +#include "test/googletest-options-test.cc" +#include "test/googletest-port-test.cc" #include "test/gtest_pred_impl_unittest.cc" #include "test/gtest_prod_test.cc" -#include "test/gtest-test-part_test.cc" +#include "test/googletest-test-part-test.cc" #include "test/gtest-typed-test_test.cc" #include "test/gtest-typed-test2_test.cc" #include "test/gtest_unittest.cc" diff --git a/security/nss/gtests/google_test/gtest/test/gtest_assert_by_exception_test.cc b/security/nss/gtests/google_test/gtest/test/gtest_assert_by_exception_test.cc new file mode 100644 index 000000000..0eae8575f --- /dev/null +++ b/security/nss/gtests/google_test/gtest/test/gtest_assert_by_exception_test.cc @@ -0,0 +1,118 @@ +// Copyright 2009, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +// Tests Google Test's assert-by-exception mode with exceptions enabled. + +#include "gtest/gtest.h" + +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <stdexcept> + +class ThrowListener : public testing::EmptyTestEventListener { + void OnTestPartResult(const testing::TestPartResult& result) override { + if (result.type() == testing::TestPartResult::kFatalFailure) { + throw testing::AssertionException(result); + } + } +}; + +// Prints the given failure message and exits the program with +// non-zero. We use this instead of a Google Test assertion to +// indicate a failure, as the latter is been tested and cannot be +// relied on. +void Fail(const char* msg) { + printf("FAILURE: %s\n", msg); + fflush(stdout); + exit(1); +} + +static void AssertFalse() { + ASSERT_EQ(2, 3) << "Expected failure"; +} + +// Tests that an assertion failure throws a subclass of +// std::runtime_error. +TEST(Test, Test) { + // A successful assertion shouldn't throw. + try { + EXPECT_EQ(3, 3); + } catch(...) { + Fail("A successful assertion wrongfully threw."); + } + + // A successful assertion shouldn't throw. + try { + EXPECT_EQ(3, 4); + } catch(...) { + Fail("A failed non-fatal assertion wrongfully threw."); + } + + // A failed assertion should throw. + try { + AssertFalse(); + } catch(const testing::AssertionException& e) { + if (strstr(e.what(), "Expected failure") != NULL) + throw; + + printf("%s", + "A failed assertion did throw an exception of the right type, " + "but the message is incorrect. Instead of containing \"Expected " + "failure\", it is:\n"); + Fail(e.what()); + } catch(...) { + Fail("A failed assertion threw the wrong type of exception."); + } + Fail("A failed assertion should've thrown but didn't."); +} + +int kTestForContinuingTest = 0; + +TEST(Test, Test2) { + // FIXME: how to force Test2 to be after Test? + kTestForContinuingTest = 1; +} + +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener); + + int result = RUN_ALL_TESTS(); + if (result == 0) { + printf("RUN_ALL_TESTS returned %d\n", result); + Fail("Expected failure instead."); + } + + if (kTestForContinuingTest == 0) { + Fail("Should have continued with other tests, but did not."); + } + return 0; +} diff --git a/security/nss/gtests/google_test/gtest/test/gtest_environment_test.cc b/security/nss/gtests/google_test/gtest/test/gtest_environment_test.cc index 3cff19e70..bc9524d66 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_environment_test.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest_environment_test.cc @@ -26,18 +26,14 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Tests using global test environments. #include <stdlib.h> #include <stdio.h> #include "gtest/gtest.h" - -#define GTEST_IMPLEMENTATION_ 1 // Required for the next #include. #include "src/gtest-internal-inl.h" -#undef GTEST_IMPLEMENTATION_ namespace testing { GTEST_DECLARE_string_(filter); diff --git a/security/nss/gtests/google_test/gtest/test/gtest_help_test.py b/security/nss/gtests/google_test/gtest/test/gtest_help_test.py index 093c838d9..582d24c2d 100755 --- a/security/nss/gtests/google_test/gtest/test/gtest_help_test.py +++ b/security/nss/gtests/google_test/gtest/test/gtest_help_test.py @@ -29,7 +29,7 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -"""Tests the --help flag of Google C++ Testing Framework. +"""Tests the --help flag of Google C++ Testing and Mocking Framework. SYNOPSIS gtest_help_test.py --build_dir=BUILD/DIR @@ -37,8 +37,6 @@ SYNOPSIS gtest_help_test.py """ -__author__ = 'wan@google.com (Zhanyong Wan)' - import os import re import gtest_test_utils diff --git a/security/nss/gtests/google_test/gtest/test/gtest_help_test_.cc b/security/nss/gtests/google_test/gtest/test/gtest_help_test_.cc index 31f78c244..750ae6ce9 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_help_test_.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest_help_test_.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // This program is meant to be run by gtest_help_test.py. Do not run // it directly. diff --git a/security/nss/gtests/google_test/gtest/test/gtest_json_test_utils.py b/security/nss/gtests/google_test/gtest/test/gtest_json_test_utils.py new file mode 100644 index 000000000..62bbfc288 --- /dev/null +++ b/security/nss/gtests/google_test/gtest/test/gtest_json_test_utils.py @@ -0,0 +1,60 @@ +# 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 utilities for gtest_json_output.""" + +import re + + +def normalize(obj): + """Normalize output object. + + Args: + obj: Google Test's JSON output object to normalize. + + Returns: + Normalized output without any references to transient information that may + change from run to run. + """ + def _normalize(key, value): + if key == 'time': + return re.sub(r'^\d+(\.\d+)?s$', '*', value) + elif key == 'timestamp': + return re.sub(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$', '*', value) + elif key == 'failure': + value = re.sub(r'^.*[/\\](.*:)\d+\n', '\\1*\n', value) + return re.sub(r'Stack trace:\n(.|\n)*', 'Stack trace:\n*', value) + else: + return normalize(value) + if isinstance(obj, dict): + return {k: _normalize(k, v) for k, v in obj.items()} + if isinstance(obj, list): + return [normalize(x) for x in obj] + else: + return obj diff --git a/security/nss/gtests/google_test/gtest/test/gtest_list_output_unittest.py b/security/nss/gtests/google_test/gtest/test/gtest_list_output_unittest.py new file mode 100644 index 000000000..3bba7ea2c --- /dev/null +++ b/security/nss/gtests/google_test/gtest/test/gtest_list_output_unittest.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python +# +# Copyright 2006, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +"""Unit test for Google Test's --gtest_list_tests flag. + +A user can ask Google Test to list all tests by specifying the +--gtest_list_tests flag. If output is requested, via --gtest_output=xml +or --gtest_output=json, the tests are listed, with extra information in the +output file. +This script tests such functionality by invoking gtest_list_output_unittest_ + (a program written with Google Test) the command line flags. +""" + +import os +import re +import gtest_test_utils + +GTEST_LIST_TESTS_FLAG = '--gtest_list_tests' +GTEST_OUTPUT_FLAG = '--gtest_output' + +EXPECTED_XML = """<\?xml version="1.0" encoding="UTF-8"\?> +<testsuites tests="2" name="AllTests"> + <testsuite name="FooTest" tests="2"> + <testcase name="Test1" file=".*gtest_list_output_unittest_.cc" line="43" /> + <testcase name="Test2" file=".*gtest_list_output_unittest_.cc" line="45" /> + </testsuite> +</testsuites> +""" + +EXPECTED_JSON = """{ + "tests": 2, + "name": "AllTests", + "testsuites": \[ + { + "name": "FooTest", + "tests": 2, + "testsuite": \[ + { + "name": "Test1", + "file": ".*gtest_list_output_unittest_.cc", + "line": 43 + }, + { + "name": "Test2", + "file": ".*gtest_list_output_unittest_.cc", + "line": 45 + } + \] + } + \] +} +""" + + +class GTestListTestsOutputUnitTest(gtest_test_utils.TestCase): + """Unit test for Google Test's list tests with output to file functionality. + """ + + def testXml(self): + """Verifies XML output for listing tests in a Google Test binary. + + Runs a test program that generates an empty XML output, and + tests that the XML output is expected. + """ + self._TestOutput('xml', EXPECTED_XML) + + def testJSON(self): + """Verifies XML output for listing tests in a Google Test binary. + + Runs a test program that generates an empty XML output, and + tests that the XML output is expected. + """ + self._TestOutput('json', EXPECTED_JSON) + + def _GetOutput(self, out_format): + file_path = os.path.join(gtest_test_utils.GetTempDir(), + 'test_out.' + out_format) + gtest_prog_path = gtest_test_utils.GetTestExecutablePath( + 'gtest_list_output_unittest_') + + command = ([ + gtest_prog_path, + '%s=%s:%s' % (GTEST_OUTPUT_FLAG, out_format, file_path), + '--gtest_list_tests' + ]) + environ_copy = os.environ.copy() + p = gtest_test_utils.Subprocess( + command, env=environ_copy, working_dir=gtest_test_utils.GetTempDir()) + + self.assert_(p.exited) + self.assertEquals(0, p.exit_code) + with open(file_path) as f: + result = f.read() + return result + + def _TestOutput(self, test_format, expected_output): + actual = self._GetOutput(test_format) + actual_lines = actual.splitlines() + expected_lines = expected_output.splitlines() + line_count = 0 + for actual_line in actual_lines: + expected_line = expected_lines[line_count] + expected_line_re = re.compile(expected_line.strip()) + self.assert_( + expected_line_re.match(actual_line.strip()), + ('actual output of "%s",\n' + 'which does not match expected regex of "%s"\n' + 'on line %d' % (actual, expected_output, line_count))) + line_count = line_count + 1 + + +if __name__ == '__main__': + os.environ['GTEST_STACK_TRACE_DEPTH'] = '1' + gtest_test_utils.Main() diff --git a/security/nss/gtests/google_test/gtest/test/gtest_list_output_unittest_.cc b/security/nss/gtests/google_test/gtest/test/gtest_list_output_unittest_.cc new file mode 100644 index 000000000..b1c7b4de3 --- /dev/null +++ b/security/nss/gtests/google_test/gtest/test/gtest_list_output_unittest_.cc @@ -0,0 +1,51 @@ +// 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. +// +// Author: david.schuldenfrei@gmail.com (David Schuldenfrei) + +// Unit test for Google Test's --gtest_list_tests and --gtest_output flag. +// +// A user can ask Google Test to list all tests that will run, +// and have the output saved in a Json/Xml file. +// The tests will not be run after listing. +// +// This program will be invoked from a Python unit test. +// Don't run it directly. + +#include "gtest/gtest.h" + +TEST(FooTest, Test1) {} + +TEST(FooTest, Test2) {} + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + + return RUN_ALL_TESTS(); +} diff --git a/security/nss/gtests/google_test/gtest/test/gtest_main_unittest.cc b/security/nss/gtests/google_test/gtest/test/gtest_main_unittest.cc index ecd9bb876..eddedeabe 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_main_unittest.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest_main_unittest.cc @@ -26,8 +26,7 @@ // 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" @@ -41,5 +40,5 @@ TEST(GTestMainTest, ShouldSucceed) { } // namespace -// We are using the main() function defined in src/gtest_main.cc, so -// we don't define it here. +// We are using the main() function defined in gtest_main.cc, so we +// don't define it here. diff --git a/security/nss/gtests/google_test/gtest/test/gtest_no_test_unittest.cc b/security/nss/gtests/google_test/gtest/test/gtest_no_test_unittest.cc index 292599af8..d4f88dbfd 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_no_test_unittest.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest_no_test_unittest.cc @@ -29,8 +29,6 @@ // Tests that a Google Test program that has no test defined can run // successfully. -// -// Author: wan@google.com (Zhanyong Wan) #include "gtest/gtest.h" diff --git a/security/nss/gtests/google_test/gtest/test/gtest_pred_impl_unittest.cc b/security/nss/gtests/google_test/gtest/test/gtest_pred_impl_unittest.cc index a84eff860..b466c150a 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_pred_impl_unittest.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest_pred_impl_unittest.cc @@ -27,7 +27,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// This file is AUTOMATICALLY GENERATED on 10/31/2011 by command +// This file is AUTOMATICALLY GENERATED on 01/02/2018 by command // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! // Regression test for gtest_pred_impl.h diff --git a/security/nss/gtests/google_test/gtest/test/gtest_premature_exit_test.cc b/security/nss/gtests/google_test/gtest/test/gtest_premature_exit_test.cc index c1ed96866..c1e93056d 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_premature_exit_test.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest_premature_exit_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Tests that Google Test manipulates the premature-exit-detection // file correctly. @@ -44,10 +43,6 @@ using ::testing::internal::posix::StatStruct; namespace { -// Is the TEST_PREMATURE_EXIT_FILE environment variable expected to be -// set? -const bool kTestPrematureExitFileEnvVarShouldBeSet = false; - class PrematureExitTest : public Test { public: // Returns true iff the given file exists. @@ -97,18 +92,6 @@ TEST_F(PrematureExitDeathTest, FileExistsDuringExecutionOfDeathTest) { }, ""); } -// Tests that TEST_PREMATURE_EXIT_FILE is set where it's expected to -// be set. -TEST_F(PrematureExitTest, TestPrematureExitFileEnvVarIsSet) { - GTEST_INTENTIONAL_CONST_COND_PUSH_() - if (kTestPrematureExitFileEnvVarShouldBeSet) { - GTEST_INTENTIONAL_CONST_COND_POP_() - const char* const filepath = GetEnv("TEST_PREMATURE_EXIT_FILE"); - ASSERT_TRUE(filepath != NULL); - ASSERT_NE(*filepath, '\0'); - } -} - // Tests that the premature-exit file exists during the execution of a // normal (non-death) test. TEST_F(PrematureExitTest, PrematureExitFileExistsDuringTestExecution) { diff --git a/security/nss/gtests/google_test/gtest/test/gtest_prod_test.cc b/security/nss/gtests/google_test/gtest/test/gtest_prod_test.cc index 060abce18..ede81a0d1 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_prod_test.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest_prod_test.cc @@ -26,13 +26,12 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + // -// Author: wan@google.com (Zhanyong Wan) -// -// Unit test for include/gtest/gtest_prod.h. +// Unit test for gtest_prod.h. +#include "production.h" #include "gtest/gtest.h" -#include "test/production.h" // Tests that private members can be accessed from a TEST declared as // a friend of the class. diff --git a/security/nss/gtests/google_test/gtest/test/gtest_repeat_test.cc b/security/nss/gtests/google_test/gtest/test/gtest_repeat_test.cc index 481012adc..1e8f499bb 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_repeat_test.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest_repeat_test.cc @@ -26,23 +26,14 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests the --gtest_repeat=number flag. #include <stdlib.h> #include <iostream> #include "gtest/gtest.h" - -// Indicates that this translation unit is part of Google Test's -// implementation. It must come before gtest-internal-inl.h is -// included, or there will be a compiler error. This trick is to -// prevent a user from accidentally including gtest-internal-inl.h in -// his code. -#define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" -#undef GTEST_IMPLEMENTATION_ namespace testing { @@ -75,7 +66,7 @@ namespace { // Used for verifying that global environment set-up and tear-down are -// inside the gtest_repeat loop. +// inside the --gtest_repeat loop. int g_environment_set_up_count = 0; int g_environment_tear_down_count = 0; @@ -119,7 +110,6 @@ TEST(BarDeathTest, ThreadSafeAndFast) { EXPECT_DEATH_IF_SUPPORTED(::testing::internal::posix::Abort(), ""); } -#if GTEST_HAS_PARAM_TEST int g_param_test_count = 0; const int kNumberOfParamTests = 10; @@ -127,15 +117,13 @@ const int kNumberOfParamTests = 10; class MyParamTest : public testing::TestWithParam<int> {}; TEST_P(MyParamTest, ShouldPass) { - // TODO(vladl@google.com): Make parameter value checking robust - // WRT order of tests. + // FIXME: Make parameter value checking robust WRT order of tests. GTEST_CHECK_INT_EQ_(g_param_test_count % kNumberOfParamTests, GetParam()); g_param_test_count++; } INSTANTIATE_TEST_CASE_P(MyParamSequence, MyParamTest, testing::Range(0, kNumberOfParamTests)); -#endif // GTEST_HAS_PARAM_TEST // Resets the count for each test. void ResetCounts() { @@ -144,9 +132,7 @@ void ResetCounts() { g_should_fail_count = 0; g_should_pass_count = 0; g_death_test_count = 0; -#if GTEST_HAS_PARAM_TEST g_param_test_count = 0; -#endif // GTEST_HAS_PARAM_TEST } // Checks that the count for each test is expected. @@ -156,9 +142,7 @@ void CheckCounts(int expected) { GTEST_CHECK_INT_EQ_(expected, g_should_fail_count); GTEST_CHECK_INT_EQ_(expected, g_should_pass_count); GTEST_CHECK_INT_EQ_(expected, g_death_test_count); -#if GTEST_HAS_PARAM_TEST GTEST_CHECK_INT_EQ_(expected * kNumberOfParamTests, g_param_test_count); -#endif // GTEST_HAS_PARAM_TEST } // Tests the behavior of Google Test when --gtest_repeat is not specified. @@ -201,9 +185,7 @@ void TestRepeatWithFilterForSuccessfulTests(int repeat) { GTEST_CHECK_INT_EQ_(0, g_should_fail_count); GTEST_CHECK_INT_EQ_(repeat, g_should_pass_count); GTEST_CHECK_INT_EQ_(repeat, g_death_test_count); -#if GTEST_HAS_PARAM_TEST GTEST_CHECK_INT_EQ_(repeat * kNumberOfParamTests, g_param_test_count); -#endif // GTEST_HAS_PARAM_TEST } // Tests using --gtest_repeat when --gtest_filter specifies a set of @@ -219,15 +201,14 @@ void TestRepeatWithFilterForFailedTests(int repeat) { GTEST_CHECK_INT_EQ_(repeat, g_should_fail_count); GTEST_CHECK_INT_EQ_(0, g_should_pass_count); GTEST_CHECK_INT_EQ_(0, g_death_test_count); -#if GTEST_HAS_PARAM_TEST GTEST_CHECK_INT_EQ_(0, g_param_test_count); -#endif // GTEST_HAS_PARAM_TEST } } // namespace int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); + testing::AddGlobalTestEnvironment(new MyEnvironment); TestRepeatUnspecified(); diff --git a/security/nss/gtests/google_test/gtest/test/gtest_sole_header_test.cc b/security/nss/gtests/google_test/gtest/test/gtest_sole_header_test.cc index ccd091a28..1d94ac6b3 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_sole_header_test.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest_sole_header_test.cc @@ -26,8 +26,7 @@ // 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) + // // This test verifies that it's possible to use Google Test by including // the gtest.h header file alone. diff --git a/security/nss/gtests/google_test/gtest/test/gtest_stress_test.cc b/security/nss/gtests/google_test/gtest/test/gtest_stress_test.cc index e7daa430d..95ada39c3 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_stress_test.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest_stress_test.cc @@ -26,23 +26,16 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests that SCOPED_TRACE() and various Google Test assertions can be // used in a large number of threads concurrently. #include "gtest/gtest.h" -#include <iostream> #include <vector> -// We must define this macro in order to #include -// gtest-internal-inl.h. This is how Google Test prevents a user from -// accidentally depending on its internal implementation. -#define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" -#undef GTEST_IMPLEMENTATION_ #if GTEST_IS_THREADSAFE diff --git a/security/nss/gtests/google_test/gtest/test/gtest_test_macro_stack_footprint_test.cc b/security/nss/gtests/google_test/gtest/test/gtest_test_macro_stack_footprint_test.cc new file mode 100644 index 000000000..a48db0501 --- /dev/null +++ b/security/nss/gtests/google_test/gtest/test/gtest_test_macro_stack_footprint_test.cc @@ -0,0 +1,89 @@ +// Copyright 2013, 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. + +// +// Each TEST() expands to some static registration logic. GCC puts all +// such static initialization logic for a translation unit in a common, +// internal function. Since Google's build system restricts how much +// stack space a function can use, there's a limit on how many TEST()s +// one can put in a single C++ test file. This test ensures that a large +// number of TEST()s can be defined in the same translation unit. + +#include "gtest/gtest.h" + +// This macro defines 10 dummy tests. +#define TEN_TESTS_(test_case_name) \ + TEST(test_case_name, T0) {} \ + TEST(test_case_name, T1) {} \ + TEST(test_case_name, T2) {} \ + TEST(test_case_name, T3) {} \ + TEST(test_case_name, T4) {} \ + TEST(test_case_name, T5) {} \ + TEST(test_case_name, T6) {} \ + TEST(test_case_name, T7) {} \ + TEST(test_case_name, T8) {} \ + TEST(test_case_name, T9) {} + +// This macro defines 100 dummy tests. +#define HUNDRED_TESTS_(test_case_name_prefix) \ + TEN_TESTS_(test_case_name_prefix ## 0) \ + TEN_TESTS_(test_case_name_prefix ## 1) \ + TEN_TESTS_(test_case_name_prefix ## 2) \ + TEN_TESTS_(test_case_name_prefix ## 3) \ + TEN_TESTS_(test_case_name_prefix ## 4) \ + TEN_TESTS_(test_case_name_prefix ## 5) \ + TEN_TESTS_(test_case_name_prefix ## 6) \ + TEN_TESTS_(test_case_name_prefix ## 7) \ + TEN_TESTS_(test_case_name_prefix ## 8) \ + TEN_TESTS_(test_case_name_prefix ## 9) + +// This macro defines 1000 dummy tests. +#define THOUSAND_TESTS_(test_case_name_prefix) \ + HUNDRED_TESTS_(test_case_name_prefix ## 0) \ + HUNDRED_TESTS_(test_case_name_prefix ## 1) \ + HUNDRED_TESTS_(test_case_name_prefix ## 2) \ + HUNDRED_TESTS_(test_case_name_prefix ## 3) \ + HUNDRED_TESTS_(test_case_name_prefix ## 4) \ + HUNDRED_TESTS_(test_case_name_prefix ## 5) \ + HUNDRED_TESTS_(test_case_name_prefix ## 6) \ + HUNDRED_TESTS_(test_case_name_prefix ## 7) \ + HUNDRED_TESTS_(test_case_name_prefix ## 8) \ + HUNDRED_TESTS_(test_case_name_prefix ## 9) + +// Ensures that we can define 1000 TEST()s in the same translation +// unit. +THOUSAND_TESTS_(T) + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + + // We don't actually need to run the dummy tests - the purpose is to + // ensure that they compile. + return 0; +} diff --git a/security/nss/gtests/google_test/gtest/test/gtest_test_utils.py b/security/nss/gtests/google_test/gtest/test/gtest_test_utils.py index 7e3cbcafd..43cba8f4c 100755 --- a/security/nss/gtests/google_test/gtest/test/gtest_test_utils.py +++ b/security/nss/gtests/google_test/gtest/test/gtest_test_utils.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python -# # Copyright 2006, Google Inc. # All rights reserved. # @@ -29,20 +27,21 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -"""Unit test utilities for Google C++ Testing Framework.""" +"""Unit test utilities for Google C++ Testing and Mocking Framework.""" +# Suppresses the 'Import not at the top of the file' lint complaint. +# pylint: disable-msg=C6204 + +import os +import sys -__author__ = 'wan@google.com (Zhanyong Wan)' +IS_WINDOWS = os.name == 'nt' +IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0] import atexit -import os import shutil -import sys import tempfile -import unittest -_test_module = unittest +import unittest as _test_module -# Suppresses the 'Import not at the top of the file' lint complaint. -# pylint: disable-msg=C6204 try: import subprocess _SUBPROCESS_MODULE_AVAILABLE = True @@ -53,9 +52,6 @@ except: GTEST_OUTPUT_VAR_NAME = 'GTEST_OUTPUT' -IS_WINDOWS = os.name == 'nt' -IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0] - # The environment variable for specifying the path to the premature-exit file. PREMATURE_EXIT_FILE_ENV_VAR = 'TEST_PREMATURE_EXIT_FILE' @@ -74,7 +70,7 @@ def SetEnvVar(env_var, value): # Here we expose a class from a particular module, depending on the # environment. The comment suppresses the 'Invalid variable name' lint # complaint. -TestCase = _test_module.TestCase # pylint: disable-msg=C6409 +TestCase = _test_module.TestCase # pylint: disable=C6409 # Initially maps a flag to its default value. After # _ParseAndStripGTestFlags() is called, maps a flag to its actual value. @@ -88,7 +84,7 @@ def _ParseAndStripGTestFlags(argv): # Suppresses the lint complaint about a global variable since we need it # here to maintain module-wide state. - global _gtest_flags_are_parsed # pylint: disable-msg=W0603 + global _gtest_flags_are_parsed # pylint: disable=W0603 if _gtest_flags_are_parsed: return @@ -145,8 +141,6 @@ atexit.register(_RemoveTempDir) def GetTempDir(): - """Returns a directory for temporary files.""" - global _temp_dir if not _temp_dir: _temp_dir = tempfile.mkdtemp() @@ -245,7 +239,7 @@ class Subprocess: p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=stderr, cwd=working_dir, universal_newlines=True, env=env) - # communicate returns a tuple with the file obect for the child's + # communicate returns a tuple with the file object for the child's # output. self.output = p.communicate()[0] self._return_code = p.returncode @@ -312,7 +306,7 @@ def Main(): _ParseAndStripGTestFlags(sys.argv) # The tested binaries should not be writing XML output files unless the # script explicitly instructs them to. - # TODO(vladl@google.com): Move this into Subprocess when we implement + # FIXME: Move this into Subprocess when we implement # passing environment into it as a parameter. if GTEST_OUTPUT_VAR_NAME in os.environ: del os.environ[GTEST_OUTPUT_VAR_NAME] diff --git a/security/nss/gtests/google_test/gtest/test/gtest_testbridge_test.py b/security/nss/gtests/google_test/gtest/test/gtest_testbridge_test.py new file mode 100644 index 000000000..87ffad73d --- /dev/null +++ b/security/nss/gtests/google_test/gtest/test/gtest_testbridge_test.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC. 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 uses filter provided via testbridge.""" + +import os + +import gtest_test_utils + +binary_name = 'gtest_testbridge_test_' +COMMAND = gtest_test_utils.GetTestExecutablePath(binary_name) +TESTBRIDGE_NAME = 'TESTBRIDGE_TEST_ONLY' + + +def Assert(condition): + if not condition: + raise AssertionError + + +class GTestTestFilterTest(gtest_test_utils.TestCase): + + def testTestExecutionIsFiltered(self): + """Tests that the test filter is picked up from the testbridge env var.""" + subprocess_env = os.environ.copy() + + subprocess_env[TESTBRIDGE_NAME] = '*.TestThatSucceeds' + p = gtest_test_utils.Subprocess(COMMAND, env=subprocess_env) + + self.assertEquals(0, p.exit_code) + + Assert('filter = *.TestThatSucceeds' in p.output) + Assert('[ OK ] TestFilterTest.TestThatSucceeds' in p.output) + Assert('[ PASSED ] 1 test.' in p.output) + + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/security/nss/gtests/google_test/gtest/test/gtest_testbridge_test_.cc b/security/nss/gtests/google_test/gtest/test/gtest_testbridge_test_.cc new file mode 100644 index 000000000..24617b209 --- /dev/null +++ b/security/nss/gtests/google_test/gtest/test/gtest_testbridge_test_.cc @@ -0,0 +1,43 @@ +// Copyright 2018, Google LLC. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +// This program is meant to be run by gtest_test_filter_test.py. Do not run +// it directly. + +#include "gtest/gtest.h" + +// These tests are used to detect if filtering is working. Only +// 'TestThatSucceeds' should ever run. + +TEST(TestFilterTest, TestThatSucceeds) {} + +TEST(TestFilterTest, TestThatFails) { + ASSERT_TRUE(false) << "This test should never be run."; +} diff --git a/security/nss/gtests/google_test/gtest/test/gtest_throw_on_failure_ex_test.cc b/security/nss/gtests/google_test/gtest/test/gtest_throw_on_failure_ex_test.cc index 8d46c76f1..93f59d49c 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_throw_on_failure_ex_test.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest_throw_on_failure_ex_test.cc @@ -26,8 +26,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // Tests Google Test's throw-on-failure mode with exceptions enabled. diff --git a/security/nss/gtests/google_test/gtest/test/gtest_unittest.cc b/security/nss/gtests/google_test/gtest/test/gtest_unittest.cc index 9625fa4e8..f7213fbf3 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_unittest.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest_unittest.cc @@ -26,17 +26,16 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: wan@google.com (Zhanyong Wan) + // // Tests for Google Test itself. This verifies that the basic constructs of // Google Test work. #include "gtest/gtest.h" -// Verifies that the command line flag variables can be accessed -// in code once <gtest/gtest.h> has been #included. -// Do not move it after other #includes. +// Verifies that the command line flag variables can be accessed in +// code once "gtest.h" has been #included. +// Do not move it after other gtest #includes. TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { bool dummy = testing::GTEST_FLAG(also_run_disabled_tests) || testing::GTEST_FLAG(break_on_failure) @@ -64,17 +63,12 @@ TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { #include <map> #include <vector> #include <ostream> +#if GTEST_LANG_CXX11 +#include <unordered_set> +#endif // GTEST_LANG_CXX11 #include "gtest/gtest-spi.h" - -// Indicates that this translation unit is part of Google Test's -// implementation. It must come before gtest-internal-inl.h is -// included, or there will be a compiler error. This trick is to -// prevent a user from accidentally including gtest-internal-inl.h in -// his code. -#define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" -#undef GTEST_IMPLEMENTATION_ namespace testing { namespace internal { @@ -86,18 +80,19 @@ class StreamingListenerTest : public Test { class FakeSocketWriter : public StreamingListener::AbstractSocketWriter { public: // Sends a string to the socket. - virtual void Send(const string& message) { output_ += message; } + virtual void Send(const std::string& message) { output_ += message; } - string output_; + std::string output_; }; StreamingListenerTest() : fake_sock_writer_(new FakeSocketWriter), streamer_(fake_sock_writer_), - test_info_obj_("FooTest", "Bar", NULL, NULL, 0, NULL) {} + test_info_obj_("FooTest", "Bar", NULL, NULL, + CodeLocation(__FILE__, __LINE__), 0, NULL) {} protected: - string* output() { return &(fake_sock_writer_->output_); } + std::string* output() { return &(fake_sock_writer_->output_); } FakeSocketWriter* const fake_sock_writer_; StreamingListener streamer_; @@ -265,6 +260,8 @@ using testing::internal::IsContainer; using testing::internal::IsContainerTest; using testing::internal::IsNotContainer; using testing::internal::NativeArray; +using testing::internal::OsStackTraceGetter; +using testing::internal::OsStackTraceGetterInterface; using testing::internal::ParseInt32Flag; using testing::internal::RelationToSourceCopy; using testing::internal::RelationToSourceReference; @@ -281,13 +278,13 @@ using testing::internal::String; using testing::internal::TestEventListenersAccessor; using testing::internal::TestResultAccessor; using testing::internal::UInt32; +using testing::internal::UnitTestImpl; using testing::internal::WideStringToUtf8; using testing::internal::edit_distance::CalculateOptimalEdits; using testing::internal::edit_distance::CreateUnifiedDiff; using testing::internal::edit_distance::EditType; using testing::internal::kMaxRandomSeed; using testing::internal::kTestTypeIdInGoogleTest; -using testing::internal::scoped_ptr; using testing::kMaxStackTraceDepth; #if GTEST_HAS_STREAM_REDIRECTION @@ -382,6 +379,31 @@ TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) { EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId()); } +// Tests CanonicalizeForStdLibVersioning. + +using ::testing::internal::CanonicalizeForStdLibVersioning; + +TEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) { + EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::bind")); + EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::_")); + EXPECT_EQ("std::__foo", CanonicalizeForStdLibVersioning("std::__foo")); + EXPECT_EQ("gtl::__1::x", CanonicalizeForStdLibVersioning("gtl::__1::x")); + EXPECT_EQ("__1::x", CanonicalizeForStdLibVersioning("__1::x")); + EXPECT_EQ("::__1::x", CanonicalizeForStdLibVersioning("::__1::x")); +} + +TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) { + EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__1::bind")); + EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__1::_")); + + EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__g::bind")); + EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__g::_")); + + EXPECT_EQ("std::bind", + CanonicalizeForStdLibVersioning("std::__google::bind")); + EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_")); +} + // Tests FormatTimeInMillisAsSeconds(). TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) { @@ -421,10 +443,10 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test { virtual void SetUp() { saved_tz_ = NULL; - GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* PR_GetEnvSecure, strdup: deprecated */) - if (PR_GetEnvSecure("TZ")) - saved_tz_ = strdup(PR_GetEnvSecure("TZ")); - GTEST_DISABLE_MSC_WARNINGS_POP_() + GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */) + if (getenv("TZ")) + saved_tz_ = strdup(getenv("TZ")); + GTEST_DISABLE_MSC_DEPRECATED_POP_() // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We // cannot use the local time zone because the function's output depends @@ -442,7 +464,7 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test { // tzset() distinguishes between the TZ variable being present and empty // and not being present, so we have to consider the case of time_zone // being NULL. -#if _MSC_VER +#if _MSC_VER || GTEST_OS_WINDOWS_MINGW // ...Unless it's MSVC, whose standard library's _putenv doesn't // distinguish between an empty and a missing variable. const std::string env_var = @@ -546,7 +568,7 @@ TEST(CodePointToUtf8Test, CanEncode8To11Bits) { // 101 0111 0110 => 110-10101 10-110110 // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints - // in wide strings and wide chars. In order to accomodate them, we have to + // in wide strings and wide chars. In order to accommodate them, we have to // introduce such character constants as integers. EXPECT_EQ("\xD5\xB6", CodePointToUtf8(static_cast<wchar_t>(0x576))); @@ -1362,8 +1384,7 @@ class TestResultTest : public Test { // In order to test TestResult, we need to modify its internal // state, in particular the TestPartResult vector it holds. // test_part_results() returns a const reference to this vector. - // We cast it to a non-const object s.t. it can be modified (yes, - // this is a hack). + // We cast it to a non-const object s.t. it can be modified TPRVector* results1 = const_cast<TPRVector*>( &TestResultAccessor::test_part_results(*r1)); TPRVector* results2 = const_cast<TPRVector*>( @@ -1388,7 +1409,7 @@ class TestResultTest : public Test { delete r2; } - // Helper that compares two two TestPartResults. + // Helper that compares two TestPartResults. static void CompareTestPartResult(const TestPartResult& expected, const TestPartResult& actual) { EXPECT_EQ(expected.type(), actual.type()); @@ -1518,6 +1539,16 @@ TEST(TestResultPropertyTest, GetTestProperty) { EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), ""); } +// Tests the Test class. +// +// It's difficult to test every public method of this class (we are +// already stretching the limit of Google Test by using it to test itself!). +// Fortunately, we don't have to do that, as we are already testing +// the functionalities of the Test class extensively by using Google Test +// alone. +// +// Therefore, this section only contains one test. + // Tests that GTestFlagSaver works on Windows and Mac. class GTestFlagSaverTest : public Test { @@ -1661,6 +1692,8 @@ TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) { EXPECT_EQ(10, Int32FromGTestEnv("temp", 10)); } +# if !defined(GTEST_GET_INT32_FROM_ENV_) + // Tests that Int32FromGTestEnv() returns the default value when the // environment variable overflows as an Int32. TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) { @@ -1685,6 +1718,8 @@ TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) { EXPECT_EQ(50, Int32FromGTestEnv("temp", 50)); } +# endif // !defined(GTEST_GET_INT32_FROM_ENV_) + // Tests that Int32FromGTestEnv() parses and returns the value of the // environment variable when it represents a valid decimal integer in // the range of an Int32. @@ -1773,7 +1808,7 @@ TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) { } // Tests that Int32FromEnvOrDie() aborts with an error message -// if the variable cannot be represnted by an Int32. +// if the variable cannot be represented by an Int32. TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234"); EXPECT_DEATH_IF_SUPPORTED( @@ -2055,8 +2090,8 @@ TEST_F(UnitTestRecordPropertyTest, AddRecordWithReservedKeysGeneratesCorrectPropertyList) { EXPECT_NONFATAL_FAILURE( Test::RecordProperty("name", "1"), - "'classname', 'name', 'status', 'time', 'type_param', and 'value_param'" - " are reserved"); + "'classname', 'name', 'status', 'time', 'type_param', 'value_param'," + " 'file', and 'line' are reserved"); } class UnitTestRecordPropertyTestEnvironment : public Environment { @@ -2416,7 +2451,7 @@ TEST(StringAssertionTest, ASSERT_STREQ) { ASSERT_STREQ(p1, p2); EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"), - "Expected: \"bad\""); + " \"bad\"\n \"good\""); } // Tests ASSERT_STREQ with NULL arguments. @@ -2452,7 +2487,7 @@ TEST(StringAssertionTest, ASSERT_STRCASEEQ) { ASSERT_STRCASEEQ("", ""); EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"), - "(ignoring case)"); + "Ignoring case"); } // Tests ASSERT_STRCASENE. @@ -3101,13 +3136,13 @@ TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) { FAIL() << "Unexpected failure: Test in disabled test case should not be run."; } -// Check that when all tests in a test case are disabled, SetupTestCase() and +// Check that when all tests in a test case are disabled, SetUpTestCase() and // TearDownTestCase() are not called. class DisabledTestsTest : public Test { protected: static void SetUpTestCase() { FAIL() << "Unexpected failure: All tests disabled in test case. " - "SetupTestCase() should not be called."; + "SetUpTestCase() should not be called."; } static void TearDownTestCase() { @@ -3246,7 +3281,7 @@ TEST_F(SingleEvaluationTest, ASSERT_STR) { // failed EXPECT_STRCASEEQ EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++), - "ignoring case"); + "Ignoring case"); EXPECT_EQ(s1_ + 2, p1_); EXPECT_EQ(s2_ + 2, p2_); } @@ -3354,7 +3389,7 @@ class NoFatalFailureTest : public Test { void DoAssertNoFatalFailureOnFails() { ASSERT_NO_FATAL_FAILURE(Fails()); - ADD_FAILURE() << "shold not reach here."; + ADD_FAILURE() << "should not reach here."; } void DoExpectNoFatalFailureOnFails() { @@ -3514,35 +3549,39 @@ TEST(AssertionTest, EqFailure) { EqFailure("foo", "bar", foo_val, bar_val, false) .failure_message()); EXPECT_STREQ( - "Value of: bar\n" - " Actual: 6\n" - "Expected: foo\n" - "Which is: 5", + "Expected equality of these values:\n" + " foo\n" + " Which is: 5\n" + " bar\n" + " Which is: 6", msg1.c_str()); const std::string msg2( EqFailure("foo", "6", foo_val, bar_val, false) .failure_message()); EXPECT_STREQ( - "Value of: 6\n" - "Expected: foo\n" - "Which is: 5", + "Expected equality of these values:\n" + " foo\n" + " Which is: 5\n" + " 6", msg2.c_str()); const std::string msg3( EqFailure("5", "bar", foo_val, bar_val, false) .failure_message()); EXPECT_STREQ( - "Value of: bar\n" - " Actual: 6\n" - "Expected: 5", + "Expected equality of these values:\n" + " 5\n" + " bar\n" + " Which is: 6", msg3.c_str()); const std::string msg4( EqFailure("5", "6", foo_val, bar_val, false).failure_message()); EXPECT_STREQ( - "Value of: 6\n" - "Expected: 5", + "Expected equality of these values:\n" + " 5\n" + " 6", msg4.c_str()); const std::string msg5( @@ -3550,10 +3589,12 @@ TEST(AssertionTest, EqFailure) { std::string("\"x\""), std::string("\"y\""), true).failure_message()); EXPECT_STREQ( - "Value of: bar\n" - " Actual: \"y\"\n" - "Expected: foo (ignoring case)\n" - "Which is: \"x\"", + "Expected equality of these values:\n" + " foo\n" + " Which is: \"x\"\n" + " bar\n" + " Which is: \"y\"\n" + "Ignoring case", msg5.c_str()); } @@ -3565,11 +3606,12 @@ TEST(AssertionTest, EqFailureWithDiff) { const std::string msg1( EqFailure("left", "right", left, right, false).failure_message()); EXPECT_STREQ( - "Value of: right\n" - " Actual: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n" - "Expected: left\n" - "Which is: " + "Expected equality of these values:\n" + " left\n" + " Which is: " "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n" + " right\n" + " Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n" "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n" "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n", msg1.c_str()); @@ -3644,7 +3686,7 @@ TEST(AssertionTest, AssertFalseWithAssertionResult) { } #ifdef __BORLANDC__ -// Restores warnings after previous "#pragma option push" supressed them +// Restores warnings after previous "#pragma option push" suppressed them # pragma option pop #endif @@ -3664,9 +3706,10 @@ TEST(ExpectTest, ASSERT_EQ_Double) { TEST(AssertionTest, ASSERT_EQ) { ASSERT_EQ(5, 2 + 3); EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3), - "Value of: 2*3\n" - " Actual: 6\n" - "Expected: 5"); + "Expected equality of these values:\n" + " 5\n" + " 2*3\n" + " Which is: 6"); } // Tests ASSERT_EQ(NULL, pointer). @@ -3674,7 +3717,7 @@ TEST(AssertionTest, ASSERT_EQ) { TEST(AssertionTest, ASSERT_EQ_NULL) { // A success. const char* p = NULL; - // Some older GCC versions may issue a spurious waring in this or the next + // Some older GCC versions may issue a spurious warning in this or the next // assertion statement. This warning should not be suppressed with // static_cast since the test verifies the ability to use bare NULL as the // expected parameter to the macro. @@ -3683,7 +3726,7 @@ TEST(AssertionTest, ASSERT_EQ_NULL) { // A failure. static int n = 0; EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n), - "Value of: &n\n"); + " &n\n Which is:"); } #endif // GTEST_CAN_COMPARE_NULL @@ -3699,7 +3742,7 @@ TEST(ExpectTest, ASSERT_EQ_0) { // A failure. EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6), - "Expected: 0"); + " 0\n 5.6"); } // Tests ASSERT_NE. @@ -3798,7 +3841,7 @@ void TestEq1(int x) { // Tests calling a test subroutine that's not part of a fixture. TEST(AssertionTest, NonFixtureSubroutine) { EXPECT_FATAL_FAILURE(TestEq1(2), - "Value of: x"); + " x\n Which is: 2"); } // An uncopyable class. @@ -3847,7 +3890,8 @@ TEST(AssertionTest, AssertWorksWithUncopyableObject) { EXPECT_FATAL_FAILURE(TestAssertNonPositive(), "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(), - "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5"); + "Expected equality of these values:\n" + " x\n Which is: 5\n y\n Which is: -1"); } // Tests that uncopyable objects can be used in expects. @@ -3859,7 +3903,8 @@ TEST(AssertionTest, ExpectWorksWithUncopyableObject) { "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); EXPECT_EQ(x, x); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), - "Value of: y\n Actual: -1\nExpected: x\nWhich is: 5"); + "Expected equality of these values:\n" + " x\n Which is: 5\n y\n Which is: -1"); } enum NamedEnum { @@ -3871,7 +3916,7 @@ TEST(AssertionTest, NamedEnum) { EXPECT_EQ(kE1, kE1); EXPECT_LT(kE1, kE2); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0"); - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Actual: 1"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1"); } // The version of gcc used in XCode 2.2 has a bug and doesn't allow @@ -3935,13 +3980,13 @@ TEST(AssertionTest, AnonymousEnum) { // ICE's in C++Builder. EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), - "Value of: kCaseB"); + " kCaseB\n Which is: "); EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), - "Actual: 42"); + "\n Which is: 42"); # endif EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), - "Which is: -1"); + "\n Which is: -1"); } #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC) @@ -4367,7 +4412,7 @@ TEST(ExpectTest, ExpectFalseWithAssertionResult) { } #ifdef __BORLANDC__ -// Restores warnings after previous "#pragma option push" supressed them +// Restores warnings after previous "#pragma option push" suppressed them # pragma option pop #endif @@ -4375,9 +4420,10 @@ TEST(ExpectTest, ExpectFalseWithAssertionResult) { TEST(ExpectTest, EXPECT_EQ) { EXPECT_EQ(5, 2 + 3); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3), - "Value of: 2*3\n" - " Actual: 6\n" - "Expected: 5"); + "Expected equality of these values:\n" + " 5\n" + " 2*3\n" + " Which is: 6"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3), "2 - 3"); } @@ -4408,7 +4454,7 @@ TEST(ExpectTest, EXPECT_EQ_NULL) { // A failure. int n = 0; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n), - "Value of: &n\n"); + " &n\n Which is:"); } #endif // GTEST_CAN_COMPARE_NULL @@ -4424,7 +4470,7 @@ TEST(ExpectTest, EXPECT_EQ_0) { // A failure. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6), - "Expected: 0"); + " 0\n 5.6"); } // Tests EXPECT_NE. @@ -4524,7 +4570,7 @@ TEST(ExpectTest, EXPECT_ANY_THROW) { TEST(ExpectTest, ExpectPrecedence) { EXPECT_EQ(1 < 2, true); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false), - "Value of: true && false"); + " true && false\n Which is: false"); } @@ -4641,7 +4687,7 @@ TEST(MacroTest, ADD_FAILURE_AT) { // Unfortunately, we cannot verify that the failure message contains // the right file path and line number the same way, as // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and - // line number. Instead, we do that in gtest_output_test_.cc. + // line number. Instead, we do that in googletest-output-test_.cc. } // Tests FAIL. @@ -4671,14 +4717,14 @@ TEST(EqAssertionTest, Bool) { EXPECT_FATAL_FAILURE({ bool false_value = false; ASSERT_EQ(false_value, true); - }, "Value of: true"); + }, " false_value\n Which is: false\n true"); } // Tests using int values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, Int) { ASSERT_EQ(32, 32); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33), - "33"); + " 32\n 33"); } // Tests using time_t values in {EXPECT|ASSERT}_EQ. @@ -4695,9 +4741,9 @@ TEST(EqAssertionTest, Char) { ASSERT_EQ('z', 'z'); const char ch = 'b'; EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch), - "ch"); + " ch\n Which is: 'b'"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch), - "ch"); + " ch\n Which is: 'b'"); } // Tests using wchar_t values in {EXPECT|ASSERT}_EQ. @@ -4705,10 +4751,11 @@ TEST(EqAssertionTest, WideChar) { EXPECT_EQ(L'b', L'b'); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'), - "Value of: L'x'\n" - " Actual: L'x' (120, 0x78)\n" - "Expected: L'\0'\n" - "Which is: L'\0' (0, 0x0)"); + "Expected equality of these values:\n" + " L'\0'\n" + " Which is: L'\0' (0, 0x0)\n" + " L'x'\n" + " Which is: L'x' (120, 0x78)"); static wchar_t wchar; wchar = L'b'; @@ -4716,7 +4763,7 @@ TEST(EqAssertionTest, WideChar) { "wchar"); wchar = 0x8119; EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar), - "Value of: wchar"); + " wchar\n Which is: L'"); } // Tests using ::std::string values in {EXPECT|ASSERT}_EQ. @@ -4745,8 +4792,7 @@ TEST(EqAssertionTest, StdString) { static ::std::string str3(str1); str3.at(2) = '\0'; EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3), - "Value of: str3\n" - " Actual: \"A \\0 in the middle\""); + " str3\n Which is: \"A \\0 in the middle\""); } #if GTEST_HAS_STD_WSTRING @@ -4866,9 +4912,9 @@ TEST(EqAssertionTest, CharPointer) { ASSERT_EQ(p1, p1); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), - "Value of: p2"); + " p2\n Which is:"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), - "p2"); + " p2\n Which is:"); EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234), reinterpret_cast<char*>(0xABC0)), "ABC0"); @@ -4888,9 +4934,9 @@ TEST(EqAssertionTest, WideCharPointer) { EXPECT_EQ(p0, p0); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), - "Value of: p2"); + " p2\n Which is:"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), - "p2"); + " p2\n Which is:"); void* pv3 = (void*)0x1234; // NOLINT void* pv4 = (void*)0xABC0; // NOLINT const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3); @@ -5319,6 +5365,59 @@ TEST_F(TestInfoTest, result) { ASSERT_EQ(0, GetTestResult(test_info)->total_part_count()); } +#define VERIFY_CODE_LOCATION \ + const int expected_line = __LINE__ - 1; \ + const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \ + ASSERT_TRUE(test_info); \ + EXPECT_STREQ(__FILE__, test_info->file()); \ + EXPECT_EQ(expected_line, test_info->line()) + +TEST(CodeLocationForTEST, Verify) { + VERIFY_CODE_LOCATION; +} + +class CodeLocationForTESTF : public Test { +}; + +TEST_F(CodeLocationForTESTF, Verify) { + VERIFY_CODE_LOCATION; +} + +class CodeLocationForTESTP : public TestWithParam<int> { +}; + +TEST_P(CodeLocationForTESTP, Verify) { + VERIFY_CODE_LOCATION; +} + +INSTANTIATE_TEST_CASE_P(, CodeLocationForTESTP, Values(0)); + +template <typename T> +class CodeLocationForTYPEDTEST : public Test { +}; + +TYPED_TEST_CASE(CodeLocationForTYPEDTEST, int); + +TYPED_TEST(CodeLocationForTYPEDTEST, Verify) { + VERIFY_CODE_LOCATION; +} + +template <typename T> +class CodeLocationForTYPEDTESTP : public Test { +}; + +TYPED_TEST_CASE_P(CodeLocationForTYPEDTESTP); + +TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) { + VERIFY_CODE_LOCATION; +} + +REGISTER_TYPED_TEST_CASE_P(CodeLocationForTYPEDTESTP, Verify); + +INSTANTIATE_TYPED_TEST_CASE_P(My, CodeLocationForTYPEDTESTP, int); + +#undef VERIFY_CODE_LOCATION + // Tests setting up and tearing down a test case. class SetUpTestCaseTest : public Test { @@ -5382,7 +5481,8 @@ TEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ("123", shared_resource_); } -// The InitGoogleTestTest test case tests testing::InitGoogleTest(). + +// The ParseFlagsTest test case tests ParseGoogleTestFlagsOnly. // The Flags struct stores a copy of all Google Test flags. struct Flags { @@ -5468,8 +5568,8 @@ struct Flags { return flags; } - // Creates a Flags struct where the gtest_random_seed flag has - // the given value. + // Creates a Flags struct where the gtest_random_seed flag has the given + // value. static Flags RandomSeed(Int32 random_seed) { Flags flags; flags.random_seed = random_seed; @@ -5484,8 +5584,8 @@ struct Flags { return flags; } - // Creates a Flags struct where the gtest_shuffle flag has - // the given value. + // Creates a Flags struct where the gtest_shuffle flag has the given + // value. static Flags Shuffle(bool shuffle) { Flags flags; flags.shuffle = shuffle; @@ -5533,8 +5633,8 @@ struct Flags { bool throw_on_failure; }; -// Fixture for testing InitGoogleTest(). -class InitGoogleTestTest : public Test { +// Fixture for testing ParseGoogleTestFlagsOnly(). +class ParseFlagsTest : public Test { protected: // Clears the flags before each test. virtual void SetUp() { @@ -5595,16 +5695,16 @@ class InitGoogleTestTest : public Test { const bool saved_help_flag = ::testing::internal::g_help_flag; ::testing::internal::g_help_flag = false; -#if GTEST_HAS_STREAM_REDIRECTION +# if GTEST_HAS_STREAM_REDIRECTION CaptureStdout(); -#endif +# endif // Parses the command line. internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1)); -#if GTEST_HAS_STREAM_REDIRECTION +# if GTEST_HAS_STREAM_REDIRECTION const std::string captured_stdout = GetCapturedStdout(); -#endif +# endif // Verifies the flag values. CheckFlags(expected); @@ -5617,7 +5717,7 @@ class InitGoogleTestTest : public Test { // help message for the flags it recognizes. EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag); -#if GTEST_HAS_STREAM_REDIRECTION +# if GTEST_HAS_STREAM_REDIRECTION const char* const expected_help_fragment = "This program contains tests written using"; if (should_print_help) { @@ -5626,7 +5726,7 @@ class InitGoogleTestTest : public Test { EXPECT_PRED_FORMAT2(IsNotSubstring, expected_help_fragment, captured_stdout); } -#endif // GTEST_HAS_STREAM_REDIRECTION +# endif // GTEST_HAS_STREAM_REDIRECTION ::testing::internal::g_help_flag = saved_help_flag; } @@ -5634,14 +5734,14 @@ class InitGoogleTestTest : public Test { // This macro wraps TestParsingFlags s.t. the user doesn't need // to specify the array sizes. -#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \ +# define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \ TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \ sizeof(argv2)/sizeof(*argv2) - 1, argv2, \ expected, should_print_help) }; // Tests parsing an empty command line. -TEST_F(InitGoogleTestTest, Empty) { +TEST_F(ParseFlagsTest, Empty) { const char* argv[] = { NULL }; @@ -5654,7 +5754,7 @@ TEST_F(InitGoogleTestTest, Empty) { } // Tests parsing a command line that has no flag. -TEST_F(InitGoogleTestTest, NoFlag) { +TEST_F(ParseFlagsTest, NoFlag) { const char* argv[] = { "foo.exe", NULL @@ -5669,7 +5769,7 @@ TEST_F(InitGoogleTestTest, NoFlag) { } // Tests parsing a bad --gtest_filter flag. -TEST_F(InitGoogleTestTest, FilterBad) { +TEST_F(ParseFlagsTest, FilterBad) { const char* argv[] = { "foo.exe", "--gtest_filter", @@ -5686,7 +5786,7 @@ TEST_F(InitGoogleTestTest, FilterBad) { } // Tests parsing an empty --gtest_filter flag. -TEST_F(InitGoogleTestTest, FilterEmpty) { +TEST_F(ParseFlagsTest, FilterEmpty) { const char* argv[] = { "foo.exe", "--gtest_filter=", @@ -5702,7 +5802,7 @@ TEST_F(InitGoogleTestTest, FilterEmpty) { } // Tests parsing a non-empty --gtest_filter flag. -TEST_F(InitGoogleTestTest, FilterNonEmpty) { +TEST_F(ParseFlagsTest, FilterNonEmpty) { const char* argv[] = { "foo.exe", "--gtest_filter=abc", @@ -5718,7 +5818,7 @@ TEST_F(InitGoogleTestTest, FilterNonEmpty) { } // Tests parsing --gtest_break_on_failure. -TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) { +TEST_F(ParseFlagsTest, BreakOnFailureWithoutValue) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure", @@ -5734,7 +5834,7 @@ TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) { } // Tests parsing --gtest_break_on_failure=0. -TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) { +TEST_F(ParseFlagsTest, BreakOnFailureFalse_0) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure=0", @@ -5750,7 +5850,7 @@ TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) { } // Tests parsing --gtest_break_on_failure=f. -TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) { +TEST_F(ParseFlagsTest, BreakOnFailureFalse_f) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure=f", @@ -5766,7 +5866,7 @@ TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) { } // Tests parsing --gtest_break_on_failure=F. -TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) { +TEST_F(ParseFlagsTest, BreakOnFailureFalse_F) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure=F", @@ -5783,7 +5883,7 @@ TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) { // Tests parsing a --gtest_break_on_failure flag that has a "true" // definition. -TEST_F(InitGoogleTestTest, BreakOnFailureTrue) { +TEST_F(ParseFlagsTest, BreakOnFailureTrue) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure=1", @@ -5799,7 +5899,7 @@ TEST_F(InitGoogleTestTest, BreakOnFailureTrue) { } // Tests parsing --gtest_catch_exceptions. -TEST_F(InitGoogleTestTest, CatchExceptions) { +TEST_F(ParseFlagsTest, CatchExceptions) { const char* argv[] = { "foo.exe", "--gtest_catch_exceptions", @@ -5815,7 +5915,7 @@ TEST_F(InitGoogleTestTest, CatchExceptions) { } // Tests parsing --gtest_death_test_use_fork. -TEST_F(InitGoogleTestTest, DeathTestUseFork) { +TEST_F(ParseFlagsTest, DeathTestUseFork) { const char* argv[] = { "foo.exe", "--gtest_death_test_use_fork", @@ -5832,7 +5932,7 @@ TEST_F(InitGoogleTestTest, DeathTestUseFork) { // Tests having the same flag twice with different values. The // expected behavior is that the one coming last takes precedence. -TEST_F(InitGoogleTestTest, DuplicatedFlags) { +TEST_F(ParseFlagsTest, DuplicatedFlags) { const char* argv[] = { "foo.exe", "--gtest_filter=a", @@ -5849,7 +5949,7 @@ TEST_F(InitGoogleTestTest, DuplicatedFlags) { } // Tests having an unrecognized flag on the command line. -TEST_F(InitGoogleTestTest, UnrecognizedFlag) { +TEST_F(ParseFlagsTest, UnrecognizedFlag) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure", @@ -5871,7 +5971,7 @@ TEST_F(InitGoogleTestTest, UnrecognizedFlag) { } // Tests having a --gtest_list_tests flag -TEST_F(InitGoogleTestTest, ListTestsFlag) { +TEST_F(ParseFlagsTest, ListTestsFlag) { const char* argv[] = { "foo.exe", "--gtest_list_tests", @@ -5887,7 +5987,7 @@ TEST_F(InitGoogleTestTest, ListTestsFlag) { } // Tests having a --gtest_list_tests flag with a "true" value -TEST_F(InitGoogleTestTest, ListTestsTrue) { +TEST_F(ParseFlagsTest, ListTestsTrue) { const char* argv[] = { "foo.exe", "--gtest_list_tests=1", @@ -5903,7 +6003,7 @@ TEST_F(InitGoogleTestTest, ListTestsTrue) { } // Tests having a --gtest_list_tests flag with a "false" value -TEST_F(InitGoogleTestTest, ListTestsFalse) { +TEST_F(ParseFlagsTest, ListTestsFalse) { const char* argv[] = { "foo.exe", "--gtest_list_tests=0", @@ -5919,7 +6019,7 @@ TEST_F(InitGoogleTestTest, ListTestsFalse) { } // Tests parsing --gtest_list_tests=f. -TEST_F(InitGoogleTestTest, ListTestsFalse_f) { +TEST_F(ParseFlagsTest, ListTestsFalse_f) { const char* argv[] = { "foo.exe", "--gtest_list_tests=f", @@ -5935,7 +6035,7 @@ TEST_F(InitGoogleTestTest, ListTestsFalse_f) { } // Tests parsing --gtest_list_tests=F. -TEST_F(InitGoogleTestTest, ListTestsFalse_F) { +TEST_F(ParseFlagsTest, ListTestsFalse_F) { const char* argv[] = { "foo.exe", "--gtest_list_tests=F", @@ -5951,7 +6051,7 @@ TEST_F(InitGoogleTestTest, ListTestsFalse_F) { } // Tests parsing --gtest_output (invalid). -TEST_F(InitGoogleTestTest, OutputEmpty) { +TEST_F(ParseFlagsTest, OutputEmpty) { const char* argv[] = { "foo.exe", "--gtest_output", @@ -5968,7 +6068,7 @@ TEST_F(InitGoogleTestTest, OutputEmpty) { } // Tests parsing --gtest_output=xml -TEST_F(InitGoogleTestTest, OutputXml) { +TEST_F(ParseFlagsTest, OutputXml) { const char* argv[] = { "foo.exe", "--gtest_output=xml", @@ -5984,7 +6084,7 @@ TEST_F(InitGoogleTestTest, OutputXml) { } // Tests parsing --gtest_output=xml:file -TEST_F(InitGoogleTestTest, OutputXmlFile) { +TEST_F(ParseFlagsTest, OutputXmlFile) { const char* argv[] = { "foo.exe", "--gtest_output=xml:file", @@ -6000,7 +6100,7 @@ TEST_F(InitGoogleTestTest, OutputXmlFile) { } // Tests parsing --gtest_output=xml:directory/path/ -TEST_F(InitGoogleTestTest, OutputXmlDirectory) { +TEST_F(ParseFlagsTest, OutputXmlDirectory) { const char* argv[] = { "foo.exe", "--gtest_output=xml:directory/path/", @@ -6017,7 +6117,7 @@ TEST_F(InitGoogleTestTest, OutputXmlDirectory) { } // Tests having a --gtest_print_time flag -TEST_F(InitGoogleTestTest, PrintTimeFlag) { +TEST_F(ParseFlagsTest, PrintTimeFlag) { const char* argv[] = { "foo.exe", "--gtest_print_time", @@ -6033,7 +6133,7 @@ TEST_F(InitGoogleTestTest, PrintTimeFlag) { } // Tests having a --gtest_print_time flag with a "true" value -TEST_F(InitGoogleTestTest, PrintTimeTrue) { +TEST_F(ParseFlagsTest, PrintTimeTrue) { const char* argv[] = { "foo.exe", "--gtest_print_time=1", @@ -6049,7 +6149,7 @@ TEST_F(InitGoogleTestTest, PrintTimeTrue) { } // Tests having a --gtest_print_time flag with a "false" value -TEST_F(InitGoogleTestTest, PrintTimeFalse) { +TEST_F(ParseFlagsTest, PrintTimeFalse) { const char* argv[] = { "foo.exe", "--gtest_print_time=0", @@ -6065,7 +6165,7 @@ TEST_F(InitGoogleTestTest, PrintTimeFalse) { } // Tests parsing --gtest_print_time=f. -TEST_F(InitGoogleTestTest, PrintTimeFalse_f) { +TEST_F(ParseFlagsTest, PrintTimeFalse_f) { const char* argv[] = { "foo.exe", "--gtest_print_time=f", @@ -6081,7 +6181,7 @@ TEST_F(InitGoogleTestTest, PrintTimeFalse_f) { } // Tests parsing --gtest_print_time=F. -TEST_F(InitGoogleTestTest, PrintTimeFalse_F) { +TEST_F(ParseFlagsTest, PrintTimeFalse_F) { const char* argv[] = { "foo.exe", "--gtest_print_time=F", @@ -6097,7 +6197,7 @@ TEST_F(InitGoogleTestTest, PrintTimeFalse_F) { } // Tests parsing --gtest_random_seed=number -TEST_F(InitGoogleTestTest, RandomSeed) { +TEST_F(ParseFlagsTest, RandomSeed) { const char* argv[] = { "foo.exe", "--gtest_random_seed=1000", @@ -6113,7 +6213,7 @@ TEST_F(InitGoogleTestTest, RandomSeed) { } // Tests parsing --gtest_repeat=number -TEST_F(InitGoogleTestTest, Repeat) { +TEST_F(ParseFlagsTest, Repeat) { const char* argv[] = { "foo.exe", "--gtest_repeat=1000", @@ -6129,7 +6229,7 @@ TEST_F(InitGoogleTestTest, Repeat) { } // Tests having a --gtest_also_run_disabled_tests flag -TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) { +TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) { const char* argv[] = { "foo.exe", "--gtest_also_run_disabled_tests", @@ -6146,7 +6246,7 @@ TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) { } // Tests having a --gtest_also_run_disabled_tests flag with a "true" value -TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) { +TEST_F(ParseFlagsTest, AlsoRunDisabledTestsTrue) { const char* argv[] = { "foo.exe", "--gtest_also_run_disabled_tests=1", @@ -6163,7 +6263,7 @@ TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) { } // Tests having a --gtest_also_run_disabled_tests flag with a "false" value -TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) { +TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFalse) { const char* argv[] = { "foo.exe", "--gtest_also_run_disabled_tests=0", @@ -6180,7 +6280,7 @@ TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) { } // Tests parsing --gtest_shuffle. -TEST_F(InitGoogleTestTest, ShuffleWithoutValue) { +TEST_F(ParseFlagsTest, ShuffleWithoutValue) { const char* argv[] = { "foo.exe", "--gtest_shuffle", @@ -6196,7 +6296,7 @@ TEST_F(InitGoogleTestTest, ShuffleWithoutValue) { } // Tests parsing --gtest_shuffle=0. -TEST_F(InitGoogleTestTest, ShuffleFalse_0) { +TEST_F(ParseFlagsTest, ShuffleFalse_0) { const char* argv[] = { "foo.exe", "--gtest_shuffle=0", @@ -6211,9 +6311,8 @@ TEST_F(InitGoogleTestTest, ShuffleFalse_0) { GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false); } -// Tests parsing a --gtest_shuffle flag that has a "true" -// definition. -TEST_F(InitGoogleTestTest, ShuffleTrue) { +// Tests parsing a --gtest_shuffle flag that has a "true" definition. +TEST_F(ParseFlagsTest, ShuffleTrue) { const char* argv[] = { "foo.exe", "--gtest_shuffle=1", @@ -6229,7 +6328,7 @@ TEST_F(InitGoogleTestTest, ShuffleTrue) { } // Tests parsing --gtest_stack_trace_depth=number. -TEST_F(InitGoogleTestTest, StackTraceDepth) { +TEST_F(ParseFlagsTest, StackTraceDepth) { const char* argv[] = { "foo.exe", "--gtest_stack_trace_depth=5", @@ -6244,7 +6343,7 @@ TEST_F(InitGoogleTestTest, StackTraceDepth) { GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false); } -TEST_F(InitGoogleTestTest, StreamResultTo) { +TEST_F(ParseFlagsTest, StreamResultTo) { const char* argv[] = { "foo.exe", "--gtest_stream_result_to=localhost:1234", @@ -6261,7 +6360,7 @@ TEST_F(InitGoogleTestTest, StreamResultTo) { } // Tests parsing --gtest_throw_on_failure. -TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) { +TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) { const char* argv[] = { "foo.exe", "--gtest_throw_on_failure", @@ -6277,7 +6376,7 @@ TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) { } // Tests parsing --gtest_throw_on_failure=0. -TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) { +TEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) { const char* argv[] = { "foo.exe", "--gtest_throw_on_failure=0", @@ -6294,7 +6393,7 @@ TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) { // Tests parsing a --gtest_throw_on_failure flag that has a "true" // definition. -TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) { +TEST_F(ParseFlagsTest, ThrowOnFailureTrue) { const char* argv[] = { "foo.exe", "--gtest_throw_on_failure=1", @@ -6309,9 +6408,9 @@ TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) { GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); } -#if GTEST_OS_WINDOWS +# if GTEST_OS_WINDOWS // Tests parsing wide strings. -TEST_F(InitGoogleTestTest, WideStrings) { +TEST_F(ParseFlagsTest, WideStrings) { const wchar_t* argv[] = { L"foo.exe", L"--gtest_filter=Foo*", @@ -6334,7 +6433,108 @@ TEST_F(InitGoogleTestTest, WideStrings) { GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false); } -#endif // GTEST_OS_WINDOWS +# endif // GTEST_OS_WINDOWS + +#if GTEST_USE_OWN_FLAGFILE_FLAG_ +class FlagfileTest : public ParseFlagsTest { + public: + virtual void SetUp() { + ParseFlagsTest::SetUp(); + + testdata_path_.Set(internal::FilePath( + testing::TempDir() + internal::GetCurrentExecutableName().string() + + "_flagfile_test")); + testing::internal::posix::RmDir(testdata_path_.c_str()); + EXPECT_TRUE(testdata_path_.CreateFolder()); + } + + virtual void TearDown() { + testing::internal::posix::RmDir(testdata_path_.c_str()); + ParseFlagsTest::TearDown(); + } + + internal::FilePath CreateFlagfile(const char* contents) { + internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName( + testdata_path_, internal::FilePath("unique"), "txt")); + FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w"); + fprintf(f, "%s", contents); + fclose(f); + return file_path; + } + + private: + internal::FilePath testdata_path_; +}; + +// Tests an empty flagfile. +TEST_F(FlagfileTest, Empty) { + internal::FilePath flagfile_path(CreateFlagfile("")); + std::string flagfile_flag = + std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); + + const char* argv[] = { + "foo.exe", + flagfile_flag.c_str(), + NULL + }; + + const char* argv2[] = { + "foo.exe", + NULL + }; + + GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); +} + +// Tests passing a non-empty --gtest_filter flag via --gtest_flagfile. +TEST_F(FlagfileTest, FilterNonEmpty) { + internal::FilePath flagfile_path(CreateFlagfile( + "--" GTEST_FLAG_PREFIX_ "filter=abc")); + std::string flagfile_flag = + std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); + + const char* argv[] = { + "foo.exe", + flagfile_flag.c_str(), + NULL + }; + + const char* argv2[] = { + "foo.exe", + NULL + }; + + GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false); +} + +// Tests passing several flags via --gtest_flagfile. +TEST_F(FlagfileTest, SeveralFlags) { + internal::FilePath flagfile_path(CreateFlagfile( + "--" GTEST_FLAG_PREFIX_ "filter=abc\n" + "--" GTEST_FLAG_PREFIX_ "break_on_failure\n" + "--" GTEST_FLAG_PREFIX_ "list_tests")); + std::string flagfile_flag = + std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); + + const char* argv[] = { + "foo.exe", + flagfile_flag.c_str(), + NULL + }; + + const char* argv2[] = { + "foo.exe", + NULL + }; + + Flags expected_flags; + expected_flags.break_on_failure = true; + expected_flags.filter = "abc"; + expected_flags.list_tests = true; + + GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false); +} +#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ // Tests current_test_info() in UnitTest. class CurrentTestInfoTest : public Test { @@ -6389,6 +6589,7 @@ TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) { } // namespace testing + // These two lines test that we can define tests in a namespace that // has the name "testing" and is nested in another namespace. namespace my_namespace { @@ -6469,7 +6670,7 @@ TEST(StreamingAssertionsTest, Truth2) { } #ifdef __BORLANDC__ -// Restores warnings after previous "#pragma option push" supressed them +// Restores warnings after previous "#pragma option push" suppressed them # pragma option pop #endif @@ -6672,6 +6873,18 @@ TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) { SetEnv("TERM", "screen-256color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. + SetEnv("TERM", "tmux"); // TERM supports colors. + EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. + + SetEnv("TERM", "tmux-256color"); // TERM supports colors. + EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. + + SetEnv("TERM", "rxvt-unicode"); // TERM supports colors. + EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. + + SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors. + EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. + SetEnv("TERM", "linux"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. @@ -6707,14 +6920,6 @@ TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) { StaticAssertTypeEq<int*, IntAlias*>(); } -TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) { - testing::UnitTest* const unit_test = testing::UnitTest::GetInstance(); - - // We don't have a stack walker in Google Test yet. - EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str()); - EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str()); -} - TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) { EXPECT_FALSE(HasNonfatalFailure()); } @@ -7166,7 +7371,7 @@ GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST. // Tests for internal utilities necessary for implementation of the universal // printing. -// TODO(vladl@google.com): Find a better home for them. +// FIXME: Find a better home for them. class ConversionHelperBase {}; class ConversionHelperDerived : public ConversionHelperBase {}; @@ -7350,6 +7555,50 @@ TEST(IsContainerTestTest, WorksForContainer) { sizeof(IsContainerTest<std::map<int, double> >(0))); } +#if GTEST_LANG_CXX11 +struct ConstOnlyContainerWithPointerIterator { + using const_iterator = int*; + const_iterator begin() const; + const_iterator end() const; +}; + +struct ConstOnlyContainerWithClassIterator { + struct const_iterator { + const int& operator*() const; + const_iterator& operator++(/* pre-increment */); + }; + const_iterator begin() const; + const_iterator end() const; +}; + +TEST(IsContainerTestTest, ConstOnlyContainer) { + EXPECT_EQ(sizeof(IsContainer), + sizeof(IsContainerTest<ConstOnlyContainerWithPointerIterator>(0))); + EXPECT_EQ(sizeof(IsContainer), + sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0))); +} +#endif // GTEST_LANG_CXX11 + +// Tests IsHashTable. +struct AHashTable { + typedef void hasher; +}; +struct NotReallyAHashTable { + typedef void hasher; + typedef void reverse_iterator; +}; +TEST(IsHashTable, Basic) { + EXPECT_TRUE(testing::internal::IsHashTable<AHashTable>::value); + EXPECT_FALSE(testing::internal::IsHashTable<NotReallyAHashTable>::value); +#if GTEST_LANG_CXX11 + EXPECT_FALSE(testing::internal::IsHashTable<std::vector<int>>::value); + EXPECT_TRUE(testing::internal::IsHashTable<std::unordered_set<int>>::value); +#endif // GTEST_LANG_CXX11 +#if GTEST_HAS_HASH_SET_ + EXPECT_TRUE(testing::internal::IsHashTable<__gnu_cxx::hash_set<int>>::value); +#endif // GTEST_HAS_HASH_SET_ +} + // Tests ArrayEq(). TEST(ArrayEqTest, WorksForDegeneratedArrays) { @@ -7523,3 +7772,24 @@ TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) { EXPECT_EQ(str, p); } +// Tests ad_hoc_test_result(). + +class AdHocTestResultTest : public testing::Test { + protected: + static void SetUpTestCase() { + FAIL() << "A failure happened inside SetUpTestCase()."; + } +}; + +TEST_F(AdHocTestResultTest, AdHocTestResultForTestCaseShowsFailure) { + const testing::TestResult& test_result = testing::UnitTest::GetInstance() + ->current_test_case() + ->ad_hoc_test_result(); + EXPECT_TRUE(test_result.Failed()); +} + +TEST_F(AdHocTestResultTest, AdHocTestResultTestForUnitTestDoesNotShowFailure) { + const testing::TestResult& test_result = + testing::UnitTest::GetInstance()->ad_hoc_test_result(); + EXPECT_FALSE(test_result.Failed()); +} diff --git a/security/nss/gtests/google_test/gtest/test/gtest_xml_outfile1_test_.cc b/security/nss/gtests/google_test/gtest/test/gtest_xml_outfile1_test_.cc index 531ced49d..a38ebac83 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_xml_outfile1_test_.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest_xml_outfile1_test_.cc @@ -27,8 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// Author: keith.ray@gmail.com (Keith Ray) -// // gtest_xml_outfile1_test_ writes some xml via TestProperty used by // gtest_xml_outfiles_test.py diff --git a/security/nss/gtests/google_test/gtest/test/gtest_xml_outfile2_test_.cc b/security/nss/gtests/google_test/gtest/test/gtest_xml_outfile2_test_.cc index 7b400b276..afaf15a5d 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_xml_outfile2_test_.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest_xml_outfile2_test_.cc @@ -27,8 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// Author: keith.ray@gmail.com (Keith Ray) -// // gtest_xml_outfile2_test_ writes some xml via TestProperty used by // gtest_xml_outfiles_test.py diff --git a/security/nss/gtests/google_test/gtest/test/gtest_xml_outfiles_test.py b/security/nss/gtests/google_test/gtest/test/gtest_xml_outfiles_test.py index 524e437e6..2c031ff8d 100755 --- a/security/nss/gtests/google_test/gtest/test/gtest_xml_outfiles_test.py +++ b/security/nss/gtests/google_test/gtest/test/gtest_xml_outfiles_test.py @@ -31,15 +31,11 @@ """Unit test for the gtest_xml_output module.""" -__author__ = "keith.ray@gmail.com (Keith Ray)" - import os from xml.dom import minidom, Node - import gtest_test_utils import gtest_xml_test_utils - GTEST_OUTPUT_SUBDIR = "xml_outfiles" GTEST_OUTPUT_1_TEST = "gtest_xml_outfile1_test_" GTEST_OUTPUT_2_TEST = "gtest_xml_outfile2_test_" @@ -47,7 +43,13 @@ GTEST_OUTPUT_2_TEST = "gtest_xml_outfile2_test_" EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests"> <testsuite name="PropertyOne" tests="1" failures="0" disabled="0" errors="0" time="*"> - <testcase name="TestSomeProperties" status="run" time="*" classname="PropertyOne" SetUpProp="1" TestSomeProperty="1" TearDownProp="1" /> + <testcase name="TestSomeProperties" status="run" time="*" classname="PropertyOne"> + <properties> + <property name="SetUpProp" value="1"/> + <property name="TestSomeProperty" value="1"/> + <property name="TearDownProp" value="1"/> + </properties> + </testcase> </testsuite> </testsuites> """ @@ -55,7 +57,13 @@ EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?> EXPECTED_XML_2 = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests"> <testsuite name="PropertyTwo" tests="1" failures="0" disabled="0" errors="0" time="*"> - <testcase name="TestSomeProperties" status="run" time="*" classname="PropertyTwo" SetUpProp="2" TestSomeProperty="2" TearDownProp="2" /> + <testcase name="TestSomeProperties" status="run" time="*" classname="PropertyTwo"> + <properties> + <property name="SetUpProp" value="2"/> + <property name="TestSomeProperty" value="2"/> + <property name="TearDownProp" value="2"/> + </properties> + </testcase> </testsuite> </testsuites> """ @@ -103,11 +111,11 @@ class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase): self.assert_(p.exited) self.assertEquals(0, p.exit_code) - # TODO(wan@google.com): libtool causes the built test binary to be + # FIXME: libtool causes the built test binary to be # named lt-gtest_xml_outfiles_test_ instead of - # gtest_xml_outfiles_test_. To account for this possibillity, we + # 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. + # when libtool replacement tool is ready. output_file_name1 = test_name + ".xml" output_file1 = os.path.join(self.output_dir_, output_file_name1) output_file_name2 = 'lt-' + output_file_name1 diff --git a/security/nss/gtests/google_test/gtest/test/gtest_xml_output_unittest.py b/security/nss/gtests/google_test/gtest/test/gtest_xml_output_unittest.py index f605d4ee2..faedd4e6c 100755 --- a/security/nss/gtests/google_test/gtest/test/gtest_xml_output_unittest.py +++ b/security/nss/gtests/google_test/gtest/test/gtest_xml_output_unittest.py @@ -31,8 +31,6 @@ """Unit test for the gtest_xml_output module""" -__author__ = 'eefacm@gmail.com (Sean Mcafee)' - import datetime import errno import os @@ -43,19 +41,28 @@ from xml.dom import minidom, Node import gtest_test_utils import gtest_xml_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.xml" -GTEST_PROGRAM_NAME = "gtest_xml_output_unittest_" +GTEST_OUTPUT_FLAG = '--gtest_output' +GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.xml' +GTEST_PROGRAM_NAME = 'gtest_xml_output_unittest_' + +# The flag indicating stacktraces are not supported +NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support' -SUPPORTS_STACK_TRACES = False +# The environment variables for test sharding. +TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS' +SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX' +SHARD_STATUS_FILE_ENV_VAR = 'GTEST_SHARD_STATUS_FILE' + +SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv if SUPPORTS_STACK_TRACES: STACK_TRACE_TEMPLATE = '\nStack trace:\n*' else: STACK_TRACE_TEMPLATE = '' + # unittest.main() can't handle unknown flags + sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG) EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="23" failures="4" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42"> @@ -64,20 +71,23 @@ EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?> </testsuite> <testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*"> <testcase name="Fails" status="run" time="*" classname="FailedTest"> - <failure message="gtest_xml_output_unittest_.cc:*
Value of: 2
Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:* -Value of: 2 -Expected: 1%(stack)s]]></failure> + <failure message="gtest_xml_output_unittest_.cc:*
Expected equality of these values:
 1
 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:* +Expected equality of these values: + 1 + 2%(stack)s]]></failure> </testcase> </testsuite> <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*"> <testcase name="Succeeds" status="run" time="*" classname="MixedResultTest"/> <testcase name="Fails" status="run" time="*" classname="MixedResultTest"> - <failure message="gtest_xml_output_unittest_.cc:*
Value of: 2
Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:* -Value of: 2 -Expected: 1%(stack)s]]></failure> - <failure message="gtest_xml_output_unittest_.cc:*
Value of: 3
Expected: 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:* -Value of: 3 -Expected: 2%(stack)s]]></failure> + <failure message="gtest_xml_output_unittest_.cc:*
Expected equality of these values:
 1
 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:* +Expected equality of these values: + 1 + 2%(stack)s]]></failure> + <failure message="gtest_xml_output_unittest_.cc:*
Expected equality of these values:
 2
 3" type=""><![CDATA[gtest_xml_output_unittest_.cc:* +Expected equality of these values: + 2 + 3%(stack)s]]></failure> </testcase> <testcase name="DISABLED_test" status="notrun" time="*" classname="MixedResultTest"/> </testsuite> @@ -99,15 +109,45 @@ Invalid characters in brackets []%(stack)s]]></failure> <testcase name="DISABLED_test_not_run" status="notrun" time="*" classname="DisabledTest"/> </testsuite> <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*" SetUpTestCase="yes" TearDownTestCase="aye"> - <testcase name="OneProperty" status="run" time="*" classname="PropertyRecordingTest" key_1="1"/> - <testcase name="IntValuedProperty" status="run" time="*" classname="PropertyRecordingTest" key_int="1"/> - <testcase name="ThreeProperties" status="run" time="*" classname="PropertyRecordingTest" key_1="1" key_2="2" key_3="3"/> - <testcase name="TwoValuesForOneKeyUsesLastValue" status="run" time="*" classname="PropertyRecordingTest" key_1="2"/> + <testcase name="OneProperty" status="run" time="*" classname="PropertyRecordingTest"> + <properties> + <property name="key_1" value="1"/> + </properties> + </testcase> + <testcase name="IntValuedProperty" status="run" time="*" classname="PropertyRecordingTest"> + <properties> + <property name="key_int" value="1"/> + </properties> + </testcase> + <testcase name="ThreeProperties" status="run" time="*" classname="PropertyRecordingTest"> + <properties> + <property name="key_1" value="1"/> + <property name="key_2" value="2"/> + <property name="key_3" value="3"/> + </properties> + </testcase> + <testcase name="TwoValuesForOneKeyUsesLastValue" status="run" time="*" classname="PropertyRecordingTest"> + <properties> + <property name="key_1" value="2"/> + </properties> + </testcase> </testsuite> <testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*"> - <testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest" key="1"/> - <testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_int="1"/> - <testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_string="1"/> + <testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest"> + <properties> + <property name="key" value="1"/> + </properties> + </testcase> + <testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" time="*" classname="NoFixtureTest"> + <properties> + <property name="key_for_utility_int" value="1"/> + </properties> + </testcase> + <testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" time="*" classname="NoFixtureTest"> + <properties> + <property name="key_for_utility_string" value="1"/> + </properties> + </testcase> </testsuite> <testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasValueParamAttribute/0" value_param="33" status="run" time="*" classname="Single/ValueParamTest" /> @@ -138,6 +178,23 @@ EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?> </testsuite> </testsuites>""" +EXPECTED_SHARDED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?> +<testsuites tests="3" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42"> + <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*"> + <testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/> + </testsuite> + <testsuite name="NoFixtureTest" tests="1" failures="0" disabled="0" errors="0" time="*"> + <testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest"> + <properties> + <property name="key" value="1"/> + </properties> + </testcase> + </testsuite> + <testsuite name="Single/ValueParamTest" tests="1" failures="0" disabled="0" errors="0" time="*"> + <testcase name="AnotherTestThatHasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" /> + </testsuite> +</testsuites>""" + EXPECTED_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="0" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests"> @@ -179,7 +236,7 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase): Runs a test program that generates an empty XML output, and checks if the timestamp attribute in the testsuites tag is valid. """ - actual = self._GetXmlOutput('gtest_no_test_unittest', [], 0) + actual = self._GetXmlOutput('gtest_no_test_unittest', [], {}, 0) date_time_str = actual.documentElement.getAttributeNode('timestamp').value # datetime.strptime() is only available in Python 2.5+ so we have to # parse the expected datetime manually. @@ -236,7 +293,7 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase): '--shut_down_xml'] p = gtest_test_utils.Subprocess(command) if p.terminated_by_signal: - # p.signal is avalable only if p.terminated_by_signal is True. + # 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)) @@ -259,7 +316,22 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase): self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED_TEST_XML, 0, extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG]) - def _GetXmlOutput(self, gtest_prog_name, extra_args, expected_exit_code): + def testShardedTestXmlOutput(self): + """Verifies XML output when run using multiple shards. + + Runs a test program that executes only one shard and verifies that tests + from other shards do not show up in the XML output. + """ + + self._TestXmlOutput( + GTEST_PROGRAM_NAME, + EXPECTED_SHARDED_TEST_XML, + 0, + extra_env={SHARD_INDEX_ENV_VAR: '0', + TOTAL_SHARDS_ENV_VAR: '10'}) + + def _GetXmlOutput(self, gtest_prog_name, extra_args, extra_env, + expected_exit_code): """ Returns the xml output generated by running the program gtest_prog_name. Furthermore, the program's exit code must be expected_exit_code. @@ -270,7 +342,11 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase): command = ([gtest_prog_path, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path)] + extra_args) - p = gtest_test_utils.Subprocess(command) + environ_copy = os.environ.copy() + if extra_env: + environ_copy.update(extra_env) + p = gtest_test_utils.Subprocess(command, env=environ_copy) + if p.terminated_by_signal: self.assert_(False, '%s was killed by signal %d' % (gtest_prog_name, p.signal)) @@ -284,7 +360,7 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase): return actual def _TestXmlOutput(self, gtest_prog_name, expected_xml, - expected_exit_code, extra_args=None): + expected_exit_code, extra_args=None, extra_env=None): """ Asserts that the XML document generated by running the program gtest_prog_name matches expected_xml, a string containing another @@ -293,7 +369,7 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase): """ actual = self._GetXmlOutput(gtest_prog_name, extra_args or [], - expected_exit_code) + extra_env or {}, expected_exit_code) expected = minidom.parseString(expected_xml) self.NormalizeXml(actual.documentElement) self.AssertEquivalentNodes(expected.documentElement, diff --git a/security/nss/gtests/google_test/gtest/test/gtest_xml_output_unittest_.cc b/security/nss/gtests/google_test/gtest/test/gtest_xml_output_unittest_.cc index 48b8771b5..2ee883800 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_xml_output_unittest_.cc +++ b/security/nss/gtests/google_test/gtest/test/gtest_xml_output_unittest_.cc @@ -27,8 +27,6 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// Author: eefacm@gmail.com (Sean Mcafee) - // Unit test for Google Test XML output. // // A user can specify XML output in a Google Test program to run via diff --git a/security/nss/gtests/google_test/gtest/test/gtest_xml_test_utils.py b/security/nss/gtests/google_test/gtest/test/gtest_xml_test_utils.py index 3d0c3b2c2..1e0358592 100755 --- a/security/nss/gtests/google_test/gtest/test/gtest_xml_test_utils.py +++ b/security/nss/gtests/google_test/gtest/test/gtest_xml_test_utils.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python -# # Copyright 2006, Google Inc. # All rights reserved. # @@ -31,15 +29,10 @@ """Unit test utilities for gtest_xml_output""" -__author__ = 'eefacm@gmail.com (Sean Mcafee)' - import re from xml.dom import minidom, Node - import gtest_test_utils - -GTEST_OUTPUT_FLAG = '--gtest_output' GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.xml' class GTestXMLTestCase(gtest_test_utils.TestCase): @@ -108,19 +101,22 @@ class GTestXMLTestCase(gtest_test_utils.TestCase): self.AssertEquivalentNodes(child, actual_children[child_id]) identifying_attribute = { - 'testsuites': 'name', - 'testsuite': 'name', - 'testcase': 'name', - 'failure': 'message', - } + 'testsuites': 'name', + 'testsuite': 'name', + 'testcase': 'name', + 'failure': 'message', + 'property': 'name', + } def _GetChildren(self, element): """ Fetches all of the child nodes of element, a DOM Element object. Returns them as the values of a dictionary keyed by the IDs of the - children. For <testsuites>, <testsuite> and <testcase> elements, the ID - is the value of their "name" attribute; for <failure> elements, it is - the value of the "message" attribute; CDATA sections and non-whitespace + children. For <testsuites>, <testsuite>, <testcase>, and <property> + elements, the ID is the value of their "name" attribute; for <failure> + elements, it is the value of the "message" attribute; for <properties> + elements, it is the value of their parent's "name" attribute plus the + literal string "properties"; CDATA sections and non-whitespace text nodes are concatenated into a single CDATA section with ID "detail". An exception is raised if any element other than the above four is encountered, if two child elements with the same identifying @@ -130,11 +126,17 @@ class GTestXMLTestCase(gtest_test_utils.TestCase): children = {} for child in element.childNodes: if child.nodeType == Node.ELEMENT_NODE: - self.assert_(child.tagName in self.identifying_attribute, - 'Encountered unknown element <%s>' % child.tagName) - childID = child.getAttribute(self.identifying_attribute[child.tagName]) - self.assert_(childID not in children) - children[childID] = child + if child.tagName == 'properties': + self.assert_(child.parentNode is not None, + 'Encountered <properties> element without a parent') + child_id = child.parentNode.getAttribute('name') + '-properties' + else: + self.assert_(child.tagName in self.identifying_attribute, + 'Encountered unknown element <%s>' % child.tagName) + child_id = child.getAttribute( + self.identifying_attribute[child.tagName]) + self.assert_(child_id not in children) + children[child_id] = child elif child.nodeType in [Node.TEXT_NODE, Node.CDATA_SECTION_NODE]: if 'detail' not in children: if (child.nodeType == Node.CDATA_SECTION_NODE or @@ -187,8 +189,8 @@ class GTestXMLTestCase(gtest_test_utils.TestCase): # Replaces the source line information with a normalized form. cdata = re.sub(source_line_pat, '\\1*\n', child.nodeValue) # Removes the actual stack trace. - child.nodeValue = re.sub(r'\nStack trace:\n(.|\n)*', - '', cdata) + child.nodeValue = re.sub(r'Stack trace:\n(.|\n)*', + 'Stack trace:\n*', cdata) for child in element.childNodes: if child.nodeType == Node.ELEMENT_NODE: self.NormalizeXml(child) diff --git a/security/nss/gtests/google_test/gtest/test/production.cc b/security/nss/gtests/google_test/gtest/test/production.cc index 8b8a40b44..0f69f6dbd 100644 --- a/security/nss/gtests/google_test/gtest/test/production.cc +++ b/security/nss/gtests/google_test/gtest/test/production.cc @@ -26,10 +26,9 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + // -// Author: wan@google.com (Zhanyong Wan) -// -// This is part of the unit test for include/gtest/gtest_prod.h. +// This is part of the unit test for gtest_prod.h. #include "production.h" diff --git a/security/nss/gtests/google_test/gtest/test/production.h b/security/nss/gtests/google_test/gtest/test/production.h index 98fd5e476..542723b70 100644 --- a/security/nss/gtests/google_test/gtest/test/production.h +++ b/security/nss/gtests/google_test/gtest/test/production.h @@ -26,10 +26,9 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + // -// Author: wan@google.com (Zhanyong Wan) -// -// This is part of the unit test for include/gtest/gtest_prod.h. +// This is part of the unit test for gtest_prod.h. #ifndef GTEST_TEST_PRODUCTION_H_ #define GTEST_TEST_PRODUCTION_H_ |