Imported Upstream version 1.12.0 upstream/1.12.0
authorJinWang An <jinwang.an@samsung.com>
Wed, 28 Dec 2022 02:05:52 +0000 (11:05 +0900)
committerJinWang An <jinwang.an@samsung.com>
Wed, 28 Dec 2022 02:05:52 +0000 (11:05 +0900)
225 files changed:
.github/workflows/gtest-ci.yml [new file with mode: 0644]
BUILD.bazel
CMakeLists.txt
CONTRIBUTING.md
CONTRIBUTORS
README.md
WORKSPACE
ci/linux-presubmit.sh
docs/advanced.md
docs/faq.md
docs/gmock_cheat_sheet.md
docs/gmock_cook_book.md
docs/gmock_faq.md
docs/gmock_for_dummies.md
docs/pkgconfig.md
docs/primer.md
docs/quickstart-bazel.md
docs/reference/actions.md
docs/reference/matchers.md
docs/reference/mocking.md
docs/reference/testing.md
googlemock/CMakeLists.txt
googlemock/README.md
googlemock/include/gmock/gmock-actions.h
googlemock/include/gmock/gmock-cardinalities.h
googlemock/include/gmock/gmock-function-mocker.h
googlemock/include/gmock/gmock-matchers.h
googlemock/include/gmock/gmock-more-actions.h
googlemock/include/gmock/gmock-more-matchers.h
googlemock/include/gmock/gmock-nice-strict.h
googlemock/include/gmock/gmock-spec-builders.h
googlemock/include/gmock/gmock.h
googlemock/include/gmock/internal/custom/README.md
googlemock/include/gmock/internal/custom/gmock-generated-actions.h
googlemock/include/gmock/internal/custom/gmock-matchers.h
googlemock/include/gmock/internal/custom/gmock-port.h
googlemock/include/gmock/internal/gmock-internal-utils.h
googlemock/include/gmock/internal/gmock-port.h
googlemock/scripts/README.md [deleted file]
googlemock/scripts/fuse_gmock_files.py [deleted file]
googlemock/scripts/generator/LICENSE [deleted file]
googlemock/scripts/generator/README [deleted file]
googlemock/scripts/generator/README.cppclean [deleted file]
googlemock/scripts/generator/cpp/__init__.py [deleted file]
googlemock/scripts/generator/cpp/ast.py [deleted file]
googlemock/scripts/generator/cpp/gmock_class.py [deleted file]
googlemock/scripts/generator/cpp/gmock_class_test.py [deleted file]
googlemock/scripts/generator/cpp/keywords.py [deleted file]
googlemock/scripts/generator/cpp/tokenize.py [deleted file]
googlemock/scripts/generator/cpp/utils.py [deleted file]
googlemock/scripts/generator/gmock_gen.py [deleted file]
googlemock/src/gmock-cardinalities.cc
googlemock/src/gmock-internal-utils.cc
googlemock/src/gmock-matchers.cc
googlemock/src/gmock-spec-builders.cc
googlemock/src/gmock.cc
googlemock/src/gmock_main.cc
googlemock/test/BUILD.bazel
googlemock/test/gmock-actions_test.cc
googlemock/test/gmock-cardinalities_test.cc
googlemock/test/gmock-function-mocker_test.cc
googlemock/test/gmock-internal-utils_test.cc
googlemock/test/gmock-matchers-arithmetic_test.cc [new file with mode: 0644]
googlemock/test/gmock-matchers-comparisons_test.cc [new file with mode: 0644]
googlemock/test/gmock-matchers-containers_test.cc [new file with mode: 0644]
googlemock/test/gmock-matchers-misc_test.cc [new file with mode: 0644]
googlemock/test/gmock-matchers_test.cc [deleted file]
googlemock/test/gmock-matchers_test.h [new file with mode: 0644]
googlemock/test/gmock-more-actions_test.cc
googlemock/test/gmock-nice-strict_test.cc
googlemock/test/gmock-port_test.cc
googlemock/test/gmock-pp-string_test.cc
googlemock/test/gmock-spec-builders_test.cc
googlemock/test/gmock_all_test.cc
googlemock/test/gmock_ex_test.cc
googlemock/test/gmock_leak_test.py
googlemock/test/gmock_leak_test_.cc
googlemock/test/gmock_link2_test.cc
googlemock/test/gmock_link_test.cc
googlemock/test/gmock_link_test.h
googlemock/test/gmock_output_test.py
googlemock/test/gmock_output_test_.cc
googlemock/test/gmock_output_test_golden.txt
googlemock/test/gmock_stress_test.cc
googlemock/test/gmock_test.cc
googlemock/test/gmock_test_utils.py
googletest/CMakeLists.txt
googletest/README.md
googletest/cmake/internal_utils.cmake
googletest/include/gtest/gtest-assertion-result.h [new file with mode: 0644]
googletest/include/gtest/gtest-death-test.h
googletest/include/gtest/gtest-matchers.h
googletest/include/gtest/gtest-message.h
googletest/include/gtest/gtest-param-test.h
googletest/include/gtest/gtest-printers.h
googletest/include/gtest/gtest-spi.h
googletest/include/gtest/gtest-test-part.h
googletest/include/gtest/gtest-typed-test.h
googletest/include/gtest/gtest.h
googletest/include/gtest/gtest_pred_impl.h
googletest/include/gtest/gtest_prod.h
googletest/include/gtest/internal/custom/README.md
googletest/include/gtest/internal/gtest-death-test-internal.h
googletest/include/gtest/internal/gtest-filepath.h
googletest/include/gtest/internal/gtest-internal.h
googletest/include/gtest/internal/gtest-param-util.h
googletest/include/gtest/internal/gtest-port-arch.h
googletest/include/gtest/internal/gtest-port.h
googletest/include/gtest/internal/gtest-string.h
googletest/include/gtest/internal/gtest-type-util.h
googletest/samples/prime_tables.h
googletest/samples/sample1.cc
googletest/samples/sample10_unittest.cc
googletest/samples/sample1_unittest.cc
googletest/samples/sample2.cc
googletest/samples/sample2.h
googletest/samples/sample2_unittest.cc
googletest/samples/sample3-inl.h
googletest/samples/sample3_unittest.cc
googletest/samples/sample4.cc
googletest/samples/sample4_unittest.cc
googletest/samples/sample5_unittest.cc
googletest/samples/sample6_unittest.cc
googletest/samples/sample7_unittest.cc
googletest/samples/sample8_unittest.cc
googletest/samples/sample9_unittest.cc
googletest/scripts/README.md [deleted file]
googletest/scripts/common.py [deleted file]
googletest/scripts/fuse_gtest_files.py [deleted file]
googletest/scripts/gen_gtest_pred_impl.py [deleted file]
googletest/scripts/gtest-config.in [deleted file]
googletest/scripts/release_docs.py [deleted file]
googletest/scripts/run_with_path.py [deleted file]
googletest/scripts/test/Makefile [deleted file]
googletest/scripts/upload.py [deleted file]
googletest/scripts/upload_gtest.py [deleted file]
googletest/src/gtest-all.cc
googletest/src/gtest-assertion-result.cc [new file with mode: 0644]
googletest/src/gtest-death-test.cc
googletest/src/gtest-filepath.cc
googletest/src/gtest-internal-inl.h
googletest/src/gtest-matchers.cc
googletest/src/gtest-port.cc
googletest/src/gtest-printers.cc
googletest/src/gtest-test-part.cc
googletest/src/gtest-typed-test.cc
googletest/src/gtest.cc
googletest/src/gtest_main.cc
googletest/test/BUILD.bazel
googletest/test/googletest-break-on-failure-unittest.py
googletest/test/googletest-break-on-failure-unittest_.cc
googletest/test/googletest-catch-exceptions-test.py
googletest/test/googletest-catch-exceptions-test_.cc
googletest/test/googletest-color-test.py
googletest/test/googletest-color-test_.cc
googletest/test/googletest-death-test-test.cc
googletest/test/googletest-death-test_ex_test.cc
googletest/test/googletest-env-var-test.py
googletest/test/googletest-env-var-test_.cc
googletest/test/googletest-failfast-unittest.py
googletest/test/googletest-failfast-unittest_.cc
googletest/test/googletest-filepath-test.cc
googletest/test/googletest-filter-unittest.py
googletest/test/googletest-filter-unittest_.cc
googletest/test/googletest-global-environment-unittest.py
googletest/test/googletest-json-outfiles-test.py
googletest/test/googletest-json-output-unittest.py
googletest/test/googletest-list-tests-unittest.py
googletest/test/googletest-list-tests-unittest_.cc
googletest/test/googletest-listener-test.cc
googletest/test/googletest-message-test.cc
googletest/test/googletest-options-test.cc
googletest/test/googletest-output-test-golden-lin.txt
googletest/test/googletest-output-test.py
googletest/test/googletest-output-test_.cc
googletest/test/googletest-param-test-invalid-name1-test.py
googletest/test/googletest-param-test-invalid-name1-test_.cc
googletest/test/googletest-param-test-invalid-name2-test.py
googletest/test/googletest-param-test-invalid-name2-test_.cc
googletest/test/googletest-param-test-test.cc
googletest/test/googletest-param-test-test.h
googletest/test/googletest-param-test2-test.cc
googletest/test/googletest-port-test.cc
googletest/test/googletest-printers-test.cc
googletest/test/googletest-setuptestsuite-test.py
googletest/test/googletest-setuptestsuite-test_.cc
googletest/test/googletest-shuffle-test.py
googletest/test/googletest-shuffle-test_.cc
googletest/test/googletest-test-part-test.cc
googletest/test/googletest-throw-on-failure-test.py
googletest/test/googletest-throw-on-failure-test_.cc
googletest/test/googletest-uninitialized-test.py
googletest/test/googletest-uninitialized-test_.cc
googletest/test/gtest-typed-test2_test.cc
googletest/test/gtest-typed-test_test.cc
googletest/test/gtest-typed-test_test.h
googletest/test/gtest-unittest-api_test.cc
googletest/test/gtest_assert_by_exception_test.cc
googletest/test/gtest_environment_test.cc
googletest/test/gtest_help_test.py
googletest/test/gtest_help_test_.cc
googletest/test/gtest_json_test_utils.py
googletest/test/gtest_list_output_unittest.py
googletest/test/gtest_main_unittest.cc
googletest/test/gtest_pred_impl_unittest.cc
googletest/test/gtest_premature_exit_test.cc
googletest/test/gtest_repeat_test.cc
googletest/test/gtest_skip_check_output_test.py
googletest/test/gtest_skip_environment_check_output_test.py
googletest/test/gtest_skip_in_environment_setup_test.cc
googletest/test/gtest_skip_test.cc
googletest/test/gtest_sole_header_test.cc
googletest/test/gtest_stress_test.cc
googletest/test/gtest_test_macro_stack_footprint_test.cc
googletest/test/gtest_test_utils.py
googletest/test/gtest_testbridge_test.py
googletest/test/gtest_testbridge_test_.cc
googletest/test/gtest_throw_on_failure_ex_test.cc
googletest/test/gtest_unittest.cc
googletest/test/gtest_xml_outfiles_test.py
googletest/test/gtest_xml_output_unittest.py
googletest/test/gtest_xml_output_unittest_.cc
googletest/test/gtest_xml_test_utils.py
googletest/test/production.h
library.json [deleted file]

diff --git a/.github/workflows/gtest-ci.yml b/.github/workflows/gtest-ci.yml
new file mode 100644 (file)
index 0000000..61fd47e
--- /dev/null
@@ -0,0 +1,40 @@
+name: ci
+
+on:
+  push:
+  pull_request:
+
+jobs:
+  Linux:
+    runs-on: ubuntu-latest
+    steps:
+
+    - uses: actions/checkout@v2
+      with:
+        fetch-depth: 0
+
+    - name: Tests
+      run: bazel test --test_output=errors //...
+
+  MacOs:
+    runs-on: macos-latest
+    steps:
+
+    - uses: actions/checkout@v2
+      with:
+        fetch-depth: 0
+
+    - name: Tests
+      run: bazel test --test_output=errors //...
+
+
+  Windows:
+    runs-on: windows-latest
+    steps:
+
+    - uses: actions/checkout@v2
+      with:
+        fetch-depth: 0
+
+    - name: Tests
+      run: bazel test --test_output=errors //...
index 965c518d7a7c4e2a4f642706e8fc57a9542ca14f..ac62251e10172614d93b385777e52defc187cac4 100644 (file)
 #
 #   Bazel Build for Google C++ Testing Framework(Google Test)
 
-load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
-
 package(default_visibility = ["//visibility:public"])
 
 licenses(["notice"])
 
 exports_files(["LICENSE"])
 
+config_setting(
+    name = "qnx",
+    constraint_values = ["@platforms//os:qnx"],
+)
+
 config_setting(
     name = "windows",
     constraint_values = ["@platforms//os:windows"],
 )
 
+config_setting(
+    name = "freebsd",
+    constraint_values = ["@platforms//os:freebsd"],
+)
+
+config_setting(
+    name = "openbsd",
+    constraint_values = ["@platforms//os:openbsd"],
+)
+
 config_setting(
     name = "msvc_compiler",
     flag_values = {
@@ -86,6 +99,7 @@ cc_library(
         "googlemock/include/gmock/*.h",
     ]),
     copts = select({
+        ":qnx": [],
         ":windows": [],
         "//conditions:default": ["-pthread"],
     }),
@@ -104,7 +118,16 @@ cc_library(
         "googletest/include",
     ],
     linkopts = select({
+        ":qnx": ["-lregex"],
         ":windows": [],
+        ":freebsd": [
+            "-lm",
+            "-pthread",
+        ],
+        ":openbsd": [
+            "-lm",
+            "-pthread",
+        ],
         "//conditions:default": ["-pthread"],
     }),
     deps = select({
@@ -112,10 +135,15 @@ cc_library(
             "@com_google_absl//absl/debugging:failure_signal_handler",
             "@com_google_absl//absl/debugging:stacktrace",
             "@com_google_absl//absl/debugging:symbolize",
+            "@com_google_absl//absl/flags:flag",
+            "@com_google_absl//absl/flags:parse",
+            "@com_google_absl//absl/flags:reflection",
+            "@com_google_absl//absl/flags:usage",
             "@com_google_absl//absl/strings",
             "@com_google_absl//absl/types:any",
             "@com_google_absl//absl/types:optional",
             "@com_google_absl//absl/types:variant",
+            "@com_googlesource_code_re2//:re2",
         ],
         "//conditions:default": [],
     }),
index ea81ab1292d0b9099ac389b6c71885b0e6a1d034..4daf35b546c5a36dc8d7af93e4f818dda4c50edd 100644 (file)
@@ -1,19 +1,21 @@
 # Note: CMake support is community-based. The maintainers do not use CMake
 # internally.
 
-cmake_minimum_required(VERSION 2.8.12)
+cmake_minimum_required(VERSION 3.5)
 
 if (POLICY CMP0048)
   cmake_policy(SET CMP0048 NEW)
 endif (POLICY CMP0048)
 
+if (POLICY CMP0077)
+  cmake_policy(SET CMP0077 NEW)
+endif (POLICY CMP0077)
+
 project(googletest-distribution)
 set(GOOGLETEST_VERSION 1.11.0)
 
-if (CMAKE_VERSION VERSION_GREATER "3.0.2")
-  if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX)
-    set(CMAKE_CXX_EXTENSIONS OFF)
-  endif()
+if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX)
+  set(CMAKE_CXX_EXTENSIONS OFF)
 endif()
 
 enable_testing()
index da45e4450ce7f155f809f058b6f8a9d05d7642ce..b3f50436e55ba74da6907d1d1f8696f899f4eb1f 100644 (file)
@@ -21,8 +21,8 @@ accept your pull requests.
 
 ## Are you a Googler?
 
-If you are a Googler, please make an attempt to submit an internal change rather
-than a GitHub Pull Request. If you are not able to submit an internal change a
+If you are a Googler, please make an attempt to submit an internal contribution
+rather than a GitHub Pull Request. If you are not able to submit internally, a
 PR is acceptable as an alternative.
 
 ## Contributing A Patch
@@ -36,7 +36,8 @@ PR is acceptable as an alternative.
     This ensures that work isn't being duplicated and communicating your plan
     early also generally leads to better patches.
 4.  If your proposed change is accepted, and you haven't already done so, sign a
-    Contributor License Agreement (see details above).
+    Contributor License Agreement
+    ([see details above](#contributor-license-agreements)).
 5.  Fork the desired repo, develop and test your code changes.
 6.  Ensure that your code adheres to the existing style in the sample to which
     you are contributing.
index 76db0b40ffb3fe70d5f321d78eade1d1e226fc43..77397a5b53fea5352f8af38bdb1c4a0ce0e30d66 100644 (file)
@@ -34,6 +34,7 @@ Manuel Klimek <klimek@google.com>
 Mario Tanev <radix@google.com>
 Mark Paskin
 Markus Heule <markus.heule@gmail.com>
+Martijn Vels <mvels@google.com>
 Matthew Simmons <simmonmt@acm.org>
 Mika Raento <mikie@iki.fi>
 Mike Bland <mbland@google.com>
@@ -55,6 +56,7 @@ Russ Rufer <russ@pentad.com>
 Sean Mcafee <eefacm@gmail.com>
 Sigurður Ásgeirsson <siggi@google.com>
 Sverre Sundsdal <sundsdal@gmail.com>
+Szymon Sobik <sobik.szymon@gmail.com>
 Takeshi Yoshino <tyoshino@google.com>
 Tracy Bialik <tracy@pentad.com>
 Vadim Berman <vadimb@google.com>
index 7d872a57ed456934329d0872d42fb5e6c30def7e..30edaecf313a04bd5653c4701dfc0ec32ab2215c 100644 (file)
--- a/README.md
+++ b/README.md
@@ -6,7 +6,8 @@
 
 GoogleTest now follows the
 [Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support).
-We recommend using the latest commit in the `master` branch in your projects.
+We recommend
+[updating to the latest commit in the `main` branch as often as possible](https://github.com/abseil/abseil-cpp/blob/master/FAQ.md#what-is-live-at-head-and-how-do-i-do-it).
 
 #### Documentation Updates
 
@@ -14,9 +15,9 @@ Our documentation is now live on GitHub Pages at
 https://google.github.io/googletest/. We recommend browsing the documentation on
 GitHub Pages rather than directly in the repository.
 
-#### Release 1.10.x
+#### Release 1.11.0
 
-[Release 1.10.x](https://github.com/google/googletest/releases/tag/release-1.10.0)
+[Release 1.11.0](https://github.com/google/googletest/releases/tag/release-1.11.0)
 is now available.
 
 #### Coming Soon
@@ -109,8 +110,8 @@ Windows and Linux platforms.
 
 [GoogleTest UI](https://github.com/ospector/gtest-gbar) is a test runner that
 runs your test binary, allows you to track its progress via a progress bar, and
-displays a list of test failures. Clicking on one shows failure text. Google
-Test UI is written in C#.
+displays a list of test failures. Clicking on one shows failure text. GoogleTest
+UI is written in C#.
 
 [GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event
 listener for GoogleTest that implements the
@@ -121,11 +122,11 @@ result output. If your test runner understands TAP, you may find it useful.
 runs tests from your binary in parallel to provide significant speed-up.
 
 [GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter)
-is a VS Code extension allowing to view GoogleTest in a tree view, and run/debug
+is a VS Code extension allowing to view GoogleTest in a tree view and run/debug
 your tests.
 
 [C++ TestMate](https://github.com/matepek/vscode-catch2-test-adapter) is a VS
-Code extension allowing to view GoogleTest in a tree view, and run/debug your
+Code extension allowing to view GoogleTest in a tree view and run/debug your
 tests.
 
 [Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser
index 614f55778e6e1f33235300fe60cbe167c2c34845..4d7b3988a23d98e1eb2af9065533add45ba6ee3a 100644 (file)
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -4,21 +4,36 @@ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
 
 http_archive(
     name = "com_google_absl",
-    urls = ["https://github.com/abseil/abseil-cpp/archive/7971fb358ae376e016d2d4fc9327aad95659b25e.zip"],  # 2021-05-20T02:59:16Z
-    strip_prefix = "abseil-cpp-7971fb358ae376e016d2d4fc9327aad95659b25e",
-    sha256 = "aeba534f7307e36fe084b452299e49b97420667a8d28102cf9a0daeed340b859",
+    sha256 = "1a1745b5ee81392f5ea4371a4ca41e55d446eeaee122903b2eaffbd8a3b67a2b",
+    strip_prefix = "abseil-cpp-01cc6567cff77738e416a7ddc17de2d435a780ce",
+    urls = ["https://github.com/abseil/abseil-cpp/archive/01cc6567cff77738e416a7ddc17de2d435a780ce.zip"],  # 2022-06-21T19:28:27Z
 )
 
+# Note this must use a commit from the `abseil` branch of the RE2 project.
+# https://github.com/google/re2/tree/abseil
 http_archive(
-  name = "rules_cc",
-  urls = ["https://github.com/bazelbuild/rules_cc/archive/68cb652a71e7e7e2858c50593e5a9e3b94e5b9a9.zip"],  # 2021-05-14T14:51:14Z
-  strip_prefix = "rules_cc-68cb652a71e7e7e2858c50593e5a9e3b94e5b9a9",
-  sha256 = "1e19e9a3bc3d4ee91d7fcad00653485ee6c798efbbf9588d40b34cbfbded143d",
+    name = "com_googlesource_code_re2",
+    sha256 = "0a890c2aa0bb05b2ce906a15efb520d0f5ad4c7d37b8db959c43772802991887",
+    strip_prefix = "re2-a427f10b9fb4622dd6d8643032600aa1b50fbd12",
+    urls = ["https://github.com/google/re2/archive/a427f10b9fb4622dd6d8643032600aa1b50fbd12.zip"],  # 2022-06-09
 )
 
 http_archive(
-  name = "rules_python",
-  urls = ["https://github.com/bazelbuild/rules_python/archive/ed6cc8f2c3692a6a7f013ff8bc185ba77eb9b4d2.zip"],  # 2021-05-17T00:24:16Z
-  strip_prefix = "rules_python-ed6cc8f2c3692a6a7f013ff8bc185ba77eb9b4d2",
-  sha256 = "98b3c592faea9636ac8444bfd9de7f3fb4c60590932d6e6ac5946e3f8dbd5ff6",
+    name = "rules_python",
+    sha256 = "0b460f17771258341528753b1679335b629d1d25e3af28eda47d009c103a6e15",
+    strip_prefix = "rules_python-aef17ad72919d184e5edb7abf61509eb78e57eda",
+    urls = ["https://github.com/bazelbuild/rules_python/archive/aef17ad72919d184e5edb7abf61509eb78e57eda.zip"],  # 2022-06-21T23:44:47Z
+)
+
+http_archive(
+    name = "bazel_skylib",
+    urls = ["https://github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz"],
+    sha256 = "f7be3474d42aae265405a592bb7da8e171919d74c16f082a5457840f06054728",
+)
+
+http_archive(
+    name = "platforms",
+    sha256 = "a879ea428c6d56ab0ec18224f976515948822451473a80d06c2e50af0bbe5121",
+    strip_prefix = "platforms-da5541f26b7de1dc8e04c075c99df5351742a4a2",
+    urls = ["https://github.com/bazelbuild/platforms/archive/da5541f26b7de1dc8e04c075c99df5351742a4a2.zip"],  # 2022-05-27
 )
index 6bea1cde26aff516d6b7a3780fcdecacb5376388..0ee56704170725348589ca4428caf087ac6959fd 100644 (file)
@@ -31,8 +31,8 @@
 
 set -euox pipefail
 
-readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20210525"
-readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20201015"
+readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20220217"
+readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20220621"
 
 if [[ -z ${GTEST_ROOT:-} ]]; then
   GTEST_ROOT="$(realpath $(dirname ${0})/..)"
@@ -76,7 +76,9 @@ time docker run \
     /usr/local/bin/bazel test ... \
       --copt="-Wall" \
       --copt="-Werror" \
+      --copt="-Wuninitialized" \
       --copt="-Wno-error=pragmas" \
+      --distdir="/bazel-distdir" \
       --keep_going \
       --show_timestamps \
       --test_output=errors
@@ -94,6 +96,7 @@ for std in ${STD}; do
       /usr/local/bin/bazel test ... \
         --copt="-Wall" \
         --copt="-Werror" \
+        --copt="-Wuninitialized" \
         --define="absl=${absl}" \
         --distdir="/bazel-distdir" \
         --keep_going \
@@ -116,6 +119,7 @@ for std in ${STD}; do
         --copt="--gcc-toolchain=/usr/local" \
         --copt="-Wall" \
         --copt="-Werror" \
+        --copt="-Wuninitialized" \
         --define="absl=${absl}" \
         --distdir="/bazel-distdir" \
         --keep_going \
index 8dff5ba1508085ae5b26a2716985eb669a90ebd8..9a752b922ab522cfb3cfffccc49a03c88a554282 100644 (file)
@@ -157,8 +157,11 @@ that can be used in the predicate assertion macro
 example:
 
 ```c++
-EXPECT_PRED_FORMAT2(testing::FloatLE, val1, val2);
-EXPECT_PRED_FORMAT2(testing::DoubleLE, val1, val2);
+using ::testing::FloatLE;
+using ::testing::DoubleLE;
+...
+EXPECT_PRED_FORMAT2(FloatLE, val1, val2);
+EXPECT_PRED_FORMAT2(DoubleLE, val1, val2);
 ```
 
 The above code verifies that `val1` is less than, or approximately equal to,
@@ -202,10 +205,9 @@ You can call the function
 
 to assert that types `T1` and `T2` are the same. The function does nothing if
 the assertion is satisfied. If the types are different, the function call will
-fail to compile, the compiler error message will say that
-`T1 and T2 are not the same type` and most likely (depending on the compiler)
-show you the actual values of `T1` and `T2`. This is mainly useful inside
-template code.
+fail to compile, the compiler error message will say that `T1 and T2 are not the
+same type` and most likely (depending on the compiler) show you the actual
+values of `T1` and `T2`. This is mainly useful inside template code.
 
 **Caveat**: When used inside a member function of a class template or a function
 template, `StaticAssertTypeEq<T1, T2>()` is effective only if the function is
@@ -383,10 +385,10 @@ EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))
 ## Death Tests
 
 In many applications, there are assertions that can cause application failure if
-a condition is not met. These sanity checks, which ensure that the program is in
-a known good state, are there to fail at the earliest possible time after some
-program state is corrupted. If the assertion checks the wrong condition, then
-the program may proceed in an erroneous state, which could lead to memory
+a condition is not met. These consistency checks, which ensure that the program
+is in a known good state, are there to fail at the earliest possible time after
+some program state is corrupted. If the assertion checks the wrong condition,
+then the program may proceed in an erroneous state, which could lead to memory
 corruption, security holes, or worse. Hence it is vitally important to test that
 such assertion statements work as expected.
 
@@ -480,9 +482,11 @@ TEST_F(FooDeathTest, DoesThat) {
 
 ### Regular Expression Syntax
 
-On POSIX systems (e.g. Linux, Cygwin, and Mac), googletest uses the
+When built with Bazel and using Abseil, googletest uses the
+[RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX
+systems (Linux, Cygwin, Mac), googletest uses the
 [POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)
-syntax. To learn about this syntax, you may want to read this
+syntax. To learn about POSIX syntax, you may want to read this
 [Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions).
 
 On Windows, googletest uses its own simple regular expression implementation. It
@@ -558,7 +562,7 @@ The automated testing framework does not set the style flag. You can choose a
 particular style of death tests by setting the flag programmatically:
 
 ```c++
-testing::FLAGS_gtest_death_test_style="threadsafe"
+GTEST_FLAG_SET(death_test_style, "threadsafe")
 ```
 
 You can do this in `main()` to set the style for all death tests in the binary,
@@ -568,12 +572,12 @@ restored afterwards, so you need not do that yourself. For example:
 ```c++
 int main(int argc, char** argv) {
   testing::InitGoogleTest(&argc, argv);
-  testing::FLAGS_gtest_death_test_style = "fast";
+  GTEST_FLAG_SET(death_test_style, "fast");
   return RUN_ALL_TESTS();
 }
 
 TEST(MyDeathTest, TestOne) {
-  testing::FLAGS_gtest_death_test_style = "threadsafe";
+  GTEST_FLAG_SET(death_test_style, "threadsafe");
   // This test is run in the "threadsafe" style:
   ASSERT_DEATH(ThisShouldDie(), "");
 }
@@ -610,15 +614,14 @@ Despite the improved thread safety afforded by the "threadsafe" style of death
 test, thread problems such as deadlock are still possible in the presence of
 handlers registered with `pthread_atfork(3)`.
 
-
 ## Using Assertions in Sub-routines
 
 {: .callout .note}
 Note: If you want to put a series of test assertions in a subroutine to check
 for a complex condition, consider using
-[a custom GMock matcher](gmock_cook_book.md#NewMatchers)
-instead. This lets you provide a more readable error message in case of failure
-and avoid all of the issues described below.
+[a custom GMock matcher](gmock_cook_book.md#NewMatchers) instead. This lets you
+provide a more readable error message in case of failure and avoid all of the
+issues described below.
 
 ### Adding Traces to Assertions
 
@@ -631,6 +634,7 @@ the `SCOPED_TRACE` macro or the `ScopedTrace` utility:
 ```c++
 SCOPED_TRACE(message);
 ```
+
 ```c++
 ScopedTrace trace("file_path", line_number, message);
 ```
@@ -837,7 +841,7 @@ will output XML like this:
 
 ```xml
   ...
-    <testcase name="MinAndMaxWidgets" status="run" time="0.006" classname="WidgetUsageTest" MaximumWidgets="12" MinimumWidgets="9" />
+    <testcase name="MinAndMaxWidgets" file="test.cpp" line="1" status="run" time="0.006" classname="WidgetUsageTest" MaximumWidgets="12" MinimumWidgets="9" />
   ...
 ```
 
@@ -888,6 +892,12 @@ preceding or following another. Also, the tests must either not modify the state
 of any shared resource, or, if they do modify the state, they must restore the
 state to its original value before passing control to the next test.
 
+Note that `SetUpTestSuite()` may be called multiple times for a test fixture
+class that has derived classes, so you should not expect code in the function
+body to be run only once. Also, derived classes still have access to shared
+resources defined as static members, so careful consideration is needed when
+managing shared resources to avoid memory leaks.
+
 Here's an example of per-test-suite set-up and tear-down:
 
 ```c++
@@ -897,7 +907,10 @@ class FooTest : public testing::Test {
   // Called before the first test in this test suite.
   // Can be omitted if not needed.
   static void SetUpTestSuite() {
-    shared_resource_ = new ...;
+    // Avoid reallocating static objects if called in subclasses of FooTest.
+    if (shared_resource_ == nullptr) {
+      shared_resource_ = new ...;
+    }
   }
 
   // Per-test-suite tear-down.
@@ -1302,6 +1315,7 @@ First, define a fixture class template, as we did with typed tests:
 ```c++
 template <typename T>
 class FooTest : public testing::Test {
+  void DoSomethingInteresting();
   ...
 };
 ```
@@ -1319,6 +1333,9 @@ this as many times as you want:
 TYPED_TEST_P(FooTest, DoesBlah) {
   // Inside a test, refer to TypeParam to get the type parameter.
   TypeParam n = 0;
+
+  // You will need to use `this` explicitly to refer to fixture members.
+  this->DoSomethingInteresting()
   ...
 }
 
@@ -1481,8 +1498,8 @@ In frameworks that report a failure by throwing an exception, you could catch
 the exception and assert on it. But googletest doesn't use exceptions, so how do
 we test that a piece of code generates an expected failure?
 
-`"gtest/gtest-spi.h"` contains some constructs to do this. After #including this header,
-you can use
+`"gtest/gtest-spi.h"` contains some constructs to do this.
+After #including this header, you can use
 
 ```c++
   EXPECT_FATAL_FAILURE(statement, substring);
@@ -1586,12 +1603,14 @@ void RegisterMyTests(const std::vector<int>& values) {
 }
 ...
 int main(int argc, char** argv) {
+  testing::InitGoogleTest(&argc, argv);
   std::vector<int> values_to_test = LoadValuesFromConfig();
   RegisterMyTests(values_to_test);
   ...
   return RUN_ALL_TESTS();
 }
 ```
+
 ## Getting the Current Test's Name
 
 Sometimes a function may need to know the name of the currently running test.
@@ -1816,8 +1835,7 @@ By default, a googletest program runs all tests the user has defined. In some
 cases (e.g. iterative test development & execution) it may be desirable stop
 test execution upon first failure (trading improved latency for completeness).
 If `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set,
-the test runner will stop execution as soon as the first test failure is
-found.
+the test runner will stop execution as soon as the first test failure is found.
 
 #### Temporarily Disabling Tests
 
@@ -1911,6 +1929,58 @@ time.
 If you combine this with `--gtest_repeat=N`, googletest will pick a different
 random seed and re-shuffle the tests in each iteration.
 
+### Distributing Test Functions to Multiple Machines
+
+If you have more than one machine you can use to run a test program, you might
+want to run the test functions in parallel and get the result faster. We call
+this technique *sharding*, where each machine is called a *shard*.
+
+GoogleTest is compatible with test sharding. To take advantage of this feature,
+your test runner (not part of GoogleTest) needs to do the following:
+
+1.  Allocate a number of machines (shards) to run the tests.
+1.  On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total
+    number of shards. It must be the same for all shards.
+1.  On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index
+    of the shard. Different shards must be assigned different indices, which
+    must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`.
+1.  Run the same test program on all shards. When GoogleTest sees the above two
+    environment variables, it will select a subset of the test functions to run.
+    Across all shards, each test function in the program will be run exactly
+    once.
+1.  Wait for all shards to finish, then collect and report the results.
+
+Your project may have tests that were written without GoogleTest and thus don't
+understand this protocol. In order for your test runner to figure out which test
+supports sharding, it can set the environment variable `GTEST_SHARD_STATUS_FILE`
+to a non-existent file path. If a test program supports sharding, it will create
+this file to acknowledge that fact; otherwise it will not create it. The actual
+contents of the file are not important at this time, although we may put some
+useful information in it in the future.
+
+Here's an example to make it clear. Suppose you have a test program `foo_test`
+that contains the following 5 test functions:
+
+```
+TEST(A, V)
+TEST(A, W)
+TEST(B, X)
+TEST(B, Y)
+TEST(B, Z)
+```
+
+Suppose you have 3 machines at your disposal. To run the test functions in
+parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and set
+`GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. Then you would
+run the same `foo_test` on each machine.
+
+GoogleTest reserves the right to change how the work is distributed across the
+shards, but here's one possible scenario:
+
+*   Machine #0 runs `A.V` and `B.X`.
+*   Machine #1 runs `A.W` and `B.Y`.
+*   Machine #2 runs `B.Z`.
+
 ### Controlling Test Output
 
 #### Colored Terminal Output
@@ -1965,8 +2035,6 @@ text because, for example, you don't have an UTF-8 compatible output medium, run
 the test program with `--gtest_print_utf8=0` or set the `GTEST_PRINT_UTF8`
 environment variable to `0`.
 
-
-
 #### Generating an XML Report
 
 googletest can emit a detailed XML report to a file in addition to its normal
@@ -2020,15 +2088,15 @@ could generate this report:
 <?xml version="1.0" encoding="UTF-8"?>
 <testsuites tests="3" failures="1" errors="0" time="0.035" timestamp="2011-10-31T18:52:42" name="AllTests">
   <testsuite name="MathTest" tests="2" failures="1" errors="0" time="0.015">
-    <testcase name="Addition" status="run" time="0.007" classname="">
+    <testcase name="Addition" file="test.cpp" line="1" status="run" time="0.007" classname="">
       <failure message="Value of: add(1, 1)&#x0A;  Actual: 3&#x0A;Expected: 2" type="">...</failure>
       <failure message="Value of: add(1, -1)&#x0A;  Actual: 1&#x0A;Expected: 0" type="">...</failure>
     </testcase>
-    <testcase name="Subtraction" status="run" time="0.005" classname="">
+    <testcase name="Subtraction" file="test.cpp" line="2" status="run" time="0.005" classname="">
     </testcase>
   </testsuite>
   <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="0.005">
-    <testcase name="NonContradiction" status="run" time="0.005" classname="">
+    <testcase name="NonContradiction" file="test.cpp" line="3" status="run" time="0.005" classname="">
     </testcase>
   </testsuite>
 </testsuites>
@@ -2046,6 +2114,9 @@ Things to note:
 *   The `timestamp` attribute records the local date and time of the test
     execution.
 
+*   The `file` and `line` attributes record the source file location, where the
+    test was defined.
+
 *   Each `<failure>` element corresponds to a single failed googletest
     assertion.
 
@@ -2085,6 +2156,8 @@ The report format conforms to the following JSON Schema:
       "type": "object",
       "properties": {
         "name": { "type": "string" },
+        "file": { "type": "string" },
+        "line": { "type": "integer" },
         "status": {
           "type": "string",
           "enum": ["RUN", "NOTRUN"]
@@ -2162,6 +2235,8 @@ message TestCase {
 
 message TestInfo {
   string name = 1;
+  string file = 6;
+  int32 line = 7;
   enum Status {
     RUN = 0;
     NOTRUN = 1;
@@ -2205,6 +2280,8 @@ could generate this report:
       "testsuite": [
         {
           "name": "Addition",
+          "file": "test.cpp",
+          "line": 1,
           "status": "RUN",
           "time": "0.007s",
           "classname": "",
@@ -2221,6 +2298,8 @@ could generate this report:
         },
         {
           "name": "Subtraction",
+          "file": "test.cpp",
+          "line": 2,
           "status": "RUN",
           "time": "0.005s",
           "classname": ""
@@ -2236,6 +2315,8 @@ could generate this report:
       "testsuite": [
         {
           "name": "NonContradiction",
+          "file": "test.cpp",
+          "line": 3,
           "status": "RUN",
           "time": "0.005s",
           "classname": ""
@@ -2253,12 +2334,11 @@ IMPORTANT: The exact format of the JSON document is subject to change.
 
 #### Detecting Test Premature Exit
 
-Google Test implements the _premature-exit-file_ protocol for test runners
-to catch any kind of unexpected exits of test programs. Upon start,
-Google Test creates the file which will be automatically deleted after
-all work has been finished. Then, the test runner can check if this file
-exists. In case the file remains undeleted, the inspected test has exited
-prematurely.
+Google Test implements the _premature-exit-file_ protocol for test runners to
+catch any kind of unexpected exits of test programs. Upon start, Google Test
+creates the file which will be automatically deleted after all work has been
+finished. Then, the test runner can check if this file exists. In case the file
+remains undeleted, the inspected test has exited prematurely.
 
 This feature is enabled only if the `TEST_PREMATURE_EXIT_FILE` environment
 variable has been set.
index 9042da1efb43a6bf0893275bb8c84e544c01c2a1..c849aff9232f8dd14672ea16883c65a844f503c6 100644 (file)
@@ -1,9 +1,9 @@
-# Googletest FAQ
+# GoogleTest FAQ
 
 ## Why should test suite names and test names not contain underscore?
 
 {: .callout .note}
-Note: Googletest reserves underscore (`_`) for special purpose keywords, such as
+Note: GoogleTest reserves underscore (`_`) for special purpose keywords, such as
 [the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition
 to the following rationale.
 
@@ -50,15 +50,15 @@ Now, the two `TEST`s will both generate the same class
 
 So for simplicity, we just ask the users to avoid `_` in `TestSuiteName` and
 `TestName`. The rule is more constraining than necessary, but it's simple and
-easy to remember. It also gives googletest some wiggle room in case its
+easy to remember. It also gives GoogleTest some wiggle room in case its
 implementation needs to change in the future.
 
 If you violate the rule, there may not be immediate consequences, but your test
 may (just may) break with a new compiler (or a new version of the compiler you
-are using) or with a new version of googletest. Therefore it's best to follow
+are using) or with a new version of GoogleTest. Therefore it's best to follow
 the rule.
 
-## Why does googletest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`?
+## Why does GoogleTest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`?
 
 First of all, you can use `nullptr` with each of these macros, e.g.
 `EXPECT_EQ(ptr, nullptr)`, `EXPECT_NE(ptr, nullptr)`, `ASSERT_EQ(ptr, nullptr)`,
@@ -68,7 +68,7 @@ because `nullptr` does not have the type problems that `NULL` does.
 Due to some peculiarity of C++, it requires some non-trivial template meta
 programming tricks to support using `NULL` as an argument of the `EXPECT_XX()`
 and `ASSERT_XX()` macros. Therefore we only do it where it's most needed
-(otherwise we make the implementation of googletest harder to maintain and more
+(otherwise we make the implementation of GoogleTest harder to maintain and more
 error-prone than necessary).
 
 Historically, the `EXPECT_EQ()` macro took the *expected* value as its first
@@ -162,7 +162,7 @@ methods, the parent process will think the calls have never occurred. Therefore,
 you may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH`
 macro.
 
-## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a googletest bug?
+## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a GoogleTest bug?
 
 Actually, the bug is in `htonl()`.
 
@@ -199,7 +199,7 @@ const int Foo::kBar;  // No initializer here.
 ```
 
 Otherwise your code is **invalid C++**, and may break in unexpected ways. In
-particular, using it in googletest comparison assertions (`EXPECT_EQ`, etc) will
+particular, using it in GoogleTest comparison assertions (`EXPECT_EQ`, etc) will
 generate an "undefined reference" linker error. The fact that "it used to work"
 doesn't mean it's valid. It just means that you were lucky. :-)
 
@@ -225,7 +225,7 @@ cases may want to use the same or slightly different fixtures. For example, you
 may want to make sure that all of a GUI library's test suites don't leak
 important system resources like fonts and brushes.
 
-In googletest, you share a fixture among test suites by putting the shared logic
+In GoogleTest, you share a fixture among test suites by putting the shared logic
 in a base test fixture, then deriving from that base a separate fixture for each
 test suite that wants to use this common logic. You then use `TEST_F()` to write
 tests using each derived fixture.
@@ -264,7 +264,7 @@ TEST_F(FooTest, Baz) { ... }
 ```
 
 If necessary, you can continue to derive test fixtures from a derived fixture.
-googletest has no limit on how deep the hierarchy can be.
+GoogleTest has no limit on how deep the hierarchy can be.
 
 For a complete example using derived test fixtures, see
 [sample5_unittest.cc](https://github.com/google/googletest/blob/master/googletest/samples/sample5_unittest.cc).
@@ -278,7 +278,7 @@ disabled by our build system. Please see more details
 
 ## My death test hangs (or seg-faults). How do I fix it?
 
-In googletest, death tests are run in a child process and the way they work is
+In GoogleTest, death tests are run in a child process and the way they work is
 delicate. To write death tests you really need to understand how they work—see
 the details at [Death Assertions](reference/assertions.md#death) in the
 Assertions Reference.
@@ -305,8 +305,8 @@ bullet - sorry!
 
 ## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp}
 
-The first thing to remember is that googletest does **not** reuse the same test
-fixture object across multiple tests. For each `TEST_F`, googletest will create
+The first thing to remember is that GoogleTest does **not** reuse the same test
+fixture object across multiple tests. For each `TEST_F`, GoogleTest will create
 a **fresh** test fixture object, immediately call `SetUp()`, run the test body,
 call `TearDown()`, and then delete the test fixture object.
 
@@ -328,7 +328,7 @@ You may still want to use `SetUp()/TearDown()` in the following cases:
 
 *   C++ does not allow virtual function calls in constructors and destructors.
     You can call a method declared as virtual, but it will not use dynamic
-    dispatch, it will use the definition from the class the constructor of which
+    dispatch. It will use the definition from the class the constructor of which
     is currently executing. This is because calling a virtual method before the
     derived class constructor has a chance to run is very dangerous - the
     virtual method might operate on uninitialized data. Therefore, if you need
@@ -345,11 +345,11 @@ You may still want to use `SetUp()/TearDown()` in the following cases:
     that many standard libraries (like STL) may throw when exceptions are
     enabled in the compiler. Therefore you should prefer `TearDown()` if you
     want to write portable tests that work with or without exceptions.
-*   The googletest team is considering making the assertion macros throw on
+*   The GoogleTest team is considering making the assertion macros throw on
     platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux
     client-side), which will eliminate the need for the user to propagate
     failures from a subroutine to its caller. Therefore, you shouldn't use
-    googletest assertions in a destructor if your code could run on such a
+    GoogleTest assertions in a destructor if your code could run on such a
     platform.
 
 ## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it?
@@ -375,7 +375,7 @@ they write
 This is **wrong and dangerous**. The testing services needs to see the return
 value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your
 `main()` function ignores it, your test will be considered successful even if it
-has a googletest assertion failure. Very bad.
+has a GoogleTest assertion failure. Very bad.
 
 We have decided to fix this (thanks to Michael Chastain for the idea). Now, your
 code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with
@@ -410,7 +410,6 @@ C++ is case-sensitive. Did you spell it as `Setup()`?
 Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and
 wonder why it's never called.
 
-
 ## I have several test suites which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious.
 
 You don't have to. Instead of
@@ -441,14 +440,14 @@ TEST_F(BarTest, Abc) { ... }
 TEST_F(BarTest, Def) { ... }
 ```
 
-## googletest output is buried in a whole bunch of LOG messages. What do I do?
+## GoogleTest output is buried in a whole bunch of LOG messages. What do I do?
 
-The googletest output is meant to be a concise and human-friendly report. If
-your test generates textual output itself, it will mix with the googletest
+The GoogleTest output is meant to be a concise and human-friendly report. If
+your test generates textual output itself, it will mix with the GoogleTest
 output, making it hard to read. However, there is an easy solution to this
 problem.
 
-Since `LOG` messages go to stderr, we decided to let googletest output go to
+Since `LOG` messages go to stderr, we decided to let GoogleTest output go to
 stdout. This way, you can easily separate the two using redirection. For
 example:
 
@@ -521,7 +520,7 @@ TEST(MyDeathTest, CompoundStatement) {
 
 ## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why?
 
-Googletest needs to be able to create objects of your test fixture class, so it
+GoogleTest needs to be able to create objects of your test fixture class, so it
 must have a default constructor. Normally the compiler will define one for you.
 However, there are cases where you have to define your own:
 
@@ -546,11 +545,11 @@ The new NPTL thread library doesn't suffer from this problem, as it doesn't
 create a manager thread. However, if you don't control which machine your test
 runs on, you shouldn't depend on this.
 
-## Why does googletest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH?
+## Why does GoogleTest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH?
 
-googletest does not interleave tests from different test suites. That is, it
+GoogleTest does not interleave tests from different test suites. That is, it
 runs all tests in one test suite first, and then runs all tests in the next test
-suite, and so on. googletest does this because it needs to set up a test suite
+suite, and so on. GoogleTest does this because it needs to set up a test suite
 before the first test in it is run, and tear it down afterwards. Splitting up
 the test case would require multiple set-up and tear-down processes, which is
 inefficient and makes the semantics unclean.
@@ -589,11 +588,11 @@ TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
 TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
 ```
 
-## googletest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds?
+## GoogleTest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds?
 
 Printing the LOG messages generated by the statement inside `EXPECT_DEATH()`
 makes it harder to search for real problems in the parent's log. Therefore,
-googletest only prints them when the death test has failed.
+GoogleTest only prints them when the death test has failed.
 
 If you really need to see such LOG messages, a workaround is to temporarily
 break the death test (e.g. by changing the regex pattern it is expected to
@@ -612,7 +611,7 @@ needs to be defined in the *same* name space. See
 
 ## How do I suppress the memory leak messages on Windows?
 
-Since the statically initialized googletest singleton requires allocations on
+Since the statically initialized GoogleTest singleton requires allocations on
 the heap, the Visual C++ memory leak detector will report memory leaks at the
 end of the program run. The easiest way to avoid this is to use the
 `_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
@@ -626,7 +625,7 @@ things accordingly, you are leaking test-only logic into production code and
 there is no easy way to ensure that the test-only code paths aren't run by
 mistake in production. Such cleverness also leads to
 [Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly
-advise against the practice, and googletest doesn't provide a way to do it.
+advise against the practice, and GoogleTest doesn't provide a way to do it.
 
 In general, the recommended way to cause the code to behave differently under
 test is [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection). You can inject
@@ -673,7 +672,7 @@ TEST(CoolTest, DoSomething) {
 ```
 
 However, the following code is **not allowed** and will produce a runtime error
-from googletest because the test methods are using different test fixture
+from GoogleTest because the test methods are using different test fixture
 classes with the same test suite name.
 
 ```c++
index 17ed7a54d80933ec8fce9a0691c958809c2dedb5..67d075dd9ebd9878d5a4d321f50cbc8bfe5315e2 100644 (file)
@@ -8,7 +8,7 @@ Given
 
 ```cpp
 class Foo {
-  ...
+ public:
   virtual ~Foo();
   virtual int GetSize() const = 0;
   virtual string Describe(const char* name) = 0;
@@ -23,7 +23,7 @@ class Foo {
 #include "gmock/gmock.h"
 
 class MockFoo : public Foo {
-  ...
+ public:
   MOCK_METHOD(int, GetSize, (), (const, override));
   MOCK_METHOD(string, Describe, (const char* name), (override));
   MOCK_METHOD(string, Describe, (int type), (override));
@@ -58,7 +58,7 @@ To mock
 ```cpp
 template <typename Elem>
 class StackInterface {
-  ...
+ public:
   virtual ~StackInterface();
   virtual int GetSize() const = 0;
   virtual void Push(const Elem& x) = 0;
@@ -71,7 +71,7 @@ class StackInterface {
 ```cpp
 template <typename Elem>
 class MockStack : public StackInterface<Elem> {
-  ...
+ public:
   MOCK_METHOD(int, GetSize, (), (const, override));
   MOCK_METHOD(void, Push, (const Elem& x), (override));
 };
@@ -230,7 +230,7 @@ class MockFunction<R(A1, ..., An)> {
 };
 ```
 
-See this [recipe](gmock_cook_book.md#using-check-points) for one application of
+See this [recipe](gmock_cook_book.md#UsingCheckPoints) for one application of
 it.
 
 ## Flags
index c08958eb16ab892787db493ac667b83736b1a369..8a11d864f202466de6f284091f9724c3164f097e 100644 (file)
@@ -392,8 +392,7 @@ Old macros and their new equivalents:
 If a mock method has no `EXPECT_CALL` spec but is called, we say that it's an
 "uninteresting call", and the default action (which can be specified using
 `ON_CALL()`) of the method will be taken. Currently, an uninteresting call will
-also by default cause gMock to print a warning. (In the future, we might remove
-this warning by default.)
+also by default cause gMock to print a warning.
 
 However, sometimes you may want to ignore these uninteresting calls, and
 sometimes you may want to treat them as errors. gMock lets you make the decision
@@ -1084,7 +1083,7 @@ using ::testing::Lt;
 ```
 
 says that `Blah` will be called with arguments `x`, `y`, and `z` where `x < y <
-z`. Note that in this example, it wasn't necessary specify the positional
+z`. Note that in this example, it wasn't necessary to specify the positional
 matchers.
 
 As a convenience and example, gMock provides some matchers for 2-tuples,
@@ -1300,23 +1299,27 @@ What if you have a pointer to pointer? You guessed it - you can use nested
 `Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer that points
 to a number less than 3 (what a mouthful...).
 
-### Testing a Certain Property of an Object
+### Defining a Custom Matcher Class {#CustomMatcherClass}
 
-Sometimes you want to specify that an object argument has a certain property,
-but there is no existing matcher that does this. If you want good error
-messages, you should [define a matcher](#NewMatchers). If you want to do it
-quick and dirty, you could get away with writing an ordinary function.
+Most matchers can be simply defined using [the MATCHER* macros](#NewMatchers),
+which are terse and flexible, and produce good error messages. However, these
+macros are not very explicit about the interfaces they create and are not always
+suitable, especially for matchers that will be widely reused.
 
-Let's say you have a mock function that takes an object of type `Foo`, which has
-an `int bar()` method and an `int baz()` method, and you want to constrain that
-the argument's `bar()` value plus its `baz()` value is a given number. Here's
-how you can define a matcher to do it:
+For more advanced cases, you may need to define your own matcher class. A custom
+matcher allows you to test a specific invariant property of that object. Let's
+take a look at how to do so.
 
-```cpp
-using ::testing::Matcher;
+Imagine you have a mock function that takes an object of type `Foo`, which has
+an `int bar()` method and an `int baz()` method. You want to constrain that the
+argument's `bar()` value plus its `baz()` value is a given number. (This is an
+invariant.) Here's how we can write and use a matcher class to do so:
 
+```cpp
 class BarPlusBazEqMatcher {
  public:
+  using is_gtest_matcher = void;
+
   explicit BarPlusBazEqMatcher(int expected_sum)
       : expected_sum_(expected_sum) {}
 
@@ -1325,23 +1328,24 @@ class BarPlusBazEqMatcher {
     return (foo.bar() + foo.baz()) == expected_sum_;
   }
 
-  void DescribeTo(std::ostream& os) const {
-    os << "bar() + baz() equals " << expected_sum_;
+  void DescribeTo(std::ostream* os) const {
+    *os << "bar() + baz() equals " << expected_sum_;
   }
 
-  void DescribeNegationTo(std::ostream& os) const {
-    os << "bar() + baz() does not equal " << expected_sum_;
+  void DescribeNegationTo(std::ostream* os) const {
+    *os << "bar() + baz() does not equal " << expected_sum_;
   }
  private:
   const int expected_sum_;
 };
 
-Matcher<const Foo&> BarPlusBazEq(int expected_sum) {
+::testing::Matcher<const Foo&> BarPlusBazEq(int expected_sum) {
   return BarPlusBazEqMatcher(expected_sum);
 }
 
 ...
-  EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...;
+  Foo foo;
+  EXPECT_CALL(foo, BarPlusBazEq(5))...;
 ```
 
 ### Matching Containers
@@ -1452,7 +1456,7 @@ the pointer is copied. When the last matcher that references the implementation
 object dies, the implementation object will be deleted.
 
 Therefore, if you have some complex matcher that you want to use again and
-again, there is no need to build it everytime. Just assign it to a matcher
+again, there is no need to build it every time. Just assign it to a matcher
 variable and use that variable repeatedly! For example,
 
 ```cpp
@@ -1754,7 +1758,7 @@ specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> C -> D`):
        |
   A ---|
        |
-        +---> C ---> D
+       +---> C ---> D
 ```
 
 This means that A must occur before B and C, and C must occur before D. There's
@@ -1980,6 +1984,7 @@ If the mock method also needs to return a value as well, you can chain
 
 ```cpp
 using ::testing::_;
+using ::testing::DoAll;
 using ::testing::Return;
 using ::testing::SetArgPointee;
 
@@ -2033,10 +2038,7 @@ class MockRolodex : public Rolodex {
 }
 ...
   MockRolodex rolodex;
-  vector<string> names;
-  names.push_back("George");
-  names.push_back("John");
-  names.push_back("Thomas");
+  vector<string> names = {"George", "John", "Thomas"};
   EXPECT_CALL(rolodex, GetNames(_))
       .WillOnce(SetArrayArgument<0>(names.begin(), names.end()));
 ```
@@ -2604,7 +2606,7 @@ efficient. When the last action that references the implementation object dies,
 the implementation object will be deleted.
 
 If you have some complex action that you want to use again and again, you may
-not have to build it from scratch everytime. If the action doesn't have an
+not have to build it from scratch every time. If the action doesn't have an
 internal state (i.e. if it always does the same thing no matter how many times
 it has been called), you can assign it to an action variable and use that
 variable repeatedly. For example:
@@ -3809,22 +3811,19 @@ Cardinality EvenNumber() {
       .Times(EvenNumber());
 ```
 
-### Writing New Actions Quickly {#QuickNewActions}
+### Writing New Actions {#QuickNewActions}
 
 If the built-in actions don't work for you, you can easily define your own one.
-Just define a functor class with a (possibly templated) call operator, matching
-the signature of your action.
+All you need is a call operator with a signature compatible with the mocked
+function. So you can use a lambda:
 
-```cpp
-struct Increment {
-  template <typename T>
-  T operator()(T* arg) {
-    return ++(*arg);
-  }
-}
+```
+MockFunction<int(int)> mock;
+EXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; });
+EXPECT_EQ(14, mock.AsStdFunction()(2));
 ```
 
-The same approach works with stateful functors (or any callable, really):
+Or a struct with a call operator (even a templated one):
 
 ```
 struct MultiplyBy {
@@ -3832,12 +3831,54 @@ struct MultiplyBy {
   T operator()(T arg) { return arg * multiplier; }
 
   int multiplier;
-}
+};
 
 // Then use:
 // EXPECT_CALL(...).WillOnce(MultiplyBy{7});
 ```
 
+It's also fine for the callable to take no arguments, ignoring the arguments
+supplied to the mock function:
+
+```
+MockFunction<int(int)> mock;
+EXPECT_CALL(mock, Call).WillOnce([] { return 17; });
+EXPECT_EQ(17, mock.AsStdFunction()(0));
+```
+
+When used with `WillOnce`, the callable can assume it will be called at most
+once and is allowed to be a move-only type:
+
+```
+// An action that contains move-only types and has an &&-qualified operator,
+// demanding in the type system that it be called at most once. This can be
+// used with WillOnce, but the compiler will reject it if handed to
+// WillRepeatedly.
+struct MoveOnlyAction {
+  std::unique_ptr<int> move_only_state;
+  std::unique_ptr<int> operator()() && { return std::move(move_only_state); }
+};
+
+MockFunction<std::unique_ptr<int>()> mock;
+EXPECT_CALL(mock, Call).WillOnce(MoveOnlyAction{std::make_unique<int>(17)});
+EXPECT_THAT(mock.AsStdFunction()(), Pointee(Eq(17)));
+```
+
+More generally, to use with a mock function whose signature is `R(Args...)` the
+object can be anything convertible to `OnceAction<R(Args...)>` or
+`Action<R(Args...)`>. The difference between the two is that `OnceAction` has
+weaker requirements (`Action` requires a copy-constructible input that can be
+called repeatedly whereas `OnceAction` requires only move-constructible and
+supports `&&`-qualified call operators), but can be used only with `WillOnce`.
+`OnceAction` is typically relevant only when supporting move-only types or
+actions that want a type-system guarantee that they will be called at most once.
+
+Typically the `OnceAction` and `Action` templates need not be referenced
+directly in your actions: a struct or class with a call operator is sufficient,
+as in the examples above. But fancier polymorphic actions that need to know the
+specific return type of the mock function can define templated conversion
+operators to make that possible. See `gmock-actions.h` for examples.
+
 #### Legacy macro-based Actions
 
 Before C++11, the functor-based actions were not supported; the old way of
@@ -4191,7 +4232,7 @@ This implementation class does *not* need to inherit from any particular class.
 What matters is that it must have a `Perform()` method template. This method
 template takes the mock function's arguments as a tuple in a **single**
 argument, and returns the result of the action. It can be either `const` or not,
-but must be invokable with exactly one template argument, which is the result
+but must be invocable with exactly one template argument, which is the result
 type. In other words, you must be able to call `Perform<R>(args)` where `R` is
 the mock function's return type and `args` is its arguments in a tuple.
 
index 2cd9b3f3155966fe078e2f17809eea4b8045c7bd..8f220bf7a8fec033ed9cb827a794397315962fcc 100644 (file)
@@ -369,8 +369,8 @@ Usually, if your action is for a particular function type, defining it using
 different types (e.g. if you are defining `Return(*value*)`),
 `MakePolymorphicAction()` is easiest. Sometimes you want precise control on what
 types of functions the action can be used in, and implementing `ActionInterface`
-is the way to go here. See the implementation of `Return()` in
-`testing/base/public/gmock-actions.h` for an example.
+is the way to go here. See the implementation of `Return()` in `gmock-actions.h`
+for an example.
 
 ### I use SetArgPointee() in WillOnce(), but gcc complains about "conflicting return type specified". What does it mean?
 
index 1f4cc246c483109a494adc7c0b3d0981e061c77b..b7264d3587f71ada659741bd6c47ac015ff46e99 100644 (file)
@@ -190,10 +190,10 @@ Some people put it in a `_test.cc`. This is fine when the interface being mocked
 `Foo` changes it, your test could break. (You can't really expect `Foo`'s
 maintainer to fix every test that uses `Foo`, can you?)
 
-So, the rule of thumb is: if you need to mock `Foo` and it's owned by others,
-define the mock class in `Foo`'s package (better, in a `testing` sub-package
-such that you can clearly separate production code and testing utilities), put
-it in a `.h` and a `cc_library`. Then everyone can reference them from their
+Generally, you should not mock classes you don't own. If you must mock such a
+class owned by others, define the mock class in `Foo`'s Bazel package (usually
+the same directory or a `testing` sub-directory), and put it in a `.h` and a
+`cc_library` with `testonly=True`. Then everyone can reference them from their
 tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and
 only tests that depend on the changed methods need to be fixed.
 
@@ -480,8 +480,8 @@ the *default* action for the function every time (unless, of course, you have a
 `WillRepeatedly()`.).
 
 What can we do inside `WillOnce()` besides `Return()`? You can return a
-reference using `ReturnRef(*variable*)`, or invoke a pre-defined function, among
-[others](gmock_cook_book.md#using-actions).
+reference using `ReturnRef(`*`variable`*`)`, or invoke a pre-defined function,
+among [others](gmock_cook_book.md#using-actions).
 
 **Important note:** The `EXPECT_CALL()` statement evaluates the action clause
 only once, even though the action may be performed many times. Therefore you
index 768e9b4c2673977f4f459dbd76c569ad490978ee..18a2546a3846acde26b930a5ee30a00cce96a570 100644 (file)
@@ -105,7 +105,7 @@ includedir=/usr/include
 
 Name: gtest
 Description: GoogleTest (without main() function)
-Version: 1.10.0
+Version: 1.11.0
 URL: https://github.com/google/googletest
 Libs: -L${libdir} -lgtest -lpthread
 Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread
index 6d8fdf443923cacc83425cf45d5102d9889f6241..aecc368b08fe5db5ba00b2d94e2940d6af098d43 100644 (file)
@@ -162,9 +162,9 @@ TEST(TestSuiteName, TestName) {
 
 `TEST()` arguments go from general to specific. The *first* argument is the name
 of the test suite, and the *second* argument is the test's name within the test
-suite. Both names must be valid C++ identifiers, and they should not contain
-any underscores (`_`). A test's *full name* consists of its containing test suite and
-its individual name. Tests from different test suites can have the same
+suite. Both names must be valid C++ identifiers, and they should not contain any
+underscores (`_`). A test's *full name* consists of its containing test suite
+and its individual name. Tests from different test suites can have the same
 individual name.
 
 For example, let's take a simple integer function:
@@ -245,8 +245,8 @@ Also, you must first define a test fixture class before using it in a
 declaration`".
 
 For each test defined with `TEST_F()`, googletest will create a *fresh* test
-fixture at runtime, immediately initialize it via `SetUp()`, run the test,
-clean up by calling `TearDown()`, and then delete the test fixture. Note that
+fixture at runtime, immediately initialize it via `SetUp()`, run the test, clean
+up by calling `TearDown()`, and then delete the test fixture. Note that
 different tests in the same test suite have different test fixture objects, and
 googletest always deletes a test fixture before it creates the next one.
 googletest does **not** reuse the same test fixture for multiple tests. Any
@@ -342,8 +342,8 @@ your defined tests in order to run them.
 
 After defining your tests, you can run them with `RUN_ALL_TESTS()`, which
 returns `0` if all the tests are successful, or `1` otherwise. Note that
-`RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from
-different test suites, or even different source files.
+`RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from different
+test suites, or even different source files.
 
 When invoked, the `RUN_ALL_TESTS()` macro:
 
@@ -456,8 +456,8 @@ int main(int argc, char **argv) {
 
 The `::testing::InitGoogleTest()` function parses the command line for
 googletest flags, and removes all recognized flags. This allows the user to
-control a test program's behavior via various flags, which we'll cover in
-the [AdvancedGuide](advanced.md). You **must** call this function before calling
+control a test program's behavior via various flags, which we'll cover in the
+[AdvancedGuide](advanced.md). You **must** call this function before calling
 `RUN_ALL_TESTS()`, or the flags won't be properly initialized.
 
 On Windows, `InitGoogleTest()` also works with wide strings, so it can be used
index 362ee6d0506eb04b85fa1b40e57db3ef1c38c09a..5d6e9c68adb0e6ad15e73660b0102611e9ad5538 100644 (file)
@@ -17,7 +17,7 @@ See [Supported Platforms](platforms.md) for more information about platforms
 compatible with GoogleTest.
 
 If you don't already have Bazel installed, see the
-[Bazel installation guide](https://docs.bazel.build/versions/master/install.html).
+[Bazel installation guide](https://docs.bazel.build/versions/main/install.html).
 
 {: .callout .note}
 Note: The terminal commands in this tutorial show a Unix shell prompt, but the
@@ -26,7 +26,7 @@ commands work on the Windows command line as well.
 ## Set up a Bazel workspace
 
 A
-[Bazel workspace](https://docs.bazel.build/versions/master/build-ref.html#workspace)
+[Bazel workspace](https://docs.bazel.build/versions/main/build-ref.html#workspace)
 is a directory on your filesystem that you use to manage source files for the
 software you want to build. Each workspace directory has a text file named
 `WORKSPACE` which may be empty, or may contain references to external
@@ -40,9 +40,9 @@ $ mkdir my_workspace && cd my_workspace
 
 Next, you’ll create the `WORKSPACE` file to specify dependencies. A common and
 recommended way to depend on GoogleTest is to use a
-[Bazel external dependency](https://docs.bazel.build/versions/master/external.html)
+[Bazel external dependency](https://docs.bazel.build/versions/main/external.html)
 via the
-[`http_archive` rule](https://docs.bazel.build/versions/master/repo/http.html#http_archive).
+[`http_archive` rule](https://docs.bazel.build/versions/main/repo/http.html#http_archive).
 To do this, in the root directory of your workspace (`my_workspace/`), create a
 file named `WORKSPACE` with the following contents:
 
@@ -62,18 +62,6 @@ as a ZIP archive from GitHub. In the above example,
 GoogleTest version to use; we recommend updating the hash often to point to the
 latest version.
 
-Bazel also needs a dependency on the
-[`rules_cc` repository](https://github.com/bazelbuild/rules_cc) to build C++
-code, so add the following to the `WORKSPACE` file:
-
-```
-http_archive(
-  name = "rules_cc",
-  urls = ["https://github.com/bazelbuild/rules_cc/archive/40548a2974f1aea06215272d9c2b47a14a24e556.zip"],
-  strip_prefix = "rules_cc-40548a2974f1aea06215272d9c2b47a14a24e556",
-)
-```
-
 Now you're ready to build C++ code that uses GoogleTest.
 
 ## Create and run a binary
@@ -104,8 +92,6 @@ To build the code, create a file named `BUILD` in the same directory with the
 following contents:
 
 ```
-load("@rules_cc//cc:defs.bzl", "cc_test")
-
 cc_test(
   name = "hello_test",
   size = "small",
@@ -118,7 +104,7 @@ This `cc_test` rule declares the C++ test binary you want to build, and links to
 GoogleTest (`//:gtest_main`) using the prefix you specified in the `WORKSPACE`
 file (`@com_google_googletest`). For more information about Bazel `BUILD` files,
 see the
-[Bazel C++ Tutorial](https://docs.bazel.build/versions/master/tutorial/cpp.html).
+[Bazel C++ Tutorial](https://docs.bazel.build/versions/main/tutorial/cpp.html).
 
 Now you can build and run your test:
 
index 166d2a897a44465c75a2f3fb9ad34025c8fc98d1..ab81a129eff692d513b27c155abed96dd30f8db6 100644 (file)
@@ -6,7 +6,7 @@ provided by GoogleTest. All actions are defined in the `::testing` namespace.
 
 ## Returning a Value
 
-|                                   |                                               |
+| Action                            | Description                                   |
 | :-------------------------------- | :-------------------------------------------- |
 | `Return()`                        | Return from a `void` mock function.           |
 | `Return(value)`                   | Return `value`. If the type of `value` is     different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed. |
@@ -20,7 +20,7 @@ provided by GoogleTest. All actions are defined in the `::testing` namespace.
 
 ## Side Effects
 
-|                                    |                                         |
+| Action                             | Description                             |
 | :--------------------------------- | :-------------------------------------- |
 | `Assign(&variable, value)` | Assign `value` to variable. |
 | `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. |
@@ -38,9 +38,9 @@ provided by GoogleTest. All actions are defined in the `::testing` namespace.
 In the following, by "callable" we mean a free function, `std::function`,
 functor, or lambda.
 
-|                                     |                                        |
+| Action                              | Description                            |
 | :---------------------------------- | :------------------------------------- |
-| `f` | Invoke f with the arguments passed to the mock function, where f is a callable. |
+| `f` | Invoke `f` with the arguments passed to the mock function, where `f` is a callable. |
 | `Invoke(f)` | Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor. |
 | `Invoke(object_pointer, &class::method)` | Invoke the method on the object with the arguments passed to the mock function. |
 | `InvokeWithoutArgs(f)` | Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. |
@@ -86,7 +86,7 @@ value, and `foo` by reference.
 
 ## Default Action
 
-| Matcher       | Description                                            |
+| Action        | Description                                            |
 | :------------ | :----------------------------------------------------- |
 | `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). |
 
@@ -96,7 +96,7 @@ composite action - trying to do so will result in a run-time error.
 
 ## Composite Actions
 
-|                                |                                             |
+| Action                         | Description                                 |
 | :----------------------------- | :------------------------------------------ |
 | `DoAll(a1, a2, ..., an)`       | Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void and will receive a  readonly view of the arguments. |
 | `IgnoreResult(a)`              | Perform action `a` and ignore its result. `a` must not return void. |
@@ -106,7 +106,7 @@ composite action - trying to do so will result in a run-time error.
 
 ## Defining Actions
 
-|                                    |                                         |
+| Macro                              | Description                             |
 | :--------------------------------- | :-------------------------------------- |
 | `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. |
 | `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. |
index 9e40cab70454a68fa8a9d708b6fa2fe87e498a76..9fb159275131504ec920303268297a373502ab49 100644 (file)
@@ -8,9 +8,13 @@ A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or
 | `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. |
 | `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. |
 
-{: .callout .note}
-**Note:** Although equality matching via `EXPECT_THAT(actual_value,
-expected_value)` is supported, prefer to make the comparison explicit via
+{: .callout .warning}
+**WARNING:** Equality matching via `EXPECT_THAT(actual_value, expected_value)`
+is supported, however note that implicit conversions can cause surprising
+results. For example, `EXPECT_THAT(some_bool, "some string")` will compile and
+may pass unintentionally.
+
+**BEST PRACTICE:** Prefer to make the comparison explicit via
 `EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value,
 expected_value)`.
 
@@ -88,16 +92,17 @@ The `argument` can be either a C string or a C++ string object:
 
 | Matcher                 | Description                                        |
 | :---------------------- | :------------------------------------------------- |
-| `ContainsRegex(string)` | `argument` matches the given regular expression.   |
-| `EndsWith(suffix)`      | `argument` ends with string `suffix`.              |
-| `HasSubstr(string)`     | `argument` contains `string` as a sub-string.      |
-| `IsEmpty()`             | `argument` is an empty string.                     |
-| `MatchesRegex(string)`  | `argument` matches the given regular expression with the match starting at the first character and ending at the last character. |
-| `StartsWith(prefix)`    | `argument` starts with string `prefix`.            |
-| `StrCaseEq(string)`     | `argument` is equal to `string`, ignoring case.    |
-| `StrCaseNe(string)`     | `argument` is not equal to `string`, ignoring case. |
-| `StrEq(string)`         | `argument` is equal to `string`.                   |
-| `StrNe(string)`         | `argument` is not equal to `string`.               |
+| `ContainsRegex(string)`  | `argument` matches the given regular expression.  |
+| `EndsWith(suffix)`       | `argument` ends with string `suffix`.             |
+| `HasSubstr(string)`      | `argument` contains `string` as a sub-string.     |
+| `IsEmpty()`              | `argument` is an empty string.                    |
+| `MatchesRegex(string)`   | `argument` matches the given regular expression with the match starting at the first character and ending at the last character. |
+| `StartsWith(prefix)`     | `argument` starts with string `prefix`.           |
+| `StrCaseEq(string)`      | `argument` is equal to `string`, ignoring case.   |
+| `StrCaseNe(string)`      | `argument` is not equal to `string`, ignoring case. |
+| `StrEq(string)`          | `argument` is equal to `string`.                  |
+| `StrNe(string)`          | `argument` is not equal to `string`.              |
+| `WhenBase64Unescaped(m)` | `argument` is a base-64 escaped string whose unescaped string matches `m`. |
 
 `ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They
 use the regular expression syntax defined
@@ -116,6 +121,7 @@ messages, you can use:
 | `BeginEndDistanceIs(m)` | `argument` is a container whose `begin()` and `end()` iterators are separated by a number of increments matching `m`. E.g. `BeginEndDistanceIs(2)` or `BeginEndDistanceIs(Lt(2))`. For containers that define a `size()` method, `SizeIs(m)` may be more efficient. |
 | `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. |
 | `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. |
+| `Contains(e).Times(n)` | `argument` contains elements that match `e`, which can be either a value or a matcher, and the number of matches is `n`, which can be either a value or a matcher. Unlike the plain `Contains` and `Each` this allows to check for arbitrary occurrences including testing for absence with `Contains(e).Times(0)`. |
 | `Each(e)` | `argument` is a container where *every* element matches `e`, which can be either a value or a matcher. |
 | `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the *i*-th element matches `ei`, which can be a value or a matcher. |
 | `ElementsAreArray({e0, e1, ..., en})`, `ElementsAreArray(a_container)`, `ElementsAreArray(begin, end)`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. |
@@ -146,7 +152,6 @@ messages, you can use:
     one might write:
 
     ```cpp
-    using ::std::get;
     MATCHER(FooEq, "") {
       return std::get<0>(arg).Equals(std::get<1>(arg));
     }
@@ -193,6 +198,7 @@ messages, you can use:
 | Matcher          | Description                                       |
 | :--------------- | :------------------------------------------------ |
 | `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. |
+| `ResultOf(result_description, f, m)` | The same as the two-parameter version, but provides a better error message.
 
 ## Pointer Matchers
 
@@ -237,6 +243,7 @@ You can make a matcher from one or more other matchers:
 | `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1` to `mn`. |
 | `AnyOfArray({m0, m1, ..., mn})`, `AnyOfArray(a_container)`, `AnyOfArray(begin, end)`, `AnyOfArray(array)`, or `AnyOfArray(array, count)` | The same as `AnyOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. |
 | `Not(m)` | `argument` doesn't match matcher `m`. |
+| `Conditional(cond, m1, m2)` | Matches matcher `m1` if `cond` evaluates to true, else matches `m2`.|
 
 ## Adapters for Matchers
 
@@ -259,7 +266,7 @@ which must be a permanent callback.
 
 ## Defining Matchers
 
-| Matcher                              | Description                           |
+| Macro                                | Description                           |
 | :----------------------------------- | :------------------------------------ |
 | `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. |
 | `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a matcher `IsDivisibleBy(n)` to match a number divisible by `n`. |
index c29f71603f41367094f9e6c53db2485a9a8b5bd3..e414ffbd0dea39b9a97989f2939943a4a87362bd 100644 (file)
@@ -248,7 +248,9 @@ EXPECT_CALL(my_mock, GetNumber())
     .WillOnce(Return(3));
 ```
 
-The `WillOnce` clause can be used any number of times on an expectation.
+The `WillOnce` clause can be used any number of times on an expectation. Unlike
+`WillRepeatedly`, the action fed to each `WillOnce` call will be called at most
+once, so may be a move-only type and/or have an `&&`-qualified call operator.
 
 #### WillRepeatedly {#EXPECT_CALL.WillRepeatedly}
 
index 554d6c95840eee3f131d33ecd7eaa4f0e68dd03b..dc47942399d745c5b0778f1c8d482dd6da2c1a1b 100644 (file)
@@ -518,8 +518,8 @@ Logs a property for the current test, test suite, or entire invocation of the
 test program. Only the last value for a given key is logged.
 
 The key must be a valid XML attribute name, and cannot conflict with the ones
-already used by GoogleTest (`name`, `status`, `time`, `classname`, `type_param`,
-and `value_param`).
+already used by GoogleTest (`name`, `file`, `line`, `status`, `time`,
+`classname`, `type_param`, and `value_param`).
 
 `RecordProperty` is `public static` so it can be called from utility functions
 that are not members of the test fixture.
index e7df8ec53d00ae08575bd68b737ba0d71ca3b291..5c1f0dafea8bfa9d6e3af07508437b29f4e7489f 100644 (file)
@@ -36,13 +36,9 @@ endif()
 # as ${gmock_SOURCE_DIR} and to the root binary directory as
 # ${gmock_BINARY_DIR}.
 # Language "C" is required for find_package(Threads).
-if (CMAKE_VERSION VERSION_LESS 3.0)
-  project(gmock CXX C)
-else()
-  cmake_policy(SET CMP0048 NEW)
-  project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
-endif()
-cmake_minimum_required(VERSION 2.8.12)
+cmake_minimum_required(VERSION 3.5)
+cmake_policy(SET CMP0048 NEW)
+project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
 
 if (COMMAND set_up_hermetic_build)
   set_up_hermetic_build()
@@ -109,11 +105,12 @@ endif()
 # to the targets for when we are part of a parent build (ie being pulled
 # in via add_subdirectory() rather than being a standalone build).
 if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
+  string(REPLACE ";" "$<SEMICOLON>" dirs "${gmock_build_include_dirs}")
   target_include_directories(gmock SYSTEM INTERFACE
-    "$<BUILD_INTERFACE:${gmock_build_include_dirs}>"
+    "$<BUILD_INTERFACE:${dirs}>"
     "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
   target_include_directories(gmock_main SYSTEM INTERFACE
-    "$<BUILD_INTERFACE:${gmock_build_include_dirs}>"
+    "$<BUILD_INTERFACE:${dirs}>"
     "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
 endif()
 
@@ -154,7 +151,10 @@ if (gmock_build_tests)
   cxx_test(gmock_ex_test gmock_main)
   cxx_test(gmock-function-mocker_test gmock_main)
   cxx_test(gmock-internal-utils_test gmock_main)
-  cxx_test(gmock-matchers_test gmock_main)
+  cxx_test(gmock-matchers-arithmetic_test gmock_main)
+  cxx_test(gmock-matchers-comparisons_test gmock_main)
+  cxx_test(gmock-matchers-containers_test gmock_main)
+  cxx_test(gmock-matchers-misc_test gmock_main)
   cxx_test(gmock-more-actions_test gmock_main)
   cxx_test(gmock-nice-strict_test gmock_main)
   cxx_test(gmock-port_test gmock_main)
index ead688325d2c603575148543bd0f1b136412c207..7da60655dba8b8e91ec66a9a65f97139af03ee9b 100644 (file)
@@ -35,10 +35,6 @@ Details and examples can be found here:
 *   [gMock Cookbook](https://google.github.io/googletest/gmock_cook_book.html)
 *   [gMock Cheat Sheet](https://google.github.io/googletest/gmock_cheat_sheet.html)
 
-Please note that code under scripts/generator/ is from the
-[cppclean project](http://code.google.com/p/cppclean/) and under the Apache
-License, which is different from GoogleMock's license.
-
 GoogleMock is a part of
 [GoogleTest C++ testing framework](http://github.com/google/googletest/) and a
 subject to the same requirements.
index f2393bd3afadaba8506261b18a32040395a28267..c785ad8abba40f95cc8f0e8aef8c20e2a0f76fb0 100644 (file)
@@ -27,7 +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.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // The ACTION* family of macros can be used in a namespace scope to
 // To learn more about using these macros, please search for 'ACTION' on
 // https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
 
-// GOOGLETEST_CM0002 DO NOT DELETE
+// IWYU pragma: private, include "gmock/gmock.h"
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
 
 #ifndef _WIN32_WCE
-# include <errno.h>
+#include <errno.h>
 #endif
 
 #include <algorithm>
 #include "gmock/internal/gmock-pp.h"
 
 #ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
+#pragma warning(push)
+#pragma warning(disable : 4100)
 #endif
 
 namespace testing {
@@ -196,9 +196,7 @@ class BuiltInDefaultValue {
  public:
   // This function returns true if and only if type T has a built-in default
   // value.
-  static bool Exists() {
-    return ::std::is_default_constructible<T>::value;
-  }
+  static bool Exists() { return ::std::is_default_constructible<T>::value; }
 
   static T Get() {
     return BuiltInDefaultValueGetter<
@@ -227,11 +225,11 @@ class BuiltInDefaultValue<T*> {
 // The following specializations define the default values for
 // specific types we care about.
 #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
-  template <> \
-  class BuiltInDefaultValue<type> { \
-   public: \
-    static bool Exists() { return true; } \
-    static type Get() { return value; } \
+  template <>                                                     \
+  class BuiltInDefaultValue<type> {                               \
+   public:                                                        \
+    static bool Exists() { return true; }                         \
+    static type Get() { return value; }                           \
   }
 
 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, );  // NOLINT
@@ -255,21 +253,309 @@ GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U);  // NOLINT
 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0);     // NOLINT
 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL);  // NOLINT
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L);     // NOLINT
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL);     // NOLINT
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L);        // NOLINT
 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0);  // NOLINT
-GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0);  // NOLINT
+GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0);    // NOLINT
 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
 
 #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
 
-// Simple two-arg form of std::disjunction.
-template <typename P, typename Q>
-using disjunction = typename ::std::conditional<P::value, P, Q>::type;
+// Partial implementations of metaprogramming types from the standard library
+// not available in C++11.
+
+template <typename P>
+struct negation
+    // NOLINTNEXTLINE
+    : std::integral_constant<bool, bool(!P::value)> {};
+
+// Base case: with zero predicates the answer is always true.
+template <typename...>
+struct conjunction : std::true_type {};
+
+// With a single predicate, the answer is that predicate.
+template <typename P1>
+struct conjunction<P1> : P1 {};
+
+// With multiple predicates the answer is the first predicate if that is false,
+// and we recurse otherwise.
+template <typename P1, typename... Ps>
+struct conjunction<P1, Ps...>
+    : std::conditional<bool(P1::value), conjunction<Ps...>, P1>::type {};
+
+template <typename...>
+struct disjunction : std::false_type {};
+
+template <typename P1>
+struct disjunction<P1> : P1 {};
+
+template <typename P1, typename... Ps>
+struct disjunction<P1, Ps...>
+    // NOLINTNEXTLINE
+    : std::conditional<!bool(P1::value), disjunction<Ps...>, P1>::type {};
+
+template <typename...>
+using void_t = void;
+
+// Detects whether an expression of type `From` can be implicitly converted to
+// `To` according to [conv]. In C++17, [conv]/3 defines this as follows:
+//
+//     An expression e can be implicitly converted to a type T if and only if
+//     the declaration T t=e; is well-formed, for some invented temporary
+//     variable t ([dcl.init]).
+//
+// [conv]/2 implies we can use function argument passing to detect whether this
+// initialization is valid.
+//
+// Note that this is distinct from is_convertible, which requires this be valid:
+//
+//     To test() {
+//       return declval<From>();
+//     }
+//
+// In particular, is_convertible doesn't give the correct answer when `To` and
+// `From` are the same non-moveable type since `declval<From>` will be an rvalue
+// reference, defeating the guaranteed copy elision that would otherwise make
+// this function work.
+//
+// REQUIRES: `From` is not cv void.
+template <typename From, typename To>
+struct is_implicitly_convertible {
+ private:
+  // A function that accepts a parameter of type T. This can be called with type
+  // U successfully only if U is implicitly convertible to T.
+  template <typename T>
+  static void Accept(T);
+
+  // A function that creates a value of type T.
+  template <typename T>
+  static T Make();
+
+  // An overload be selected when implicit conversion from T to To is possible.
+  template <typename T, typename = decltype(Accept<To>(Make<T>()))>
+  static std::true_type TestImplicitConversion(int);
+
+  // A fallback overload selected in all other cases.
+  template <typename T>
+  static std::false_type TestImplicitConversion(...);
+
+ public:
+  using type = decltype(TestImplicitConversion<From>(0));
+  static constexpr bool value = type::value;
+};
+
+// Like std::invoke_result_t from C++17, but works only for objects with call
+// operators (not e.g. member function pointers, which we don't need specific
+// support for in OnceAction because std::function deals with them).
+template <typename F, typename... Args>
+using call_result_t = decltype(std::declval<F>()(std::declval<Args>()...));
+
+template <typename Void, typename R, typename F, typename... Args>
+struct is_callable_r_impl : std::false_type {};
+
+// Specialize the struct for those template arguments where call_result_t is
+// well-formed. When it's not, the generic template above is chosen, resulting
+// in std::false_type.
+template <typename R, typename F, typename... Args>
+struct is_callable_r_impl<void_t<call_result_t<F, Args...>>, R, F, Args...>
+    : std::conditional<
+          std::is_void<R>::value,  //
+          std::true_type,          //
+          is_implicitly_convertible<call_result_t<F, Args...>, R>>::type {};
+
+// Like std::is_invocable_r from C++17, but works only for objects with call
+// operators. See the note on call_result_t.
+template <typename R, typename F, typename... Args>
+using is_callable_r = is_callable_r_impl<void, R, F, Args...>;
+
+// Like std::as_const from C++17.
+template <typename T>
+typename std::add_const<T>::type& as_const(T& t) {
+  return t;
+}
 
 }  // namespace internal
 
+// Specialized for function types below.
+template <typename F>
+class OnceAction;
+
+// An action that can only be used once.
+//
+// This is accepted by WillOnce, which doesn't require the underlying action to
+// be copy-constructible (only move-constructible), and promises to invoke it as
+// an rvalue reference. This allows the action to work with move-only types like
+// std::move_only_function in a type-safe manner.
+//
+// For example:
+//
+//     // Assume we have some API that needs to accept a unique pointer to some
+//     // non-copyable object Foo.
+//     void AcceptUniquePointer(std::unique_ptr<Foo> foo);
+//
+//     // We can define an action that provides a Foo to that API. Because It
+//     // has to give away its unique pointer, it must not be called more than
+//     // once, so its call operator is &&-qualified.
+//     struct ProvideFoo {
+//       std::unique_ptr<Foo> foo;
+//
+//       void operator()() && {
+//         AcceptUniquePointer(std::move(Foo));
+//       }
+//     };
+//
+//     // This action can be used with WillOnce.
+//     EXPECT_CALL(mock, Call)
+//         .WillOnce(ProvideFoo{std::make_unique<Foo>(...)});
+//
+//     // But a call to WillRepeatedly will fail to compile. This is correct,
+//     // since the action cannot correctly be used repeatedly.
+//     EXPECT_CALL(mock, Call)
+//         .WillRepeatedly(ProvideFoo{std::make_unique<Foo>(...)});
+//
+// A less-contrived example would be an action that returns an arbitrary type,
+// whose &&-qualified call operator is capable of dealing with move-only types.
+template <typename Result, typename... Args>
+class OnceAction<Result(Args...)> final {
+ private:
+  // True iff we can use the given callable type (or lvalue reference) directly
+  // via StdFunctionAdaptor.
+  template <typename Callable>
+  using IsDirectlyCompatible = internal::conjunction<
+      // It must be possible to capture the callable in StdFunctionAdaptor.
+      std::is_constructible<typename std::decay<Callable>::type, Callable>,
+      // The callable must be compatible with our signature.
+      internal::is_callable_r<Result, typename std::decay<Callable>::type,
+                              Args...>>;
+
+  // True iff we can use the given callable type via StdFunctionAdaptor once we
+  // ignore incoming arguments.
+  template <typename Callable>
+  using IsCompatibleAfterIgnoringArguments = internal::conjunction<
+      // It must be possible to capture the callable in a lambda.
+      std::is_constructible<typename std::decay<Callable>::type, Callable>,
+      // The callable must be invocable with zero arguments, returning something
+      // convertible to Result.
+      internal::is_callable_r<Result, typename std::decay<Callable>::type>>;
+
+ public:
+  // Construct from a callable that is directly compatible with our mocked
+  // signature: it accepts our function type's arguments and returns something
+  // convertible to our result type.
+  template <typename Callable,
+            typename std::enable_if<
+                internal::conjunction<
+                    // Teach clang on macOS that we're not talking about a
+                    // copy/move constructor here. Otherwise it gets confused
+                    // when checking the is_constructible requirement of our
+                    // traits above.
+                    internal::negation<std::is_same<
+                        OnceAction, typename std::decay<Callable>::type>>,
+                    IsDirectlyCompatible<Callable>>  //
+                ::value,
+                int>::type = 0>
+  OnceAction(Callable&& callable)  // NOLINT
+      : function_(StdFunctionAdaptor<typename std::decay<Callable>::type>(
+            {}, std::forward<Callable>(callable))) {}
+
+  // As above, but for a callable that ignores the mocked function's arguments.
+  template <typename Callable,
+            typename std::enable_if<
+                internal::conjunction<
+                    // Teach clang on macOS that we're not talking about a
+                    // copy/move constructor here. Otherwise it gets confused
+                    // when checking the is_constructible requirement of our
+                    // traits above.
+                    internal::negation<std::is_same<
+                        OnceAction, typename std::decay<Callable>::type>>,
+                    // Exclude callables for which the overload above works.
+                    // We'd rather provide the arguments if possible.
+                    internal::negation<IsDirectlyCompatible<Callable>>,
+                    IsCompatibleAfterIgnoringArguments<Callable>>::value,
+                int>::type = 0>
+  OnceAction(Callable&& callable)  // NOLINT
+                                   // Call the constructor above with a callable
+                                   // that ignores the input arguments.
+      : OnceAction(IgnoreIncomingArguments<typename std::decay<Callable>::type>{
+            std::forward<Callable>(callable)}) {}
+
+  // We are naturally copyable because we store only an std::function, but
+  // semantically we should not be copyable.
+  OnceAction(const OnceAction&) = delete;
+  OnceAction& operator=(const OnceAction&) = delete;
+  OnceAction(OnceAction&&) = default;
+
+  // Invoke the underlying action callable with which we were constructed,
+  // handing it the supplied arguments.
+  Result Call(Args... args) && {
+    return function_(std::forward<Args>(args)...);
+  }
+
+ private:
+  // An adaptor that wraps a callable that is compatible with our signature and
+  // being invoked as an rvalue reference so that it can be used as an
+  // StdFunctionAdaptor. This throws away type safety, but that's fine because
+  // this is only used by WillOnce, which we know calls at most once.
+  //
+  // Once we have something like std::move_only_function from C++23, we can do
+  // away with this.
+  template <typename Callable>
+  class StdFunctionAdaptor final {
+   public:
+    // A tag indicating that the (otherwise universal) constructor is accepting
+    // the callable itself, instead of e.g. stealing calls for the move
+    // constructor.
+    struct CallableTag final {};
+
+    template <typename F>
+    explicit StdFunctionAdaptor(CallableTag, F&& callable)
+        : callable_(std::make_shared<Callable>(std::forward<F>(callable))) {}
+
+    // Rather than explicitly returning Result, we return whatever the wrapped
+    // callable returns. This allows for compatibility with existing uses like
+    // the following, when the mocked function returns void:
+    //
+    //     EXPECT_CALL(mock_fn_, Call)
+    //         .WillOnce([&] {
+    //            [...]
+    //            return 0;
+    //         });
+    //
+    // Such a callable can be turned into std::function<void()>. If we use an
+    // explicit return type of Result here then it *doesn't* work with
+    // std::function, because we'll get a "void function should not return a
+    // value" error.
+    //
+    // We need not worry about incompatible result types because the SFINAE on
+    // OnceAction already checks this for us. std::is_invocable_r_v itself makes
+    // the same allowance for void result types.
+    template <typename... ArgRefs>
+    internal::call_result_t<Callable, ArgRefs...> operator()(
+        ArgRefs&&... args) const {
+      return std::move(*callable_)(std::forward<ArgRefs>(args)...);
+    }
+
+   private:
+    // We must put the callable on the heap so that we are copyable, which
+    // std::function needs.
+    std::shared_ptr<Callable> callable_;
+  };
+
+  // An adaptor that makes a callable that accepts zero arguments callable with
+  // our mocked arguments.
+  template <typename Callable>
+  struct IgnoreIncomingArguments {
+    internal::call_result_t<Callable> operator()(Args&&...) {
+      return std::move(callable)();
+    }
+
+    Callable callable;
+  };
+
+  std::function<Result(Args...)> function_;
+};
+
 // When an unexpected function call is encountered, Google Mock will
 // let it return a default value if the user has specified one for its
 // return type, or if the return type has a built-in default value;
@@ -339,7 +625,8 @@ class DefaultValue {
 
    private:
     const T value_;
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
+    FixedValueProducer(const FixedValueProducer&) = delete;
+    FixedValueProducer& operator=(const FixedValueProducer&) = delete;
   };
 
   class FactoryValueProducer : public ValueProducer {
@@ -350,7 +637,8 @@ class DefaultValue {
 
    private:
     const FactoryFunction factory_;
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
+    FactoryValueProducer(const FactoryValueProducer&) = delete;
+    FactoryValueProducer& operator=(const FactoryValueProducer&) = delete;
   };
 
   static ValueProducer* producer_;
@@ -424,28 +712,34 @@ class ActionInterface {
   virtual Result Perform(const ArgumentTuple& args) = 0;
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
+  ActionInterface(const ActionInterface&) = delete;
+  ActionInterface& operator=(const ActionInterface&) = delete;
 };
 
-// An Action<F> is a copyable and IMMUTABLE (except by assignment)
-// object that represents an action to be taken when a mock function
-// of type F is called.  The implementation of Action<T> is just a
-// std::shared_ptr to const ActionInterface<T>. Don't inherit from Action!
-// You can view an object implementing ActionInterface<F> as a
-// concrete action (including its current state), and an Action<F>
-// object as a handle to it.
 template <typename F>
-class Action {
+class Action;
+
+// An Action<R(Args...)> is a copyable and IMMUTABLE (except by assignment)
+// object that represents an action to be taken when a mock function of type
+// R(Args...) is called. The implementation of Action<T> is just a
+// std::shared_ptr to const ActionInterface<T>. Don't inherit from Action! You
+// can view an object implementing ActionInterface<F> as a concrete action
+// (including its current state), and an Action<F> object as a handle to it.
+template <typename R, typename... Args>
+class Action<R(Args...)> {
+ private:
+  using F = R(Args...);
+
   // Adapter class to allow constructing Action from a legacy ActionInterface.
   // New code should create Actions from functors instead.
   struct ActionAdapter {
     // Adapter must be copyable to satisfy std::function requirements.
     ::std::shared_ptr<ActionInterface<F>> impl_;
 
-    template <typename... Args>
-    typename internal::Function<F>::Result operator()(Args&&... args) {
+    template <typename... InArgs>
+    typename internal::Function<F>::Result operator()(InArgs&&... args) {
       return impl_->Perform(
-          ::std::forward_as_tuple(::std::forward<Args>(args)...));
+          ::std::forward_as_tuple(::std::forward<InArgs>(args)...));
     }
   };
 
@@ -480,7 +774,8 @@ class Action {
   // Action<F>, as long as F's arguments can be implicitly converted
   // to Func's and Func's return type can be implicitly converted to F's.
   template <typename Func>
-  explicit Action(const Action<Func>& action) : fun_(action.fun_) {}
+  Action(const Action<Func>& action)  // NOLINT
+      : fun_(action.fun_) {}
 
   // Returns true if and only if this is the DoDefault() action.
   bool IsDoDefault() const { return fun_ == nullptr; }
@@ -498,6 +793,24 @@ class Action {
     return internal::Apply(fun_, ::std::move(args));
   }
 
+  // An action can be used as a OnceAction, since it's obviously safe to call it
+  // once.
+  operator OnceAction<F>() const {  // NOLINT
+    // Return a OnceAction-compatible callable that calls Perform with the
+    // arguments it is provided. We could instead just return fun_, but then
+    // we'd need to handle the IsDoDefault() case separately.
+    struct OA {
+      Action<F> action;
+
+      R operator()(Args... args) && {
+        return action.Perform(
+            std::forward_as_tuple(std::forward<Args>(args)...));
+      }
+    };
+
+    return OA{*this};
+  }
+
  private:
   template <typename G>
   friend class Action;
@@ -514,8 +827,8 @@ class Action {
 
   template <typename FunctionImpl>
   struct IgnoreArgs {
-    template <typename... Args>
-    Result operator()(const Args&...) const {
+    template <typename... InArgs>
+    Result operator()(const InArgs&...) const {
       return function_impl();
     }
 
@@ -606,118 +919,198 @@ struct ByMoveWrapper {
   T payload;
 };
 
-// Implements the polymorphic Return(x) action, which can be used in
-// any function that returns the type of x, regardless of the argument
-// types.
-//
-// Note: The value passed into Return must be converted into
-// Function<F>::Result when this action is cast to Action<F> rather than
-// when that action is performed. This is important in scenarios like
-//
-// MOCK_METHOD1(Method, T(U));
-// ...
-// {
-//   Foo foo;
-//   X x(&foo);
-//   EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
-// }
-//
-// In the example above the variable x holds reference to foo which leaves
-// scope and gets destroyed.  If copying X just copies a reference to foo,
-// that copy will be left with a hanging reference.  If conversion to T
-// makes a copy of foo, the above code is safe. To support that scenario, we
-// need to make sure that the type conversion happens inside the EXPECT_CALL
-// statement, and conversion of the result of Return to Action<T(U)> is a
-// good place for that.
-//
-// The real life example of the above scenario happens when an invocation
-// of gtl::Container() is passed into Return.
-//
+// The general implementation of Return(R). Specializations follow below.
 template <typename R>
-class ReturnAction {
+class ReturnAction final {
  public:
-  // Constructs a ReturnAction object from the value to be returned.
-  // 'value' is passed by value instead of by const reference in order
-  // to allow Return("string literal") to compile.
-  explicit ReturnAction(R value) : value_(new R(std::move(value))) {}
+  explicit ReturnAction(R value) : value_(std::move(value)) {}
+
+  template <typename U, typename... Args,
+            typename = typename std::enable_if<conjunction<
+                // See the requirements documented on Return.
+                negation<std::is_same<void, U>>,  //
+                negation<std::is_reference<U>>,   //
+                std::is_convertible<R, U>,        //
+                std::is_move_constructible<U>>::value>::type>
+  operator OnceAction<U(Args...)>() && {  // NOLINT
+    return Impl<U>(std::move(value_));
+  }
 
-  // This template type conversion operator allows Return(x) to be
-  // used in ANY function that returns x's type.
-  template <typename F>
-  operator Action<F>() const {  // NOLINT
-    // Assert statement belongs here because this is the best place to verify
-    // conditions on F. It produces the clearest error messages
-    // in most compilers.
-    // Impl really belongs in this scope as a local class but can't
-    // because MSVC produces duplicate symbols in different translation units
-    // in this case. Until MS fixes that bug we put Impl into the class scope
-    // and put the typedef both here (for use in assert statement) and
-    // in the Impl class. But both definitions must be the same.
-    typedef typename Function<F>::Result Result;
-    GTEST_COMPILE_ASSERT_(
-        !std::is_reference<Result>::value,
-        use_ReturnRef_instead_of_Return_to_return_a_reference);
-    static_assert(!std::is_void<Result>::value,
-                  "Can't use Return() on an action expected to return `void`.");
-    return Action<F>(new Impl<R, F>(value_));
+  template <typename U, typename... Args,
+            typename = typename std::enable_if<conjunction<
+                // See the requirements documented on Return.
+                negation<std::is_same<void, U>>,   //
+                negation<std::is_reference<U>>,    //
+                std::is_convertible<const R&, U>,  //
+                std::is_copy_constructible<U>>::value>::type>
+  operator Action<U(Args...)>() const {  // NOLINT
+    return Impl<U>(value_);
   }
 
  private:
-  // Implements the Return(x) action for a particular function type F.
-  template <typename R_, typename F>
-  class Impl : public ActionInterface<F> {
+  // Implements the Return(x) action for a mock function that returns type U.
+  template <typename U>
+  class Impl final {
    public:
-    typedef typename Function<F>::Result Result;
-    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
+    // The constructor used when the return value is allowed to move from the
+    // input value (i.e. we are converting to OnceAction).
+    explicit Impl(R&& input_value)
+        : state_(new State(std::move(input_value))) {}
 
-    // The implicit cast is necessary when Result has more than one
-    // single-argument constructor (e.g. Result is std::vector<int>) and R
-    // has a type conversion operator template.  In that case, value_(value)
-    // won't compile as the compiler doesn't known which constructor of
-    // Result to call.  ImplicitCast_ forces the compiler to convert R to
-    // Result without considering explicit constructors, thus resolving the
-    // ambiguity. value_ is then initialized using its copy constructor.
-    explicit Impl(const std::shared_ptr<R>& value)
-        : value_before_cast_(*value),
-          value_(ImplicitCast_<Result>(value_before_cast_)) {}
+    // The constructor used when the return value is not allowed to move from
+    // the input value (i.e. we are converting to Action).
+    explicit Impl(const R& input_value) : state_(new State(input_value)) {}
 
-    Result Perform(const ArgumentTuple&) override { return value_; }
+    U operator()() && { return std::move(state_->value); }
+    U operator()() const& { return state_->value; }
 
    private:
-    GTEST_COMPILE_ASSERT_(!std::is_reference<Result>::value,
-                          Result_cannot_be_a_reference_type);
-    // We save the value before casting just in case it is being cast to a
-    // wrapper type.
-    R value_before_cast_;
-    Result value_;
-
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
+    // We put our state on the heap so that the compiler-generated copy/move
+    // constructors work correctly even when U is a reference-like type. This is
+    // necessary only because we eagerly create State::value (see the note on
+    // that symbol for details). If we instead had only the input value as a
+    // member then the default constructors would work fine.
+    //
+    // For example, when R is std::string and U is std::string_view, value is a
+    // reference to the string backed by input_value. The copy constructor would
+    // copy both, so that we wind up with a new input_value object (with the
+    // same contents) and a reference to the *old* input_value object rather
+    // than the new one.
+    struct State {
+      explicit State(const R& input_value_in)
+          : input_value(input_value_in),
+            // Make an implicit conversion to Result before initializing the U
+            // object we store, avoiding calling any explicit constructor of U
+            // from R.
+            //
+            // This simulates the language rules: a function with return type U
+            // that does `return R()` requires R to be implicitly convertible to
+            // U, and uses that path for the conversion, even U Result has an
+            // explicit constructor from R.
+            value(ImplicitCast_<U>(internal::as_const(input_value))) {}
+
+      // As above, but for the case where we're moving from the ReturnAction
+      // object because it's being used as a OnceAction.
+      explicit State(R&& input_value_in)
+          : input_value(std::move(input_value_in)),
+            // For the same reason as above we make an implicit conversion to U
+            // before initializing the value.
+            //
+            // Unlike above we provide the input value as an rvalue to the
+            // implicit conversion because this is a OnceAction: it's fine if it
+            // wants to consume the input value.
+            value(ImplicitCast_<U>(std::move(input_value))) {}
+
+      // A copy of the value originally provided by the user. We retain this in
+      // addition to the value of the mock function's result type below in case
+      // the latter is a reference-like type. See the std::string_view example
+      // in the documentation on Return.
+      R input_value;
+
+      // The value we actually return, as the type returned by the mock function
+      // itself.
+      //
+      // We eagerly initialize this here, rather than lazily doing the implicit
+      // conversion automatically each time Perform is called, for historical
+      // reasons: in 2009-11, commit a070cbd91c (Google changelist 13540126)
+      // made the Action<U()> conversion operator eagerly convert the R value to
+      // U, but without keeping the R alive. This broke the use case discussed
+      // in the documentation for Return, making reference-like types such as
+      // std::string_view not safe to use as U where the input type R is a
+      // value-like type such as std::string.
+      //
+      // The example the commit gave was not very clear, nor was the issue
+      // thread (https://github.com/google/googlemock/issues/86), but it seems
+      // the worry was about reference-like input types R that flatten to a
+      // value-like type U when being implicitly converted. An example of this
+      // is std::vector<bool>::reference, which is often a proxy type with an
+      // reference to the underlying vector:
+      //
+      //     // Helper method: have the mock function return bools according
+      //     // to the supplied script.
+      //     void SetActions(MockFunction<bool(size_t)>& mock,
+      //                     const std::vector<bool>& script) {
+      //       for (size_t i = 0; i < script.size(); ++i) {
+      //         EXPECT_CALL(mock, Call(i)).WillOnce(Return(script[i]));
+      //       }
+      //     }
+      //
+      //     TEST(Foo, Bar) {
+      //       // Set actions using a temporary vector, whose operator[]
+      //       // returns proxy objects that references that will be
+      //       // dangling once the call to SetActions finishes and the
+      //       // vector is destroyed.
+      //       MockFunction<bool(size_t)> mock;
+      //       SetActions(mock, {false, true});
+      //
+      //       EXPECT_FALSE(mock.AsStdFunction()(0));
+      //       EXPECT_TRUE(mock.AsStdFunction()(1));
+      //     }
+      //
+      // This eager conversion helps with a simple case like this, but doesn't
+      // fully make these types work in general. For example the following still
+      // uses a dangling reference:
+      //
+      //     TEST(Foo, Baz) {
+      //       MockFunction<std::vector<std::string>()> mock;
+      //
+      //       // Return the same vector twice, and then the empty vector
+      //       // thereafter.
+      //       auto action = Return(std::initializer_list<std::string>{
+      //           "taco", "burrito",
+      //       });
+      //
+      //       EXPECT_CALL(mock, Call)
+      //           .WillOnce(action)
+      //           .WillOnce(action)
+      //           .WillRepeatedly(Return(std::vector<std::string>{}));
+      //
+      //       EXPECT_THAT(mock.AsStdFunction()(),
+      //                   ElementsAre("taco", "burrito"));
+      //       EXPECT_THAT(mock.AsStdFunction()(),
+      //                   ElementsAre("taco", "burrito"));
+      //       EXPECT_THAT(mock.AsStdFunction()(), IsEmpty());
+      //     }
+      //
+      U value;
+    };
+
+    const std::shared_ptr<State> state_;
   };
 
-  // Partially specialize for ByMoveWrapper. This version of ReturnAction will
-  // move its contents instead.
-  template <typename R_, typename F>
-  class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
-   public:
-    typedef typename Function<F>::Result Result;
-    typedef typename Function<F>::ArgumentTuple ArgumentTuple;
+  R value_;
+};
+
+// A specialization of ReturnAction<R> when R is ByMoveWrapper<T> for some T.
+//
+// This version applies the type system-defeating hack of moving from T even in
+// the const call operator, checking at runtime that it isn't called more than
+// once, since the user has declared their intent to do so by using ByMove.
+template <typename T>
+class ReturnAction<ByMoveWrapper<T>> final {
+ public:
+  explicit ReturnAction(ByMoveWrapper<T> wrapper)
+      : state_(new State(std::move(wrapper.payload))) {}
 
-    explicit Impl(const std::shared_ptr<R>& wrapper)
-        : performed_(false), wrapper_(wrapper) {}
+  T operator()() const {
+    GTEST_CHECK_(!state_->called)
+        << "A ByMove() action must be performed at most once.";
 
-    Result Perform(const ArgumentTuple&) override {
-      GTEST_CHECK_(!performed_)
-          << "A ByMove() action should only be performed once.";
-      performed_ = true;
-      return std::move(wrapper_->payload);
-    }
+    state_->called = true;
+    return std::move(state_->value);
+  }
 
-   private:
-    bool performed_;
-    const std::shared_ptr<R> wrapper_;
+ private:
+  // We store our state on the heap so that we are copyable as required by
+  // Action, despite the fact that we are stateful and T may not be copyable.
+  struct State {
+    explicit State(T&& value_in) : value(std::move(value_in)) {}
+
+    T value;
+    bool called = false;
   };
 
-  const std::shared_ptr<R> value_;
+  const std::shared_ptr<State> state_;
 };
 
 // Implements the ReturnNull() action.
@@ -759,8 +1152,8 @@ class ReturnRefAction {
     // Asserts that the function return type is a reference.  This
     // catches the user error of using ReturnRef(x) when Return(x)
     // should be used, and generates some helpful error message.
-    GTEST_COMPILE_ASSERT_(std::is_reference<Result>::value,
-                          use_Return_instead_of_ReturnRef_to_return_a_value);
+    static_assert(std::is_reference<Result>::value,
+                  "use Return instead of ReturnRef to return a value");
     return Action<F>(new Impl<F>(ref_));
   }
 
@@ -801,9 +1194,8 @@ class ReturnRefOfCopyAction {
     // Asserts that the function return type is a reference.  This
     // catches the user error of using ReturnRefOfCopy(x) when Return(x)
     // should be used, and generates some helpful error message.
-    GTEST_COMPILE_ASSERT_(
-        std::is_reference<Result>::value,
-        use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
+    static_assert(std::is_reference<Result>::value,
+                  "use Return instead of ReturnRefOfCopy to return a value");
     return Action<F>(new Impl<F>(value_));
   }
 
@@ -839,7 +1231,7 @@ class ReturnRoundRobinAction {
 
   template <typename... Args>
   T operator()(Args&&...) const {
-     return state_->Next();
+    return state_->Next();
   }
 
  private:
@@ -862,7 +1254,9 @@ class DoDefaultAction {
   // This template type conversion operator allows DoDefault() to be
   // used in any function.
   template <typename F>
-  operator Action<F>() const { return Action<F>(); }  // NOLINT
+  operator Action<F>() const {
+    return Action<F>();
+  }  // NOLINT
 };
 
 // Implements the Assign action to set a given pointer referent to a
@@ -890,8 +1284,7 @@ template <typename T>
 class SetErrnoAndReturnAction {
  public:
   SetErrnoAndReturnAction(int errno_value, T result)
-      : errno_(errno_value),
-        result_(result) {}
+      : errno_(errno_value), result_(result) {}
   template <typename Result, typename ArgumentTuple>
   Result Perform(const ArgumentTuple& /* args */) const {
     errno = errno_;
@@ -1002,8 +1395,8 @@ class IgnoreResultAction {
    private:
     // Type OriginalFunction is the same as F except that its return
     // type is IgnoredValue.
-    typedef typename internal::Function<F>::MakeResultIgnoredValue
-        OriginalFunction;
+    typedef
+        typename internal::Function<F>::MakeResultIgnoredValue OriginalFunction;
 
     const Action<OriginalFunction> action_;
   };
@@ -1013,55 +1406,239 @@ class IgnoreResultAction {
 
 template <typename InnerAction, size_t... I>
 struct WithArgsAction {
-  InnerAction action;
+  InnerAction inner_action;
 
-  // The inner action could be anything convertible to Action<X>.
-  // We use the conversion operator to detect the signature of the inner Action.
+  // The signature of the function as seen by the inner action, given an out
+  // action with the given result and argument types.
   template <typename R, typename... Args>
+  using InnerSignature =
+      R(typename std::tuple_element<I, std::tuple<Args...>>::type...);
+
+  // Rather than a call operator, we must define conversion operators to
+  // particular action types. This is necessary for embedded actions like
+  // DoDefault(), which rely on an action conversion operators rather than
+  // providing a call operator because even with a particular set of arguments
+  // they don't have a fixed return type.
+
+  template <typename R, typename... Args,
+            typename std::enable_if<
+                std::is_convertible<
+                    InnerAction,
+                    // Unfortunately we can't use the InnerSignature alias here;
+                    // MSVC complains about the I parameter pack not being
+                    // expanded (error C3520) despite it being expanded in the
+                    // type alias.
+                    OnceAction<R(typename std::tuple_element<
+                                 I, std::tuple<Args...>>::type...)>>::value,
+                int>::type = 0>
+  operator OnceAction<R(Args...)>() && {  // NOLINT
+    struct OA {
+      OnceAction<InnerSignature<R, Args...>> inner_action;
+
+      R operator()(Args&&... args) && {
+        return std::move(inner_action)
+            .Call(std::get<I>(
+                std::forward_as_tuple(std::forward<Args>(args)...))...);
+      }
+    };
+
+    return OA{std::move(inner_action)};
+  }
+
+  template <typename R, typename... Args,
+            typename std::enable_if<
+                std::is_convertible<
+                    const InnerAction&,
+                    // Unfortunately we can't use the InnerSignature alias here;
+                    // MSVC complains about the I parameter pack not being
+                    // expanded (error C3520) despite it being expanded in the
+                    // type alias.
+                    Action<R(typename std::tuple_element<
+                             I, std::tuple<Args...>>::type...)>>::value,
+                int>::type = 0>
   operator Action<R(Args...)>() const {  // NOLINT
-    using TupleType = std::tuple<Args...>;
-    Action<R(typename std::tuple_element<I, TupleType>::type...)>
-        converted(action);
+    Action<InnerSignature<R, Args...>> converted(inner_action);
 
-    return [converted](Args... args) -> R {
+    return [converted](Args&&... args) -> R {
       return converted.Perform(std::forward_as_tuple(
-        std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));
+          std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));
     };
   }
 };
 
 template <typename... Actions>
-struct DoAllAction {
- private:
+class DoAllAction;
+
+// Base case: only a single action.
+template <typename FinalAction>
+class DoAllAction<FinalAction> {
+ public:
+  struct UserConstructorTag {};
+
   template <typename T>
-  using NonFinalType =
-      typename std::conditional<std::is_scalar<T>::value, T, const T&>::type;
+  explicit DoAllAction(UserConstructorTag, T&& action)
+      : final_action_(std::forward<T>(action)) {}
+
+  // Rather than a call operator, we must define conversion operators to
+  // particular action types. This is necessary for embedded actions like
+  // DoDefault(), which rely on an action conversion operators rather than
+  // providing a call operator because even with a particular set of arguments
+  // they don't have a fixed return type.
+
+  template <typename R, typename... Args,
+            typename std::enable_if<
+                std::is_convertible<FinalAction, OnceAction<R(Args...)>>::value,
+                int>::type = 0>
+  operator OnceAction<R(Args...)>() && {  // NOLINT
+    return std::move(final_action_);
+  }
 
-  template <typename ActionT, size_t... I>
-  std::vector<ActionT> Convert(IndexSequence<I...>) const {
-    return {ActionT(std::get<I>(actions))...};
+  template <
+      typename R, typename... Args,
+      typename std::enable_if<
+          std::is_convertible<const FinalAction&, Action<R(Args...)>>::value,
+          int>::type = 0>
+  operator Action<R(Args...)>() const {  // NOLINT
+    return final_action_;
   }
 
+ private:
+  FinalAction final_action_;
+};
+
+// Recursive case: support N actions by calling the initial action and then
+// calling through to the base class containing N-1 actions.
+template <typename InitialAction, typename... OtherActions>
+class DoAllAction<InitialAction, OtherActions...>
+    : private DoAllAction<OtherActions...> {
+ private:
+  using Base = DoAllAction<OtherActions...>;
+
+  // The type of reference that should be provided to an initial action for a
+  // mocked function parameter of type T.
+  //
+  // There are two quirks here:
+  //
+  //  *  Unlike most forwarding functions, we pass scalars through by value.
+  //     This isn't strictly necessary because an lvalue reference would work
+  //     fine too and be consistent with other non-reference types, but it's
+  //     perhaps less surprising.
+  //
+  //     For example if the mocked function has signature void(int), then it
+  //     might seem surprising for the user's initial action to need to be
+  //     convertible to Action<void(const int&)>. This is perhaps less
+  //     surprising for a non-scalar type where there may be a performance
+  //     impact, or it might even be impossible, to pass by value.
+  //
+  //  *  More surprisingly, `const T&` is often not a const reference type.
+  //     By the reference collapsing rules in C++17 [dcl.ref]/6, if T refers to
+  //     U& or U&& for some non-scalar type U, then InitialActionArgType<T> is
+  //     U&. In other words, we may hand over a non-const reference.
+  //
+  //     So for example, given some non-scalar type Obj we have the following
+  //     mappings:
+  //
+  //            T               InitialActionArgType<T>
+  //         -------            -----------------------
+  //         Obj                const Obj&
+  //         Obj&               Obj&
+  //         Obj&&              Obj&
+  //         const Obj          const Obj&
+  //         const Obj&         const Obj&
+  //         const Obj&&        const Obj&
+  //
+  //     In other words, the initial actions get a mutable view of an non-scalar
+  //     argument if and only if the mock function itself accepts a non-const
+  //     reference type. They are never given an rvalue reference to an
+  //     non-scalar type.
+  //
+  //     This situation makes sense if you imagine use with a matcher that is
+  //     designed to write through a reference. For example, if the caller wants
+  //     to fill in a reference argument and then return a canned value:
+  //
+  //         EXPECT_CALL(mock, Call)
+  //             .WillOnce(DoAll(SetArgReferee<0>(17), Return(19)));
+  //
+  template <typename T>
+  using InitialActionArgType =
+      typename std::conditional<std::is_scalar<T>::value, T, const T&>::type;
+
  public:
-  std::tuple<Actions...> actions;
+  struct UserConstructorTag {};
+
+  template <typename T, typename... U>
+  explicit DoAllAction(UserConstructorTag, T&& initial_action,
+                       U&&... other_actions)
+      : Base({}, std::forward<U>(other_actions)...),
+        initial_action_(std::forward<T>(initial_action)) {}
+
+  template <typename R, typename... Args,
+            typename std::enable_if<
+                conjunction<
+                    // Both the initial action and the rest must support
+                    // conversion to OnceAction.
+                    std::is_convertible<
+                        InitialAction,
+                        OnceAction<void(InitialActionArgType<Args>...)>>,
+                    std::is_convertible<Base, OnceAction<R(Args...)>>>::value,
+                int>::type = 0>
+  operator OnceAction<R(Args...)>() && {  // NOLINT
+    // Return an action that first calls the initial action with arguments
+    // filtered through InitialActionArgType, then forwards arguments directly
+    // to the base class to deal with the remaining actions.
+    struct OA {
+      OnceAction<void(InitialActionArgType<Args>...)> initial_action;
+      OnceAction<R(Args...)> remaining_actions;
+
+      R operator()(Args... args) && {
+        std::move(initial_action)
+            .Call(static_cast<InitialActionArgType<Args>>(args)...);
+
+        return std::move(remaining_actions).Call(std::forward<Args>(args)...);
+      }
+    };
 
-  template <typename R, typename... Args>
+    return OA{
+        std::move(initial_action_),
+        std::move(static_cast<Base&>(*this)),
+    };
+  }
+
+  template <
+      typename R, typename... Args,
+      typename std::enable_if<
+          conjunction<
+              // Both the initial action and the rest must support conversion to
+              // Action.
+              std::is_convertible<const InitialAction&,
+                                  Action<void(InitialActionArgType<Args>...)>>,
+              std::is_convertible<const Base&, Action<R(Args...)>>>::value,
+          int>::type = 0>
   operator Action<R(Args...)>() const {  // NOLINT
-    struct Op {
-      std::vector<Action<void(NonFinalType<Args>...)>> converted;
-      Action<R(Args...)> last;
+    // Return an action that first calls the initial action with arguments
+    // filtered through InitialActionArgType, then forwards arguments directly
+    // to the base class to deal with the remaining actions.
+    struct OA {
+      Action<void(InitialActionArgType<Args>...)> initial_action;
+      Action<R(Args...)> remaining_actions;
+
       R operator()(Args... args) const {
-        auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...);
-        for (auto& a : converted) {
-          a.Perform(tuple_args);
-        }
-        return last.Perform(std::move(tuple_args));
+        initial_action.Perform(std::forward_as_tuple(
+            static_cast<InitialActionArgType<Args>>(args)...));
+
+        return remaining_actions.Perform(
+            std::forward_as_tuple(std::forward<Args>(args)...));
       }
     };
-    return Op{Convert<Action<void(NonFinalType<Args>...)>>(
-                  MakeIndexSequence<sizeof...(Actions) - 1>()),
-              std::get<sizeof...(Actions) - 1>(actions)};
+
+    return OA{
+        initial_action_,
+        static_cast<const Base&>(*this),
+    };
   }
+
+ private:
+  InitialAction initial_action_;
 };
 
 template <typename T, typename... Params>
@@ -1078,10 +1655,11 @@ struct ReturnNewAction {
 
 template <size_t k>
 struct ReturnArgAction {
-  template <typename... Args>
-  auto operator()(const Args&... args) const ->
-      typename std::tuple_element<k, std::tuple<Args...>>::type {
-    return std::get<k>(std::tie(args...));
+  template <typename... Args,
+            typename = typename std::enable_if<(k < sizeof...(Args))>::type>
+  auto operator()(Args&&... args) const -> decltype(std::get<k>(
+      std::forward_as_tuple(std::forward<Args>(args)...))) {
+    return std::get<k>(std::forward_as_tuple(std::forward<Args>(args)...));
   }
 };
 
@@ -1203,7 +1781,8 @@ typedef internal::IgnoredValue Unused;
 template <typename... Action>
 internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
     Action&&... action) {
-  return {std::forward_as_tuple(std::forward<Action>(action)...)};
+  return internal::DoAllAction<typename std::decay<Action>::type...>(
+      {}, std::forward<Action>(action)...);
 }
 
 // WithArg<k>(an_action) creates an action that passes the k-th
@@ -1212,8 +1791,8 @@ internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
 // multiple arguments.  For convenience, we also provide
 // WithArgs<k>(an_action) (defined below) as a synonym.
 template <size_t k, typename InnerAction>
-internal::WithArgsAction<typename std::decay<InnerAction>::type, k>
-WithArg(InnerAction&& action) {
+internal::WithArgsAction<typename std::decay<InnerAction>::type, k> WithArg(
+    InnerAction&& action) {
   return {std::forward<InnerAction>(action)};
 }
 
@@ -1232,14 +1811,35 @@ WithArgs(InnerAction&& action) {
 // argument.  In other words, it adapts an action accepting no
 // argument to one that accepts (and ignores) arguments.
 template <typename InnerAction>
-internal::WithArgsAction<typename std::decay<InnerAction>::type>
-WithoutArgs(InnerAction&& action) {
+internal::WithArgsAction<typename std::decay<InnerAction>::type> WithoutArgs(
+    InnerAction&& action) {
   return {std::forward<InnerAction>(action)};
 }
 
-// Creates an action that returns 'value'.  'value' is passed by value
-// instead of const reference - otherwise Return("string literal")
-// will trigger a compiler error about using array as initializer.
+// Creates an action that returns a value.
+//
+// The returned type can be used with a mock function returning a non-void,
+// non-reference type U as follows:
+//
+//  *  If R is convertible to U and U is move-constructible, then the action can
+//     be used with WillOnce.
+//
+//  *  If const R& is convertible to U and U is copy-constructible, then the
+//     action can be used with both WillOnce and WillRepeatedly.
+//
+// The mock expectation contains the R value from which the U return value is
+// constructed (a move/copy of the argument to Return). This means that the R
+// value will survive at least until the mock object's expectations are cleared
+// or the mock object is destroyed, meaning that U can safely be a
+// reference-like type such as std::string_view:
+//
+//     // The mock function returns a view of a copy of the string fed to
+//     // Return. The view is valid even after the action is performed.
+//     MockFunction<std::string_view()> mock;
+//     EXPECT_CALL(mock, Call).WillOnce(Return(std::string("taco")));
+//     const std::string_view result = mock.AsStdFunction()();
+//     EXPECT_EQ("taco", result);
+//
 template <typename R>
 internal::ReturnAction<R> Return(R value) {
   return internal::ReturnAction<R>(std::move(value));
@@ -1273,6 +1873,8 @@ inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
   return internal::ReturnRefOfCopyAction<R>(x);
 }
 
+// DEPRECATED: use Return(x) directly with WillOnce.
+//
 // Modifies the parent action (a Return() action) to perform a move of the
 // argument instead of a copy.
 // Return(ByMove()) actions can only be executed once and will assert this
@@ -1319,7 +1921,7 @@ internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) {
 
 // Creates an action that sets a pointer referent to a given value.
 template <typename T1, typename T2>
-PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
+PolymorphicAction<internal::AssignAction<T1, T2>> Assign(T1* ptr, T2 val) {
   return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
 }
 
@@ -1327,8 +1929,8 @@ PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
 
 // Creates an action that sets errno and returns the appropriate error.
 template <typename T>
-PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
-SetErrnoAndReturn(int errval, T result) {
+PolymorphicAction<internal::SetErrnoAndReturnAction<T>> SetErrnoAndReturn(
+    int errval, T result) {
   return MakePolymorphicAction(
       internal::SetErrnoAndReturnAction<T>(errval, result));
 }
@@ -1482,7 +2084,8 @@ struct ExcessiveArg {};
 
 // Builds an implementation of an Action<> for some particular signature, using
 // a class defined by an ACTION* macro.
-template <typename F, typename Impl> struct ActionImpl;
+template <typename F, typename Impl>
+struct ActionImpl;
 
 template <typename Impl>
 struct ImplBase {
@@ -1502,7 +2105,7 @@ struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {
   using args_type = std::tuple<Args...>;
 
   ActionImpl() = default;  // Only defined if appropriate for Base.
-  explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} { }
+  explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} {}
 
   R operator()(Args&&... arg) const {
     static constexpr size_t kMaxArgs =
@@ -1521,12 +2124,14 @@ struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {
     // args_type get passed, followed by a dummy of unspecified type for the
     // remainder up to 10 explicit args.
     static constexpr ExcessiveArg kExcessArg{};
-    return static_cast<const Impl&>(*this).template gmock_PerformImpl<
-        /*function_type=*/function_type, /*return_type=*/R,
-        /*args_type=*/args_type,
-        /*argN_type=*/typename std::tuple_element<arg_id, args_type>::type...>(
-        /*args=*/args, std::get<arg_id>(args)...,
-        ((void)excess_id, kExcessArg)...);
+    return static_cast<const Impl&>(*this)
+        .template gmock_PerformImpl<
+            /*function_type=*/function_type, /*return_type=*/R,
+            /*args_type=*/args_type,
+            /*argN_type=*/
+            typename std::tuple_element<arg_id, args_type>::type...>(
+            /*args=*/args, std::get<arg_id>(args)...,
+            ((void)excess_id, kExcessArg)...);
   }
 };
 
@@ -1545,7 +2150,7 @@ template <typename F, typename Impl>
 
 #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \
   , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_
-#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_           \
+#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_                 \
   const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \
       GMOCK_INTERNAL_ARG_UNUSED, , 10)
 
@@ -1584,42 +2189,47 @@ template <typename F, typename Impl>
 #define GMOCK_ACTION_FIELD_PARAMS_(params) \
   GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params)
 
-#define GMOCK_INTERNAL_ACTION(name, full_name, params)                        \
-  template <GMOCK_ACTION_TYPENAME_PARAMS_(params)>                            \
-  class full_name {                                                           \
-   public:                                                                    \
-    explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params))              \
-        : impl_(std::make_shared<gmock_Impl>(                                 \
-                GMOCK_ACTION_GVALUE_PARAMS_(params))) { }                     \
-    full_name(const full_name&) = default;                                    \
-    full_name(full_name&&) noexcept = default;                                \
-    template <typename F>                                                     \
-    operator ::testing::Action<F>() const {                                   \
-      return ::testing::internal::MakeAction<F>(impl_);                       \
-    }                                                                         \
-   private:                                                                   \
-    class gmock_Impl {                                                        \
-     public:                                                                  \
-      explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params))           \
-          : GMOCK_ACTION_INIT_PARAMS_(params) {}                              \
-      template <typename function_type, typename return_type,                 \
-                typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>        \
-      return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
-      GMOCK_ACTION_FIELD_PARAMS_(params)                                      \
-    };                                                                        \
-    std::shared_ptr<const gmock_Impl> impl_;                                  \
-  };                                                                          \
-  template <GMOCK_ACTION_TYPENAME_PARAMS_(params)>                            \
-  inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name(                   \
-      GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) {                             \
-    return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>(                      \
-        GMOCK_ACTION_GVALUE_PARAMS_(params));                                 \
-  }                                                                           \
-  template <GMOCK_ACTION_TYPENAME_PARAMS_(params)>                            \
-  template <typename function_type, typename return_type, typename args_type, \
-            GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>                                \
-  return_type full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl::      \
-  gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
+#define GMOCK_INTERNAL_ACTION(name, full_name, params)                         \
+  template <GMOCK_ACTION_TYPENAME_PARAMS_(params)>                             \
+  class full_name {                                                            \
+   public:                                                                     \
+    explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params))               \
+        : impl_(std::make_shared<gmock_Impl>(                                  \
+              GMOCK_ACTION_GVALUE_PARAMS_(params))) {}                         \
+    full_name(const full_name&) = default;                                     \
+    full_name(full_name&&) noexcept = default;                                 \
+    template <typename F>                                                      \
+    operator ::testing::Action<F>() const {                                    \
+      return ::testing::internal::MakeAction<F>(impl_);                        \
+    }                                                                          \
+                                                                               \
+   private:                                                                    \
+    class gmock_Impl {                                                         \
+     public:                                                                   \
+      explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params))            \
+          : GMOCK_ACTION_INIT_PARAMS_(params) {}                               \
+      template <typename function_type, typename return_type,                  \
+                typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>         \
+      return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const;  \
+      GMOCK_ACTION_FIELD_PARAMS_(params)                                       \
+    };                                                                         \
+    std::shared_ptr<const gmock_Impl> impl_;                                   \
+  };                                                                           \
+  template <GMOCK_ACTION_TYPENAME_PARAMS_(params)>                             \
+  inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name(                    \
+      GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_;        \
+  template <GMOCK_ACTION_TYPENAME_PARAMS_(params)>                             \
+  inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name(                    \
+      GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) {                              \
+    return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>(                       \
+        GMOCK_ACTION_GVALUE_PARAMS_(params));                                  \
+  }                                                                            \
+  template <GMOCK_ACTION_TYPENAME_PARAMS_(params)>                             \
+  template <typename function_type, typename return_type, typename args_type,  \
+            GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>                                 \
+  return_type                                                                  \
+  full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl::gmock_PerformImpl( \
+      GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
 
 }  // namespace internal
 
@@ -1627,12 +2237,13 @@ template <typename F, typename Impl>
 #define ACTION(name)                                                          \
   class name##Action {                                                        \
    public:                                                                    \
-   explicit name##Action() noexcept {}                                        \
-   name##Action(const name##Action&) noexcept {}                              \
+    explicit name##Action() noexcept {}                                       \
+    name##Action(const name##Action&) noexcept {}                             \
     template <typename F>                                                     \
     operator ::testing::Action<F>() const {                                   \
       return ::testing::internal::MakeAction<F, gmock_Impl>();                \
     }                                                                         \
+                                                                              \
    private:                                                                   \
     class gmock_Impl {                                                        \
      public:                                                                  \
@@ -1681,7 +2292,7 @@ template <typename F, typename Impl>
 }  // namespace testing
 
 #ifdef _MSC_VER
-# pragma warning(pop)
+#pragma warning(pop)
 #endif
 
 #endif  // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
index fc7f803a7a6515c21e3fbf9b505b0a76e8b9c670..b6ab648e50a649257120e62fdc404e8e5ba2c1d9 100644 (file)
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file implements some commonly used cardinalities.  More
 // cardinalities can be defined by the user implementing the
 // CardinalityInterface interface if necessary.
 
-// GOOGLETEST_CM0002 DO NOT DELETE
+// IWYU pragma: private, include "gmock/gmock.h"
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
 
 #include <limits.h>
+
 #include <memory>
 #include <ostream>  // NOLINT
+
 #include "gmock/internal/gmock-port.h"
 #include "gtest/gtest.h"
 
@@ -116,7 +118,7 @@ class GTEST_API_ Cardinality {
   // cardinality, i.e. exceed the maximum number of allowed calls.
   bool IsOverSaturatedByCallCount(int call_count) const {
     return impl_->IsSaturatedByCallCount(call_count) &&
-        !impl_->IsSatisfiedByCallCount(call_count);
+           !impl_->IsSatisfiedByCallCount(call_count);
   }
 
   // Describes self to an ostream
index 0fc6f6f3f13ccdaf94a4d055783879a57dcf8dc5..f565d980c56533099e9e175fcb9b0728b8b8e536 100644 (file)
@@ -31,7 +31,8 @@
 //
 // This file implements MOCK_METHOD.
 
-// GOOGLETEST_CM0002 DO NOT DELETE
+// IWYU pragma: private, include "gmock/gmock.h"
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_  // NOLINT
 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_  // NOLINT
@@ -64,6 +65,39 @@ struct ThisRefAdjuster {
   }
 };
 
+constexpr bool PrefixOf(const char* a, const char* b) {
+  return *a == 0 || (*a == *b && internal::PrefixOf(a + 1, b + 1));
+}
+
+template <int N, int M>
+constexpr bool StartsWith(const char (&prefix)[N], const char (&str)[M]) {
+  return N <= M && internal::PrefixOf(prefix, str);
+}
+
+template <int N, int M>
+constexpr bool EndsWith(const char (&suffix)[N], const char (&str)[M]) {
+  return N <= M && internal::PrefixOf(suffix, str + M - N);
+}
+
+template <int N, int M>
+constexpr bool Equals(const char (&a)[N], const char (&b)[M]) {
+  return N == M && internal::PrefixOf(a, b);
+}
+
+template <int N>
+constexpr bool ValidateSpec(const char (&spec)[N]) {
+  return internal::Equals("const", spec) ||
+         internal::Equals("override", spec) ||
+         internal::Equals("final", spec) ||
+         internal::Equals("noexcept", spec) ||
+         (internal::StartsWith("noexcept(", spec) &&
+          internal::EndsWith(")", spec)) ||
+         internal::Equals("ref(&)", spec) ||
+         internal::Equals("ref(&&)", spec) ||
+         (internal::StartsWith("Calltype(", spec) &&
+          internal::EndsWith(")", spec));
+}
+
 }  // namespace internal
 
 // The style guide prohibits "using" statements in a namespace scope
@@ -86,17 +120,18 @@ using internal::FunctionMocker;
 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \
   GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ())
 
-#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec)     \
-  GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args);                                   \
-  GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec);                                   \
-  GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(                                      \
-      GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args));           \
-  GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec)                                     \
-  GMOCK_INTERNAL_MOCK_METHOD_IMPL(                                            \
-      GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec),     \
-      GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec),    \
-      GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec),                                \
-      GMOCK_INTERNAL_GET_CALLTYPE(_Spec), GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \
+#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec)  \
+  GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args);                                \
+  GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec);                                \
+  GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(                                   \
+      GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args));        \
+  GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec)                                  \
+  GMOCK_INTERNAL_MOCK_METHOD_IMPL(                                         \
+      GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec),  \
+      GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \
+      GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec),                             \
+      GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Spec),                             \
+      GMOCK_INTERNAL_GET_REF_SPEC(_Spec),                                  \
       (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)))
 
 #define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \
@@ -166,11 +201,11 @@ using internal::FunctionMocker;
             GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N));               \
   }                                                                            \
   mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)>        \
-      GMOCK_MOCKER_(_N, _Constness, _MethodName)
+  GMOCK_MOCKER_(_N, _Constness, _MethodName)
 
 #define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__
 
-// Five Valid modifiers.
+// Valid modifiers.
 #define GMOCK_INTERNAL_HAS_CONST(_Tuple) \
   GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple))
 
@@ -189,6 +224,14 @@ using internal::FunctionMocker;
       GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \
       _elem, )
 
+#define GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Tuple) \
+  GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE, ~, _Tuple)
+
+#define GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE(_i, _, _elem)          \
+  GMOCK_PP_IF(                                                          \
+      GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem)), \
+      GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), )
+
 #define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \
   GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple)
 
@@ -196,19 +239,25 @@ using internal::FunctionMocker;
   GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \
               GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), )
 
-#define GMOCK_INTERNAL_GET_CALLTYPE(_Tuple) \
-  GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_CALLTYPE_IMPL, ~, _Tuple)
-
-#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem)            \
-  static_assert(                                                          \
-      (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) +    \
-       GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \
-       GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) +    \
-       GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \
-       GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) +      \
-       GMOCK_INTERNAL_IS_CALLTYPE(_elem)) == 1,                           \
-      GMOCK_PP_STRINGIZE(                                                 \
+#ifdef GMOCK_INTERNAL_STRICT_SPEC_ASSERT
+#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \
+  static_assert(                                                     \
+      ::testing::internal::ValidateSpec(GMOCK_PP_STRINGIZE(_elem)),  \
+      "Token \'" GMOCK_PP_STRINGIZE(                                 \
+          _elem) "\' cannot be recognized as a valid specification " \
+                 "modifier. Is a ',' missing?");
+#else
+#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem)                 \
+  static_assert(                                                               \
+      (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) +         \
+       GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) +      \
+       GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) +         \
+       GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) +      \
+       GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) +           \
+       GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem))) == 1, \
+      GMOCK_PP_STRINGIZE(                                                      \
           _elem) " cannot be recognized as a valid specification modifier.");
+#endif  // GMOCK_INTERNAL_STRICT_SPEC_ASSERT
 
 // Modifiers implementation.
 #define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \
@@ -238,26 +287,12 @@ using internal::FunctionMocker;
 
 #define GMOCK_INTERNAL_UNPACK_ref(x) x
 
-#define GMOCK_INTERNAL_GET_CALLTYPE_IMPL(_i, _, _elem)           \
-  GMOCK_PP_IF(GMOCK_INTERNAL_IS_CALLTYPE(_elem),                 \
-              GMOCK_INTERNAL_GET_VALUE_CALLTYPE, GMOCK_PP_EMPTY) \
-  (_elem)
+#define GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem) \
+  GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CALLTYPE_I_, _elem)
+
+#define GMOCK_INTERNAL_DETECT_CALLTYPE_I_Calltype ,
 
-// TODO(iserna): GMOCK_INTERNAL_IS_CALLTYPE and
-// GMOCK_INTERNAL_GET_VALUE_CALLTYPE needed more expansions to work on windows
-// maybe they can be simplified somehow.
-#define GMOCK_INTERNAL_IS_CALLTYPE(_arg) \
-  GMOCK_INTERNAL_IS_CALLTYPE_I(          \
-      GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
-#define GMOCK_INTERNAL_IS_CALLTYPE_I(_arg) GMOCK_PP_IS_ENCLOSED_PARENS(_arg)
-
-#define GMOCK_INTERNAL_GET_VALUE_CALLTYPE(_arg) \
-  GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I(          \
-      GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
-#define GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I(_arg) \
-  GMOCK_PP_IDENTITY _arg
-
-#define GMOCK_INTERNAL_IS_CALLTYPE_HELPER_Calltype
+#define GMOCK_INTERNAL_UNPACK_Calltype(...) __VA_ARGS__
 
 // Note: The use of `identity_t` here allows _Ret to represent return types that
 // would normally need to be specified in a different way. For example, a method
index 86be9c176ebcaf8e8e373626d851f4be2f4687c9..6282901145aa0f09115ff98133b5e39a0322c55f 100644 (file)
@@ -27,7 +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.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // The MATCHER* family of macros can be used in a namespace scope to
 // See googletest/include/gtest/gtest-matchers.h for the definition of class
 // Matcher, class MatcherInterface, and others.
 
-// GOOGLETEST_CM0002 DO NOT DELETE
+// IWYU pragma: private, include "gmock/gmock.h"
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
@@ -313,7 +313,9 @@ class StringMatchResultListener : public MatchResultListener {
  private:
   ::std::stringstream ss_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
+  StringMatchResultListener(const StringMatchResultListener&) = delete;
+  StringMatchResultListener& operator=(const StringMatchResultListener&) =
+      delete;
 };
 
 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
@@ -396,7 +398,7 @@ class MatcherCastImpl {
 // is already a Matcher.  This only compiles when type T can be
 // statically converted to type U.
 template <typename T, typename U>
-class MatcherCastImpl<T, Matcher<U> > {
+class MatcherCastImpl<T, Matcher<U>> {
  public:
   static Matcher<T> Cast(const Matcher<U>& source_matcher) {
     return Matcher<T>(new Impl(source_matcher));
@@ -450,7 +452,7 @@ class MatcherCastImpl<T, Matcher<U> > {
 // This even more specialized version is used for efficiently casting
 // a matcher to its own type.
 template <typename T>
-class MatcherCastImpl<T, Matcher<T> > {
+class MatcherCastImpl<T, Matcher<T>> {
  public:
   static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
 };
@@ -533,19 +535,18 @@ inline Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {
                 "T must be implicitly convertible to U");
   // Enforce that we are not converting a non-reference type T to a reference
   // type U.
-  GTEST_COMPILE_ASSERT_(
-      std::is_reference<T>::value || !std::is_reference<U>::value,
-      cannot_convert_non_reference_arg_to_reference);
+  static_assert(std::is_reference<T>::value || !std::is_reference<U>::value,
+                "cannot convert non reference arg to reference");
   // In case both T and U are arithmetic types, enforce that the
   // conversion is not lossy.
   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
   typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
   constexpr bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
   constexpr bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
-  GTEST_COMPILE_ASSERT_(
+  static_assert(
       kTIsOther || kUIsOther ||
-      (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
-      conversion_of_arithmetic_types_must_be_lossless);
+          (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
+      "conversion of arithmetic types must be lossless");
   return MatcherCast<T>(matcher);
 }
 
@@ -678,9 +679,9 @@ bool TupleMatches(const MatcherTuple& matcher_tuple,
                   const ValueTuple& value_tuple) {
   // Makes sure that matcher_tuple and value_tuple have the same
   // number of fields.
-  GTEST_COMPILE_ASSERT_(std::tuple_size<MatcherTuple>::value ==
-                            std::tuple_size<ValueTuple>::value,
-                        matcher_and_value_have_different_numbers_of_fields);
+  static_assert(std::tuple_size<MatcherTuple>::value ==
+                    std::tuple_size<ValueTuple>::value,
+                "matcher and value have different numbers of fields");
   return TuplePrefix<std::tuple_size<ValueTuple>::value>::Matches(matcher_tuple,
                                                                   value_tuple);
 }
@@ -689,8 +690,7 @@ bool TupleMatches(const MatcherTuple& matcher_tuple,
 // is no failure, nothing will be streamed to os.
 template <typename MatcherTuple, typename ValueTuple>
 void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
-                                const ValueTuple& values,
-                                ::std::ostream* os) {
+                                const ValueTuple& values, ::std::ostream* os) {
   TuplePrefix<std::tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
       matchers, values, os);
 }
@@ -714,14 +714,14 @@ class TransformTupleValuesHelper {
  private:
   template <typename Tup, size_t kRemainingSize>
   struct IterateOverTuple {
-    OutIter operator() (Func f, const Tup& t, OutIter out) const {
+    OutIter operator()(Func f, const Tup& t, OutIter out) const {
       *out++ = f(::std::get<TupleSize::value - kRemainingSize>(t));
       return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
     }
   };
   template <typename Tup>
   struct IterateOverTuple<Tup, 0> {
-    OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
+    OutIter operator()(Func /* f */, const Tup& /* t */, OutIter out) const {
       return out;
     }
   };
@@ -767,9 +767,7 @@ class IsNullMatcher {
   }
 
   void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
-  void DescribeNegationTo(::std::ostream* os) const {
-    *os << "isn't NULL";
-  }
+  void DescribeNegationTo(::std::ostream* os) const { *os << "isn't NULL"; }
 };
 
 // Implements the polymorphic NotNull() matcher, which matches any raw or smart
@@ -783,9 +781,7 @@ class NotNullMatcher {
   }
 
   void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
-  void DescribeNegationTo(::std::ostream* os) const {
-    *os << "is NULL";
-  }
+  void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; }
 };
 
 // Ref(variable) matches any argument that is a reference to
@@ -871,8 +867,7 @@ inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
 // String comparison for narrow or wide strings that can have embedded NUL
 // characters.
 template <typename StringType>
-bool CaseInsensitiveStringEquals(const StringType& s1,
-                                 const StringType& s2) {
+bool CaseInsensitiveStringEquals(const StringType& s1, const StringType& s2) {
   // Are the heads equal?
   if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
     return false;
@@ -933,8 +928,8 @@ class StrEqualityMatcher {
   bool MatchAndExplain(const MatcheeStringType& s,
                        MatchResultListener* /* listener */) const {
     const StringType s2(s);
-    const bool eq = case_sensitive_ ? s2 == string_ :
-        CaseInsensitiveStringEquals(s2, string_);
+    const bool eq = case_sensitive_ ? s2 == string_
+                                    : CaseInsensitiveStringEquals(s2, string_);
     return expect_eq_ == eq;
   }
 
@@ -1021,8 +1016,7 @@ class HasSubstrMatcher {
 template <typename StringType>
 class StartsWithMatcher {
  public:
-  explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
-  }
+  explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {}
 
 #if GTEST_INTERNAL_HAS_STRING_VIEW
   bool MatchAndExplain(const internal::StringView& s,
@@ -1053,7 +1047,7 @@ class StartsWithMatcher {
                        MatchResultListener* /* listener */) const {
     const StringType& s2(s);
     return s2.length() >= prefix_.length() &&
-        s2.substr(0, prefix_.length()) == prefix_;
+           s2.substr(0, prefix_.length()) == prefix_;
   }
 
   void DescribeTo(::std::ostream* os) const {
@@ -1107,7 +1101,7 @@ class EndsWithMatcher {
                        MatchResultListener* /* listener */) const {
     const StringType& s2(s);
     return s2.length() >= suffix_.length() &&
-        s2.substr(s2.length() - suffix_.length()) == suffix_;
+           s2.substr(s2.length() - suffix_.length()) == suffix_;
   }
 
   void DescribeTo(::std::ostream* os) const {
@@ -1124,6 +1118,45 @@ class EndsWithMatcher {
   const StringType suffix_;
 };
 
+// Implements the polymorphic WhenBase64Unescaped(matcher) matcher, which can be
+// used as a Matcher<T> as long as T can be converted to a string.
+class WhenBase64UnescapedMatcher {
+ public:
+  using is_gtest_matcher = void;
+
+  explicit WhenBase64UnescapedMatcher(
+      const Matcher<const std::string&>& internal_matcher)
+      : internal_matcher_(internal_matcher) {}
+
+  // Matches anything that can convert to std::string.
+  template <typename MatcheeStringType>
+  bool MatchAndExplain(const MatcheeStringType& s,
+                       MatchResultListener* listener) const {
+    const std::string s2(s);  // NOLINT (needed for working with string_view).
+    std::string unescaped;
+    if (!internal::Base64Unescape(s2, &unescaped)) {
+      if (listener != nullptr) {
+        *listener << "is not a valid base64 escaped string";
+      }
+      return false;
+    }
+    return MatchPrintAndExplain(unescaped, internal_matcher_, listener);
+  }
+
+  void DescribeTo(::std::ostream* os) const {
+    *os << "matches after Base64Unescape ";
+    internal_matcher_.DescribeTo(os);
+  }
+
+  void DescribeNegationTo(::std::ostream* os) const {
+    *os << "does not match after Base64Unescape ";
+    internal_matcher_.DescribeTo(os);
+  }
+
+ private:
+  const Matcher<const std::string&> internal_matcher_;
+};
+
 // Implements a matcher that compares the two fields of a 2-tuple
 // using one of the ==, <=, <, etc, operators.  The two fields being
 // compared don't have to have the same type.
@@ -1197,8 +1230,7 @@ class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
 template <typename T>
 class NotMatcherImpl : public MatcherInterface<const T&> {
  public:
-  explicit NotMatcherImpl(const Matcher<T>& matcher)
-      : matcher_(matcher) {}
+  explicit NotMatcherImpl(const Matcher<T>& matcher) : matcher_(matcher) {}
 
   bool MatchAndExplain(const T& x,
                        MatchResultListener* listener) const override {
@@ -1242,7 +1274,7 @@ class NotMatcher {
 template <typename T>
 class AllOfMatcherImpl : public MatcherInterface<const T&> {
  public:
-  explicit AllOfMatcherImpl(std::vector<Matcher<T> > matchers)
+  explicit AllOfMatcherImpl(std::vector<Matcher<T>> matchers)
       : matchers_(std::move(matchers)) {}
 
   void DescribeTo(::std::ostream* os) const override {
@@ -1293,7 +1325,7 @@ class AllOfMatcherImpl : public MatcherInterface<const T&> {
   }
 
  private:
-  const std::vector<Matcher<T> > matchers_;
+  const std::vector<Matcher<T>> matchers_;
 };
 
 // VariadicMatcher is used for the variadic implementation of
@@ -1316,14 +1348,14 @@ class VariadicMatcher {
   // all of the provided matchers (Matcher1, Matcher2, ...) can match.
   template <typename T>
   operator Matcher<T>() const {
-    std::vector<Matcher<T> > values;
+    std::vector<Matcher<T>> values;
     CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>());
     return Matcher<T>(new CombiningMatcher<T>(std::move(values)));
   }
 
  private:
   template <typename T, size_t I>
-  void CreateVariadicMatcher(std::vector<Matcher<T> >* values,
+  void CreateVariadicMatcher(std::vector<Matcher<T>>* values,
                              std::integral_constant<size_t, I>) const {
     values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_)));
     CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>());
@@ -1331,7 +1363,7 @@ class VariadicMatcher {
 
   template <typename T>
   void CreateVariadicMatcher(
-      std::vector<Matcher<T> >*,
+      std::vector<Matcher<T>>*,
       std::integral_constant<size_t, sizeof...(Args)>) const {}
 
   std::tuple<Args...> matchers_;
@@ -1347,7 +1379,7 @@ using AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>;
 template <typename T>
 class AnyOfMatcherImpl : public MatcherInterface<const T&> {
  public:
-  explicit AnyOfMatcherImpl(std::vector<Matcher<T> > matchers)
+  explicit AnyOfMatcherImpl(std::vector<Matcher<T>> matchers)
       : matchers_(std::move(matchers)) {}
 
   void DescribeTo(::std::ostream* os) const override {
@@ -1398,13 +1430,35 @@ class AnyOfMatcherImpl : public MatcherInterface<const T&> {
   }
 
  private:
-  const std::vector<Matcher<T> > matchers_;
+  const std::vector<Matcher<T>> matchers_;
 };
 
 // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
 template <typename... Args>
 using AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>;
 
+// ConditionalMatcher is the implementation of Conditional(cond, m1, m2)
+template <typename MatcherTrue, typename MatcherFalse>
+class ConditionalMatcher {
+ public:
+  ConditionalMatcher(bool condition, MatcherTrue matcher_true,
+                     MatcherFalse matcher_false)
+      : condition_(condition),
+        matcher_true_(std::move(matcher_true)),
+        matcher_false_(std::move(matcher_false)) {}
+
+  template <typename T>
+  operator Matcher<T>() const {  // NOLINT(runtime/explicit)
+    return condition_ ? SafeMatcherCast<T>(matcher_true_)
+                      : SafeMatcherCast<T>(matcher_false_);
+  }
+
+ private:
+  bool condition_;
+  MatcherTrue matcher_true_;
+  MatcherFalse matcher_false_;
+};
+
 // Wrapper for implementation of Any/AllOfArray().
 template <template <class> class MatcherImpl, typename T>
 class SomeOfArrayMatcher {
@@ -1454,8 +1508,7 @@ class TrulyMatcher {
     // We cannot write 'return !!predicate_(x);' as that doesn't work
     // when predicate_(x) returns a class convertible to bool but
     // having no operator!().
-    if (predicate_(x))
-      return true;
+    if (predicate_(x)) return true;
     *listener << "didn't satisfy the given predicate";
     return false;
   }
@@ -1563,8 +1616,8 @@ class PredicateFormatterFromMatcher {
 // used for implementing ASSERT_THAT() and EXPECT_THAT().
 // Implementation detail: 'matcher' is received by-value to force decaying.
 template <typename M>
-inline PredicateFormatterFromMatcher<M>
-MakePredicateFormatterFromMatcher(M matcher) {
+inline PredicateFormatterFromMatcher<M> MakePredicateFormatterFromMatcher(
+    M matcher) {
   return PredicateFormatterFromMatcher<M>(std::move(matcher));
 }
 
@@ -1579,9 +1632,7 @@ class IsNanMatcher {
   }
 
   void DescribeTo(::std::ostream* os) const { *os << "is NaN"; }
-  void DescribeNegationTo(::std::ostream* os) const {
-    *os << "isn't NaN";
-  }
+  void DescribeNegationTo(::std::ostream* os) const { *os << "isn't NaN"; }
 };
 
 // Implements the polymorphic floating point equality matcher, which matches
@@ -1597,9 +1648,8 @@ class FloatingEqMatcher {
   // equality comparisons between NANs will always return false.  We specify a
   // negative max_abs_error_ term to indicate that ULP-based approximation will
   // be used for comparison.
-  FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
-    expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
-  }
+  FloatingEqMatcher(FloatType expected, bool nan_eq_nan)
+      : expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {}
 
   // Constructor that supports a user-specified max_abs_error that will be used
   // for comparison instead of ULP-based approximation.  The max absolute
@@ -1661,8 +1711,8 @@ class FloatingEqMatcher {
       // os->precision() returns the previously set precision, which we
       // store to restore the ostream to its original configuration
       // after outputting.
-      const ::std::streamsize old_precision = os->precision(
-          ::std::numeric_limits<FloatType>::digits10 + 2);
+      const ::std::streamsize old_precision =
+          os->precision(::std::numeric_limits<FloatType>::digits10 + 2);
       if (FloatingPoint<FloatType>(expected_).is_nan()) {
         if (nan_eq_nan_) {
           *os << "is NaN";
@@ -1680,8 +1730,8 @@ class FloatingEqMatcher {
 
     void DescribeNegationTo(::std::ostream* os) const override {
       // As before, get original precision.
-      const ::std::streamsize old_precision = os->precision(
-          ::std::numeric_limits<FloatType>::digits10 + 2);
+      const ::std::streamsize old_precision =
+          os->precision(::std::numeric_limits<FloatType>::digits10 + 2);
       if (FloatingPoint<FloatType>(expected_).is_nan()) {
         if (nan_eq_nan_) {
           *os << "isn't NaN";
@@ -1699,9 +1749,7 @@ class FloatingEqMatcher {
     }
 
    private:
-    bool HasMaxAbsError() const {
-      return max_abs_error_ >= 0;
-    }
+    bool HasMaxAbsError() const { return max_abs_error_ >= 0; }
 
     const FloatType expected_;
     const bool nan_eq_nan_;
@@ -1773,9 +1821,8 @@ class FloatingEq2Matcher {
   template <typename Tuple>
   class Impl : public MatcherInterface<Tuple> {
    public:
-    Impl(FloatType max_abs_error, bool nan_eq_nan) :
-        max_abs_error_(max_abs_error),
-        nan_eq_nan_(nan_eq_nan) {}
+    Impl(FloatType max_abs_error, bool nan_eq_nan)
+        : max_abs_error_(max_abs_error), nan_eq_nan_(nan_eq_nan) {}
 
     bool MatchAndExplain(Tuple args,
                          MatchResultListener* listener) const override {
@@ -1951,9 +1998,7 @@ class WhenDynamicCastToMatcherBase {
  protected:
   const Matcher<To> matcher_;
 
-  static std::string GetToName() {
-    return GetTypeName<To>();
-  }
+  static std::string GetToName() { return GetTypeName<To>(); }
 
  private:
   static void GetCastTypeDescription(::std::ostream* os) {
@@ -2090,7 +2135,7 @@ class PropertyMatcher {
   }
 
   template <typename T>
-  bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
+  bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
     return MatchAndExplainImpl(
         typename std::is_pointer<typename std::remove_const<T>::type>::type(),
         value, listener);
@@ -2142,16 +2187,16 @@ struct CallableTraits {
 
 // Specialization for function pointers.
 template <typename ArgType, typename ResType>
-struct CallableTraits<ResType(*)(ArgType)> {
+struct CallableTraits<ResType (*)(ArgType)> {
   typedef ResType ResultType;
-  typedef ResType(*StorageType)(ArgType);
+  typedef ResType (*StorageType)(ArgType);
 
-  static void CheckIsValid(ResType(*f)(ArgType)) {
+  static void CheckIsValid(ResType (*f)(ArgType)) {
     GTEST_CHECK_(f != nullptr)
         << "NULL function pointer is passed into ResultOf().";
   }
   template <typename T>
-  static ResType Invoke(ResType(*f)(ArgType), T arg) {
+  static ResType Invoke(ResType (*f)(ArgType), T arg) {
     return (*f)(arg);
   }
 };
@@ -2162,13 +2207,21 @@ template <typename Callable, typename InnerMatcher>
 class ResultOfMatcher {
  public:
   ResultOfMatcher(Callable callable, InnerMatcher matcher)
-      : callable_(std::move(callable)), matcher_(std::move(matcher)) {
+      : ResultOfMatcher(/*result_description=*/"", std::move(callable),
+                        std::move(matcher)) {}
+
+  ResultOfMatcher(const std::string& result_description, Callable callable,
+                  InnerMatcher matcher)
+      : result_description_(result_description),
+        callable_(std::move(callable)),
+        matcher_(std::move(matcher)) {
     CallableTraits<Callable>::CheckIsValid(callable_);
   }
 
   template <typename T>
   operator Matcher<T>() const {
-    return Matcher<T>(new Impl<const T&>(callable_, matcher_));
+    return Matcher<T>(
+        new Impl<const T&>(result_description_, callable_, matcher_));
   }
 
  private:
@@ -2181,21 +2234,36 @@ class ResultOfMatcher {
 
    public:
     template <typename M>
-    Impl(const CallableStorageType& callable, const M& matcher)
-        : callable_(callable), matcher_(MatcherCast<ResultType>(matcher)) {}
+    Impl(const std::string& result_description,
+         const CallableStorageType& callable, const M& matcher)
+        : result_description_(result_description),
+          callable_(callable),
+          matcher_(MatcherCast<ResultType>(matcher)) {}
 
     void DescribeTo(::std::ostream* os) const override {
-      *os << "is mapped by the given callable to a value that ";
+      if (result_description_.empty()) {
+        *os << "is mapped by the given callable to a value that ";
+      } else {
+        *os << "whose " << result_description_ << " ";
+      }
       matcher_.DescribeTo(os);
     }
 
     void DescribeNegationTo(::std::ostream* os) const override {
-      *os << "is mapped by the given callable to a value that ";
+      if (result_description_.empty()) {
+        *os << "is mapped by the given callable to a value that ";
+      } else {
+        *os << "whose " << result_description_ << " ";
+      }
       matcher_.DescribeNegationTo(os);
     }
 
     bool MatchAndExplain(T obj, MatchResultListener* listener) const override {
-      *listener << "which is mapped by the given callable to ";
+      if (result_description_.empty()) {
+        *listener << "which is mapped by the given callable to ";
+      } else {
+        *listener << "whose " << result_description_ << " is ";
+      }
       // Cannot pass the return value directly to MatchPrintAndExplain, which
       // takes a non-const reference as argument.
       // Also, specifying template argument explicitly is needed because T could
@@ -2206,6 +2274,7 @@ class ResultOfMatcher {
     }
 
    private:
+    const std::string result_description_;
     // Functors often define operator() as non-const method even though
     // they are actually stateless. But we need to use them even when
     // 'this' is a const pointer. It's the user's responsibility not to
@@ -2215,6 +2284,7 @@ class ResultOfMatcher {
     const Matcher<ResultType> matcher_;
   };  // class Impl
 
+  const std::string result_description_;
   const CallableStorageType callable_;
   const InnerMatcher matcher_;
 };
@@ -2224,8 +2294,7 @@ template <typename SizeMatcher>
 class SizeIsMatcher {
  public:
   explicit SizeIsMatcher(const SizeMatcher& size_matcher)
-       : size_matcher_(size_matcher) {
-  }
+      : size_matcher_(size_matcher) {}
 
   template <typename Container>
   operator Matcher<Container>() const {
@@ -2253,8 +2322,8 @@ class SizeIsMatcher {
       SizeType size = container.size();
       StringMatchResultListener size_listener;
       const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
-      *listener
-          << "whose size " << size << (result ? " matches" : " doesn't match");
+      *listener << "whose size " << size
+                << (result ? " matches" : " doesn't match");
       PrintIfNotEmpty(size_listener.str(), listener->stream());
       return result;
     }
@@ -2283,8 +2352,9 @@ class BeginEndDistanceIsMatcher {
   template <typename Container>
   class Impl : public MatcherInterface<Container> {
    public:
-    typedef internal::StlContainerView<
-        GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
+    typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_(
+        Container)>
+        ContainerView;
     typedef typename std::iterator_traits<
         typename ContainerView::type::const_iterator>::difference_type
         DistanceType;
@@ -2364,18 +2434,15 @@ class ContainerEqMatcher {
     typedef internal::StlContainerView<
         typename std::remove_const<LhsContainer>::type>
         LhsView;
-    typedef typename LhsView::type LhsStlContainer;
     StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
-    if (lhs_stl_container == expected_)
-      return true;
+    if (lhs_stl_container == expected_) return true;
 
     ::std::ostream* const os = listener->stream();
     if (os != nullptr) {
       // Something is different. Check for extra values first.
       bool printed_header = false;
-      for (typename LhsStlContainer::const_iterator it =
-               lhs_stl_container.begin();
-           it != lhs_stl_container.end(); ++it) {
+      for (auto it = lhs_stl_container.begin(); it != lhs_stl_container.end();
+           ++it) {
         if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
             expected_.end()) {
           if (printed_header) {
@@ -2390,11 +2457,10 @@ class ContainerEqMatcher {
 
       // Now check for missing values.
       bool printed_header2 = false;
-      for (typename StlContainer::const_iterator it = expected_.begin();
-           it != expected_.end(); ++it) {
-        if (internal::ArrayAwareFind(
-                lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
-            lhs_stl_container.end()) {
+      for (auto it = expected_.begin(); it != expected_.end(); ++it) {
+        if (internal::ArrayAwareFind(lhs_stl_container.begin(),
+                                     lhs_stl_container.end(),
+                                     *it) == lhs_stl_container.end()) {
           if (printed_header2) {
             *os << ", ";
           } else {
@@ -2417,7 +2483,9 @@ class ContainerEqMatcher {
 // A comparator functor that uses the < operator to compare two values.
 struct LessComparator {
   template <typename T, typename U>
-  bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
+  bool operator()(const T& lhs, const U& rhs) const {
+    return lhs < rhs;
+  }
 };
 
 // Implements WhenSortedBy(comparator, container_matcher).
@@ -2436,14 +2504,16 @@ class WhenSortedByMatcher {
   template <typename LhsContainer>
   class Impl : public MatcherInterface<LhsContainer> {
    public:
-    typedef internal::StlContainerView<
-         GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
+    typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_(
+        LhsContainer)>
+        LhsView;
     typedef typename LhsView::type LhsStlContainer;
     typedef typename LhsView::const_reference LhsStlContainerReference;
     // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
     // so that we can match associative containers.
-    typedef typename RemoveConstFromKey<
-        typename LhsStlContainer::value_type>::type LhsValue;
+    typedef
+        typename RemoveConstFromKey<typename LhsStlContainer::value_type>::type
+            LhsValue;
 
     Impl(const Comparator& comparator, const ContainerMatcher& matcher)
         : comparator_(comparator), matcher_(matcher) {}
@@ -2463,8 +2533,8 @@ class WhenSortedByMatcher {
       LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
       ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
                                                lhs_stl_container.end());
-      ::std::sort(
-           sorted_container.begin(), sorted_container.end(), comparator_);
+      ::std::sort(sorted_container.begin(), sorted_container.end(),
+                  comparator_);
 
       if (!listener->IsInterested()) {
         // If the listener is not interested, we do not need to
@@ -2477,8 +2547,8 @@ class WhenSortedByMatcher {
       *listener << " when sorted";
 
       StringMatchResultListener inner_listener;
-      const bool match = matcher_.MatchAndExplain(sorted_container,
-                                                  &inner_listener);
+      const bool match =
+          matcher_.MatchAndExplain(sorted_container, &inner_listener);
       PrintIfNotEmpty(inner_listener.str(), listener->stream());
       return match;
     }
@@ -2487,7 +2557,8 @@ class WhenSortedByMatcher {
     const Comparator comparator_;
     const Matcher<const ::std::vector<LhsValue>&> matcher_;
 
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
+    Impl(const Impl&) = delete;
+    Impl& operator=(const Impl&) = delete;
   };
 
  private:
@@ -2501,9 +2572,9 @@ class WhenSortedByMatcher {
 // container and the RHS container respectively.
 template <typename TupleMatcher, typename RhsContainer>
 class PointwiseMatcher {
-  GTEST_COMPILE_ASSERT_(
+  static_assert(
       !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,
-      use_UnorderedPointwise_with_hash_tables);
+      "use UnorderedPointwise with hash tables");
 
  public:
   typedef internal::StlContainerView<RhsContainer> RhsView;
@@ -2522,9 +2593,9 @@ class PointwiseMatcher {
 
   template <typename LhsContainer>
   operator Matcher<LhsContainer>() const {
-    GTEST_COMPILE_ASSERT_(
+    static_assert(
         !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,
-        use_UnorderedPointwise_with_hash_tables);
+        "use UnorderedPointwise with hash tables");
 
     return Matcher<LhsContainer>(
         new Impl<const LhsContainer&>(tuple_matcher_, rhs_));
@@ -2533,8 +2604,9 @@ class PointwiseMatcher {
   template <typename LhsContainer>
   class Impl : public MatcherInterface<LhsContainer> {
    public:
-    typedef internal::StlContainerView<
-         GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
+    typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_(
+        LhsContainer)>
+        LhsView;
     typedef typename LhsView::type LhsStlContainer;
     typedef typename LhsView::const_reference LhsStlContainerReference;
     typedef typename LhsStlContainer::value_type LhsValue;
@@ -2574,14 +2646,14 @@ class PointwiseMatcher {
         return false;
       }
 
-      typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
-      typename RhsStlContainer::const_iterator right = rhs_.begin();
+      auto left = lhs_stl_container.begin();
+      auto right = rhs_.begin();
       for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
         if (listener->IsInterested()) {
           StringMatchResultListener inner_listener;
           // Create InnerMatcherArg as a temporarily object to avoid it outlives
           // *left and *right. Dereference or the conversion to `const T&` may
-          // return temp objects, e.g for vector<bool>.
+          // return temp objects, e.g. for vector<bool>.
           if (!mono_tuple_matcher_.MatchAndExplain(
                   InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),
                                   ImplicitCast_<const RhsValue&>(*right)),
@@ -2628,18 +2700,17 @@ class QuantifierMatcherImpl : public MatcherInterface<Container> {
   template <typename InnerMatcher>
   explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
       : inner_matcher_(
-           testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
+            testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
 
   // Checks whether:
   // * All elements in the container match, if all_elements_should_match.
   // * Any element in the container matches, if !all_elements_should_match.
-  bool MatchAndExplainImpl(bool all_elements_should_match,
-                           Container container,
+  bool MatchAndExplainImpl(bool all_elements_should_match, Container container,
                            MatchResultListener* listener) const {
     StlContainerReference stl_container = View::ConstReference(container);
     size_t i = 0;
-    for (typename StlContainer::const_iterator it = stl_container.begin();
-         it != stl_container.end(); ++it, ++i) {
+    for (auto it = stl_container.begin(); it != stl_container.end();
+         ++it, ++i) {
       StringMatchResultListener inner_listener;
       const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
 
@@ -2653,6 +2724,54 @@ class QuantifierMatcherImpl : public MatcherInterface<Container> {
     return all_elements_should_match;
   }
 
+  bool MatchAndExplainImpl(const Matcher<size_t>& count_matcher,
+                           Container container,
+                           MatchResultListener* listener) const {
+    StlContainerReference stl_container = View::ConstReference(container);
+    size_t i = 0;
+    std::vector<size_t> match_elements;
+    for (auto it = stl_container.begin(); it != stl_container.end();
+         ++it, ++i) {
+      StringMatchResultListener inner_listener;
+      const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
+      if (matches) {
+        match_elements.push_back(i);
+      }
+    }
+    if (listener->IsInterested()) {
+      if (match_elements.empty()) {
+        *listener << "has no element that matches";
+      } else if (match_elements.size() == 1) {
+        *listener << "whose element #" << match_elements[0] << " matches";
+      } else {
+        *listener << "whose elements (";
+        std::string sep = "";
+        for (size_t e : match_elements) {
+          *listener << sep << e;
+          sep = ", ";
+        }
+        *listener << ") match";
+      }
+    }
+    StringMatchResultListener count_listener;
+    if (count_matcher.MatchAndExplain(match_elements.size(), &count_listener)) {
+      *listener << " and whose match quantity of " << match_elements.size()
+                << " matches";
+      PrintIfNotEmpty(count_listener.str(), listener->stream());
+      return true;
+    } else {
+      if (match_elements.empty()) {
+        *listener << " and";
+      } else {
+        *listener << " but";
+      }
+      *listener << " whose match quantity of " << match_elements.size()
+                << " does not match";
+      PrintIfNotEmpty(count_listener.str(), listener->stream());
+      return false;
+    }
+  }
+
  protected:
   const Matcher<const Element&> inner_matcher_;
 };
@@ -2709,6 +2828,58 @@ class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
   }
 };
 
+// Implements Contains(element_matcher).Times(n) for the given argument type
+// Container.
+template <typename Container>
+class ContainsTimesMatcherImpl : public QuantifierMatcherImpl<Container> {
+ public:
+  template <typename InnerMatcher>
+  explicit ContainsTimesMatcherImpl(InnerMatcher inner_matcher,
+                                    Matcher<size_t> count_matcher)
+      : QuantifierMatcherImpl<Container>(inner_matcher),
+        count_matcher_(std::move(count_matcher)) {}
+
+  void DescribeTo(::std::ostream* os) const override {
+    *os << "quantity of elements that match ";
+    this->inner_matcher_.DescribeTo(os);
+    *os << " ";
+    count_matcher_.DescribeTo(os);
+  }
+
+  void DescribeNegationTo(::std::ostream* os) const override {
+    *os << "quantity of elements that match ";
+    this->inner_matcher_.DescribeTo(os);
+    *os << " ";
+    count_matcher_.DescribeNegationTo(os);
+  }
+
+  bool MatchAndExplain(Container container,
+                       MatchResultListener* listener) const override {
+    return this->MatchAndExplainImpl(count_matcher_, container, listener);
+  }
+
+ private:
+  const Matcher<size_t> count_matcher_;
+};
+
+// Implements polymorphic Contains(element_matcher).Times(n).
+template <typename M>
+class ContainsTimesMatcher {
+ public:
+  explicit ContainsTimesMatcher(M m, Matcher<size_t> count_matcher)
+      : inner_matcher_(m), count_matcher_(std::move(count_matcher)) {}
+
+  template <typename Container>
+  operator Matcher<Container>() const {  // NOLINT
+    return Matcher<Container>(new ContainsTimesMatcherImpl<const Container&>(
+        inner_matcher_, count_matcher_));
+  }
+
+ private:
+  const M inner_matcher_;
+  const Matcher<size_t> count_matcher_;
+};
+
 // Implements polymorphic Contains(element_matcher).
 template <typename M>
 class ContainsMatcher {
@@ -2716,11 +2887,15 @@ class ContainsMatcher {
   explicit ContainsMatcher(M m) : inner_matcher_(m) {}
 
   template <typename Container>
-  operator Matcher<Container>() const {
+  operator Matcher<Container>() const {  // NOLINT
     return Matcher<Container>(
         new ContainsMatcherImpl<const Container&>(inner_matcher_));
   }
 
+  ContainsTimesMatcher<M> Times(Matcher<size_t> count_matcher) const {
+    return ContainsTimesMatcher<M>(inner_matcher_, std::move(count_matcher));
+  }
+
  private:
   const M inner_matcher_;
 };
@@ -2732,7 +2907,7 @@ class EachMatcher {
   explicit EachMatcher(M m) : inner_matcher_(m) {}
 
   template <typename Container>
-  operator Matcher<Container>() const {
+  operator Matcher<Container>() const {  // NOLINT
     return Matcher<Container>(
         new EachMatcherImpl<const Container&>(inner_matcher_));
   }
@@ -2778,8 +2953,7 @@ class KeyMatcherImpl : public MatcherInterface<PairType> {
   template <typename InnerMatcher>
   explicit KeyMatcherImpl(InnerMatcher inner_matcher)
       : inner_matcher_(
-          testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
-  }
+            testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {}
 
   // Returns true if and only if 'key_value.first' (the key) matches the inner
   // matcher.
@@ -2884,8 +3058,7 @@ class PairMatcherImpl : public MatcherInterface<PairType> {
       : first_matcher_(
             testing::SafeMatcherCast<const FirstType&>(first_matcher)),
         second_matcher_(
-            testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
-  }
+            testing::SafeMatcherCast<const SecondType&>(second_matcher)) {}
 
   // Describes what this matcher does.
   void DescribeTo(::std::ostream* os) const override {
@@ -2963,7 +3136,7 @@ class PairMatcher {
       : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
 
   template <typename PairType>
-  operator Matcher<PairType> () const {
+  operator Matcher<PairType>() const {
     return Matcher<PairType>(
         new PairMatcherImpl<const PairType&>(first_matcher_, second_matcher_));
   }
@@ -3235,7 +3408,7 @@ class ElementsAreMatcherImpl : public MatcherInterface<Container> {
     // explanations[i] is the explanation of the element at index i.
     ::std::vector<std::string> explanations(count());
     StlContainerReference stl_container = View::ConstReference(container);
-    typename StlContainer::const_iterator it = stl_container.begin();
+    auto it = stl_container.begin();
     size_t exam_pos = 0;
     bool mismatch_found = false;  // Have we found a mismatched element yet?
 
@@ -3312,7 +3485,7 @@ class ElementsAreMatcherImpl : public MatcherInterface<Container> {
 
   size_t count() const { return matchers_.size(); }
 
-  ::std::vector<Matcher<const Element&> > matchers_;
+  ::std::vector<Matcher<const Element&>> matchers_;
 };
 
 // Connectivity matrix of (elements X matchers), in element-major order.
@@ -3324,8 +3497,7 @@ class GTEST_API_ MatchMatrix {
   MatchMatrix(size_t num_elements, size_t num_matchers)
       : num_elements_(num_elements),
         num_matchers_(num_matchers),
-        matched_(num_elements_* num_matchers_, 0) {
-  }
+        matched_(num_elements_ * num_matchers_, 0) {}
 
   size_t LhsSize() const { return num_elements_; }
   size_t RhsSize() const { return num_matchers_; }
@@ -3364,8 +3536,7 @@ typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
 
 // Returns a maximum bipartite matching for the specified graph 'g'.
 // The matching is represented as a vector of {element, matcher} pairs.
-GTEST_API_ ElementMatcherPairs
-FindMaxBipartiteMatching(const MatchMatrix& g);
+GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g);
 
 struct UnorderedMatcherRequire {
   enum Flags {
@@ -3402,9 +3573,7 @@ class GTEST_API_ UnorderedElementsAreMatcherImplBase {
   bool FindPairing(const MatchMatrix& matrix,
                    MatchResultListener* listener) const;
 
-  MatcherDescriberVec& matcher_describers() {
-    return matcher_describers_;
-  }
+  MatcherDescriberVec& matcher_describers() { return matcher_describers_; }
 
   static Message Elements(size_t n) {
     return Message() << n << " element" << (n == 1 ? "" : "s");
@@ -3428,7 +3597,6 @@ class UnorderedElementsAreMatcherImpl
   typedef internal::StlContainerView<RawContainer> View;
   typedef typename View::type StlContainer;
   typedef typename View::const_reference StlContainerReference;
-  typedef typename StlContainer::const_iterator StlContainerConstIterator;
   typedef typename StlContainer::value_type Element;
 
   template <typename InputIter>
@@ -3511,7 +3679,7 @@ class UnorderedElementsAreMatcherImpl
     return matrix;
   }
 
-  ::std::vector<Matcher<const Element&> > matchers_;
+  ::std::vector<Matcher<const Element&>> matchers_;
 };
 
 // Functor for use in TransformTuple.
@@ -3536,7 +3704,7 @@ class UnorderedElementsAreMatcher {
     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
     typedef typename internal::StlContainerView<RawContainer>::type View;
     typedef typename View::value_type Element;
-    typedef ::std::vector<Matcher<const Element&> > MatcherVec;
+    typedef ::std::vector<Matcher<const Element&>> MatcherVec;
     MatcherVec matchers;
     matchers.reserve(::std::tuple_size<MatcherTuple>::value);
     TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
@@ -3559,15 +3727,15 @@ class ElementsAreMatcher {
 
   template <typename Container>
   operator Matcher<Container>() const {
-    GTEST_COMPILE_ASSERT_(
+    static_assert(
         !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||
             ::std::tuple_size<MatcherTuple>::value < 2,
-        use_UnorderedElementsAre_with_hash_tables);
+        "use UnorderedElementsAre with hash tables");
 
     typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
     typedef typename internal::StlContainerView<RawContainer>::type View;
     typedef typename View::value_type Element;
-    typedef ::std::vector<Matcher<const Element&> > MatcherVec;
+    typedef ::std::vector<Matcher<const Element&>> MatcherVec;
     MatcherVec matchers;
     matchers.reserve(::std::tuple_size<MatcherTuple>::value);
     TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
@@ -3610,9 +3778,9 @@ class ElementsAreArrayMatcher {
 
   template <typename Container>
   operator Matcher<Container>() const {
-    GTEST_COMPILE_ASSERT_(
+    static_assert(
         !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,
-        use_UnorderedElementsAreArray_with_hash_tables);
+        "use UnorderedElementsAreArray with hash tables");
 
     return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(
         matchers_.begin(), matchers_.end()));
@@ -3702,9 +3870,9 @@ BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
 // 'negation' is false; otherwise returns the description of the
 // negation of the matcher.  'param_values' contains a list of strings
 // that are the print-out of the matcher's parameters.
-GTEST_API_ std::string FormatMatcherDescription(bool negation,
-                                                const char* matcher_name,
-                                                const Strings& param_values);
+GTEST_API_ std::string FormatMatcherDescription(
+    bool negation, const char* matcher_name,
+    const std::vector<const char*>& param_names, const Strings& param_values);
 
 // Implements a matcher that checks the value of a optional<> type variable.
 template <typename ValueMatcher>
@@ -3981,26 +4149,26 @@ ElementsAreArray(Iter first, Iter last) {
 }
 
 template <typename T>
-inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
-    const T* pointer, size_t count) {
+inline auto ElementsAreArray(const T* pointer, size_t count)
+    -> decltype(ElementsAreArray(pointer, pointer + count)) {
   return ElementsAreArray(pointer, pointer + count);
 }
 
 template <typename T, size_t N>
-inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
-    const T (&array)[N]) {
+inline auto ElementsAreArray(const T (&array)[N])
+    -> decltype(ElementsAreArray(array, N)) {
   return ElementsAreArray(array, N);
 }
 
 template <typename Container>
-inline internal::ElementsAreArrayMatcher<typename Container::value_type>
-ElementsAreArray(const Container& container) {
+inline auto ElementsAreArray(const Container& container)
+    -> decltype(ElementsAreArray(container.begin(), container.end())) {
   return ElementsAreArray(container.begin(), container.end());
 }
 
 template <typename T>
-inline internal::ElementsAreArrayMatcher<T>
-ElementsAreArray(::std::initializer_list<T> xs) {
+inline auto ElementsAreArray(::std::initializer_list<T> xs)
+    -> decltype(ElementsAreArray(xs.begin(), xs.end())) {
   return ElementsAreArray(xs.begin(), xs.end());
 }
 
@@ -4027,14 +4195,14 @@ UnorderedElementsAreArray(Iter first, Iter last) {
 }
 
 template <typename T>
-inline internal::UnorderedElementsAreArrayMatcher<T>
-UnorderedElementsAreArray(const T* pointer, size_t count) {
+inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(
+    const T* pointer, size_t count) {
   return UnorderedElementsAreArray(pointer, pointer + count);
 }
 
 template <typename T, size_t N>
-inline internal::UnorderedElementsAreArrayMatcher<T>
-UnorderedElementsAreArray(const T (&array)[N]) {
+inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(
+    const T (&array)[N]) {
   return UnorderedElementsAreArray(array, N);
 }
 
@@ -4046,8 +4214,8 @@ UnorderedElementsAreArray(const Container& container) {
 }
 
 template <typename T>
-inline internal::UnorderedElementsAreArrayMatcher<T>
-UnorderedElementsAreArray(::std::initializer_list<T> xs) {
+inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(
+    ::std::initializer_list<T> xs) {
   return UnorderedElementsAreArray(xs.begin(), xs.end());
 }
 
@@ -4081,14 +4249,14 @@ Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
 }
 
 // Creates a polymorphic matcher that matches any NULL pointer.
-inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
+inline PolymorphicMatcher<internal::IsNullMatcher> IsNull() {
   return MakePolymorphicMatcher(internal::IsNullMatcher());
 }
 
 // Creates a polymorphic matcher that matches any non-NULL pointer.
 // This is convenient as Not(NULL) doesn't compile (the compiler
 // thinks that that expression is comparing a pointer with an integer).
-inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
+inline PolymorphicMatcher<internal::NotNullMatcher> NotNull() {
   return MakePolymorphicMatcher(internal::NotNullMatcher());
 }
 
@@ -4119,8 +4287,8 @@ inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
 // Creates a matcher that matches any double argument approximately equal to
 // rhs, up to the specified max absolute error bound, where two NANs are
 // considered unequal.  The max absolute error bound must be non-negative.
-inline internal::FloatingEqMatcher<double> DoubleNear(
-    double rhs, double max_abs_error) {
+inline internal::FloatingEqMatcher<double> DoubleNear(double rhs,
+                                                      double max_abs_error) {
   return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
 }
 
@@ -4147,8 +4315,8 @@ inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
 // Creates a matcher that matches any float argument approximately equal to
 // rhs, up to the specified max absolute error bound, where two NANs are
 // considered unequal.  The max absolute error bound must be non-negative.
-inline internal::FloatingEqMatcher<float> FloatNear(
-    float rhs, float max_abs_error) {
+inline internal::FloatingEqMatcher<float> FloatNear(float rhs,
+                                                    float max_abs_error) {
   return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
 }
 
@@ -4176,7 +4344,7 @@ inline internal::PointeeMatcher<InnerMatcher> Pointee(
 // If To is a reference and the cast fails, this matcher returns false
 // immediately.
 template <typename To>
-inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
+inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To>>
 WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
   return MakePolymorphicMatcher(
       internal::WhenDynamicCastToMatcher<To>(inner_matcher));
@@ -4188,12 +4356,10 @@ WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
 //   Field(&Foo::number, Ge(5))
 // matches a Foo object x if and only if x.number >= 5.
 template <typename Class, typename FieldType, typename FieldMatcher>
-inline PolymorphicMatcher<
-  internal::FieldMatcher<Class, FieldType> > Field(
+inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType>> Field(
     FieldType Class::*field, const FieldMatcher& matcher) {
-  return MakePolymorphicMatcher(
-      internal::FieldMatcher<Class, FieldType>(
-          field, MatcherCast<const FieldType&>(matcher)));
+  return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
+      field, MatcherCast<const FieldType&>(matcher)));
   // The call to MatcherCast() is required for supporting inner
   // matchers of compatible types.  For example, it allows
   //   Field(&Foo::bar, m)
@@ -4203,7 +4369,7 @@ inline PolymorphicMatcher<
 // Same as Field() but also takes the name of the field to provide better error
 // messages.
 template <typename Class, typename FieldType, typename FieldMatcher>
-inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field(
+inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType>> Field(
     const std::string& field_name, FieldType Class::*field,
     const FieldMatcher& matcher) {
   return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(
@@ -4216,7 +4382,7 @@ inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field(
 // matches a Foo object x if and only if x.str() starts with "hi".
 template <typename Class, typename PropertyType, typename PropertyMatcher>
 inline PolymorphicMatcher<internal::PropertyMatcher<
-    Class, PropertyType, PropertyType (Class::*)() const> >
+    Class, PropertyType, PropertyType (Class::*)() const>>
 Property(PropertyType (Class::*property)() const,
          const PropertyMatcher& matcher) {
   return MakePolymorphicMatcher(
@@ -4233,7 +4399,7 @@ Property(PropertyType (Class::*property)() const,
 // better error messages.
 template <typename Class, typename PropertyType, typename PropertyMatcher>
 inline PolymorphicMatcher<internal::PropertyMatcher<
-    Class, PropertyType, PropertyType (Class::*)() const> >
+    Class, PropertyType, PropertyType (Class::*)() const>>
 Property(const std::string& property_name,
          PropertyType (Class::*property)() const,
          const PropertyMatcher& matcher) {
@@ -4246,8 +4412,8 @@ Property(const std::string& property_name,
 // The same as above but for reference-qualified member functions.
 template <typename Class, typename PropertyType, typename PropertyMatcher>
 inline PolymorphicMatcher<internal::PropertyMatcher<
-    Class, PropertyType, PropertyType (Class::*)() const &> >
-Property(PropertyType (Class::*property)() const &,
+    Class, PropertyType, PropertyType (Class::*)() const&>>
+Property(PropertyType (Class::*property)() const&,
          const PropertyMatcher& matcher) {
   return MakePolymorphicMatcher(
       internal::PropertyMatcher<Class, PropertyType,
@@ -4258,9 +4424,9 @@ Property(PropertyType (Class::*property)() const &,
 // Three-argument form for reference-qualified member functions.
 template <typename Class, typename PropertyType, typename PropertyMatcher>
 inline PolymorphicMatcher<internal::PropertyMatcher<
-    Class, PropertyType, PropertyType (Class::*)() const &> >
+    Class, PropertyType, PropertyType (Class::*)() const&>>
 Property(const std::string& property_name,
-         PropertyType (Class::*property)() const &,
+         PropertyType (Class::*property)() const&,
          const PropertyMatcher& matcher) {
   return MakePolymorphicMatcher(
       internal::PropertyMatcher<Class, PropertyType,
@@ -4279,15 +4445,25 @@ Property(const std::string& property_name,
 template <typename Callable, typename InnerMatcher>
 internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(
     Callable callable, InnerMatcher matcher) {
+  return internal::ResultOfMatcher<Callable, InnerMatcher>(std::move(callable),
+                                                           std::move(matcher));
+}
+
+// Same as ResultOf() above, but also takes a description of the `callable`
+// result to provide better error messages.
+template <typename Callable, typename InnerMatcher>
+internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(
+    const std::string& result_description, Callable callable,
+    InnerMatcher matcher) {
   return internal::ResultOfMatcher<Callable, InnerMatcher>(
-      std::move(callable), std::move(matcher));
+      result_description, std::move(callable), std::move(matcher));
 }
 
 // String matchers.
 
 // Matches a string equal to str.
 template <typename T = std::string>
-PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
+PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrEq(
     const internal::StringLike<T>& str) {
   return MakePolymorphicMatcher(
       internal::StrEqualityMatcher<std::string>(std::string(str), true, true));
@@ -4295,7 +4471,7 @@ PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
 
 // Matches a string not equal to str.
 template <typename T = std::string>
-PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
+PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrNe(
     const internal::StringLike<T>& str) {
   return MakePolymorphicMatcher(
       internal::StrEqualityMatcher<std::string>(std::string(str), false, true));
@@ -4303,7 +4479,7 @@ PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
 
 // Matches a string equal to str, ignoring case.
 template <typename T = std::string>
-PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
+PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrCaseEq(
     const internal::StringLike<T>& str) {
   return MakePolymorphicMatcher(
       internal::StrEqualityMatcher<std::string>(std::string(str), true, false));
@@ -4311,7 +4487,7 @@ PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
 
 // Matches a string not equal to str, ignoring case.
 template <typename T = std::string>
-PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
+PolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrCaseNe(
     const internal::StringLike<T>& str) {
   return MakePolymorphicMatcher(internal::StrEqualityMatcher<std::string>(
       std::string(str), false, false));
@@ -4320,7 +4496,7 @@ PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
 // Creates a matcher that matches any string, std::string, or C string
 // that contains the given substring.
 template <typename T = std::string>
-PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
+PolymorphicMatcher<internal::HasSubstrMatcher<std::string>> HasSubstr(
     const internal::StringLike<T>& substring) {
   return MakePolymorphicMatcher(
       internal::HasSubstrMatcher<std::string>(std::string(substring)));
@@ -4328,7 +4504,7 @@ PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
 
 // Matches a string that starts with 'prefix' (case-sensitive).
 template <typename T = std::string>
-PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
+PolymorphicMatcher<internal::StartsWithMatcher<std::string>> StartsWith(
     const internal::StringLike<T>& prefix) {
   return MakePolymorphicMatcher(
       internal::StartsWithMatcher<std::string>(std::string(prefix)));
@@ -4336,7 +4512,7 @@ PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
 
 // Matches a string that ends with 'suffix' (case-sensitive).
 template <typename T = std::string>
-PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
+PolymorphicMatcher<internal::EndsWithMatcher<std::string>> EndsWith(
     const internal::StringLike<T>& suffix) {
   return MakePolymorphicMatcher(
       internal::EndsWithMatcher<std::string>(std::string(suffix)));
@@ -4346,50 +4522,50 @@ PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
 // Wide string matchers.
 
 // Matches a string equal to str.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrEq(
+inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrEq(
     const std::wstring& str) {
   return MakePolymorphicMatcher(
       internal::StrEqualityMatcher<std::wstring>(str, true, true));
 }
 
 // Matches a string not equal to str.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> > StrNe(
+inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrNe(
     const std::wstring& str) {
   return MakePolymorphicMatcher(
       internal::StrEqualityMatcher<std::wstring>(str, false, true));
 }
 
 // Matches a string equal to str, ignoring case.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
-StrCaseEq(const std::wstring& str) {
+inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrCaseEq(
+    const std::wstring& str) {
   return MakePolymorphicMatcher(
       internal::StrEqualityMatcher<std::wstring>(str, true, false));
 }
 
 // Matches a string not equal to str, ignoring case.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring> >
-StrCaseNe(const std::wstring& str) {
+inline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrCaseNe(
+    const std::wstring& str) {
   return MakePolymorphicMatcher(
       internal::StrEqualityMatcher<std::wstring>(str, false, false));
 }
 
 // Creates a matcher that matches any ::wstring, std::wstring, or C wide string
 // that contains the given substring.
-inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring> > HasSubstr(
+inline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring>> HasSubstr(
     const std::wstring& substring) {
   return MakePolymorphicMatcher(
       internal::HasSubstrMatcher<std::wstring>(substring));
 }
 
 // Matches a string that starts with 'prefix' (case-sensitive).
-inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring> >
-StartsWith(const std::wstring& prefix) {
+inline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring>> StartsWith(
+    const std::wstring& prefix) {
   return MakePolymorphicMatcher(
       internal::StartsWithMatcher<std::wstring>(prefix));
 }
 
 // Matches a string that ends with 'suffix' (case-sensitive).
-inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring> > EndsWith(
+inline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring>> EndsWith(
     const std::wstring& suffix) {
   return MakePolymorphicMatcher(
       internal::EndsWithMatcher<std::wstring>(suffix));
@@ -4484,8 +4660,8 @@ inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
 // predicate.  The predicate can be any unary function or functor
 // whose return type can be implicitly converted to bool.
 template <typename Predicate>
-inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
-Truly(Predicate pred) {
+inline PolymorphicMatcher<internal::TrulyMatcher<Predicate>> Truly(
+    Predicate pred) {
   return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
 }
 
@@ -4496,8 +4672,8 @@ Truly(Predicate pred) {
 //   EXPECT_THAT(container, SizeIs(2));     // Checks container has 2 elements.
 //   EXPECT_THAT(container, SizeIs(Le(2));  // Checks container has at most 2.
 template <typename SizeMatcher>
-inline internal::SizeIsMatcher<SizeMatcher>
-SizeIs(const SizeMatcher& size_matcher) {
+inline internal::SizeIsMatcher<SizeMatcher> SizeIs(
+    const SizeMatcher& size_matcher) {
   return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
 }
 
@@ -4507,8 +4683,8 @@ SizeIs(const SizeMatcher& size_matcher) {
 // do not implement size(). The container must provide const_iterator (with
 // valid iterator_traits), begin() and end().
 template <typename DistanceMatcher>
-inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
-BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
+inline internal::BeginEndDistanceIsMatcher<DistanceMatcher> BeginEndDistanceIs(
+    const DistanceMatcher& distance_matcher) {
   return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
 }
 
@@ -4517,8 +4693,8 @@ BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
 // values that are included in one container but not the other. (Duplicate
 // values and order differences are not explained.)
 template <typename Container>
-inline PolymorphicMatcher<internal::ContainerEqMatcher<
-    typename std::remove_const<Container>::type>>
+inline PolymorphicMatcher<
+    internal::ContainerEqMatcher<typename std::remove_const<Container>::type>>
 ContainerEq(const Container& rhs) {
   return MakePolymorphicMatcher(internal::ContainerEqMatcher<Container>(rhs));
 }
@@ -4526,9 +4702,8 @@ ContainerEq(const Container& rhs) {
 // Returns a matcher that matches a container that, when sorted using
 // the given comparator, matches container_matcher.
 template <typename Comparator, typename ContainerMatcher>
-inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
-WhenSortedBy(const Comparator& comparator,
-             const ContainerMatcher& container_matcher) {
+inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher> WhenSortedBy(
+    const Comparator& comparator, const ContainerMatcher& container_matcher) {
   return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
       comparator, container_matcher);
 }
@@ -4538,9 +4713,9 @@ WhenSortedBy(const Comparator& comparator,
 template <typename ContainerMatcher>
 inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
 WhenSorted(const ContainerMatcher& container_matcher) {
-  return
-      internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
-          internal::LessComparator(), container_matcher);
+  return internal::WhenSortedByMatcher<internal::LessComparator,
+                                       ContainerMatcher>(
+      internal::LessComparator(), container_matcher);
 }
 
 // Matches an STL-style container or a native array that contains the
@@ -4557,15 +4732,13 @@ Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
                                                              rhs);
 }
 
-
 // Supports the Pointwise(m, {a, b, c}) syntax.
 template <typename TupleMatcher, typename T>
-inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
+inline internal::PointwiseMatcher<TupleMatcher, std::vector<T>> Pointwise(
     const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
   return Pointwise(tuple_matcher, std::vector<T>(rhs));
 }
 
-
 // UnorderedPointwise(pair_matcher, rhs) matches an STL-style
 // container or a native array that contains the same number of
 // elements as in rhs, where in some permutation of the container, its
@@ -4594,28 +4767,25 @@ UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
       RhsView::ConstReference(rhs_container);
 
   // Create a matcher for each element in rhs_container.
-  ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
-  for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
-       it != rhs_stl_container.end(); ++it) {
-    matchers.push_back(
-        internal::MatcherBindSecond(tuple2_matcher, *it));
+  ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second>> matchers;
+  for (auto it = rhs_stl_container.begin(); it != rhs_stl_container.end();
+       ++it) {
+    matchers.push_back(internal::MatcherBindSecond(tuple2_matcher, *it));
   }
 
   // Delegate the work to UnorderedElementsAreArray().
   return UnorderedElementsAreArray(matchers);
 }
 
-
 // Supports the UnorderedPointwise(m, {a, b, c}) syntax.
 template <typename Tuple2Matcher, typename T>
 inline internal::UnorderedElementsAreArrayMatcher<
-    typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
+    typename internal::BoundSecondMatcher<Tuple2Matcher, T>>
 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
                    std::initializer_list<T> rhs) {
   return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
 }
 
-
 // Matches an STL-style container or a native array that contains at
 // least one element matching the given value or matcher.
 //
@@ -4625,7 +4795,7 @@ UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
 //   page_ids.insert(1);
 //   EXPECT_THAT(page_ids, Contains(1));
 //   EXPECT_THAT(page_ids, Contains(Gt(2)));
-//   EXPECT_THAT(page_ids, Not(Contains(4)));
+//   EXPECT_THAT(page_ids, Not(Contains(4)));  // See below for Times(0)
 //
 //   ::std::map<int, size_t> page_lengths;
 //   page_lengths[1] = 100;
@@ -4634,6 +4804,19 @@ UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
 //
 //   const char* user_ids[] = { "joe", "mike", "tom" };
 //   EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
+//
+// The matcher supports a modifier `Times` that allows to check for arbitrary
+// occurrences including testing for absence with Times(0).
+//
+// Examples:
+//   ::std::vector<int> ids;
+//   ids.insert(1);
+//   ids.insert(1);
+//   ids.insert(3);
+//   EXPECT_THAT(ids, Contains(1).Times(2));      // 1 occurs 2 times
+//   EXPECT_THAT(ids, Contains(2).Times(0));      // 2 is not present
+//   EXPECT_THAT(ids, Contains(3).Times(Ge(1)));  // 3 occurs at least once
+
 template <typename M>
 inline internal::ContainsMatcher<M> Contains(M matcher) {
   return internal::ContainsMatcher<M>(matcher);
@@ -4760,7 +4943,7 @@ inline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(
 // Matches an STL-style container or a native array that contains only
 // elements matching the given value or matcher.
 //
-// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
+// Each(m) is semantically equivalent to `Not(Contains(Not(m)))`. Only
 // the messages are different.
 //
 // Examples:
@@ -4803,13 +4986,25 @@ inline internal::KeyMatcher<M> Key(M inner_matcher) {
 // to match a std::map<int, string> that contains exactly one element whose key
 // is >= 5 and whose value equals "foo".
 template <typename FirstMatcher, typename SecondMatcher>
-inline internal::PairMatcher<FirstMatcher, SecondMatcher>
-Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
-  return internal::PairMatcher<FirstMatcher, SecondMatcher>(
-      first_matcher, second_matcher);
+inline internal::PairMatcher<FirstMatcher, SecondMatcher> Pair(
+    FirstMatcher first_matcher, SecondMatcher second_matcher) {
+  return internal::PairMatcher<FirstMatcher, SecondMatcher>(first_matcher,
+                                                            second_matcher);
 }
 
 namespace no_adl {
+// Conditional() creates a matcher that conditionally uses either the first or
+// second matcher provided. For example, we could create an `equal if, and only
+// if' matcher using the Conditional wrapper as follows:
+//
+//   EXPECT_THAT(result, Conditional(condition, Eq(expected), Ne(expected)));
+template <typename MatcherTrue, typename MatcherFalse>
+internal::ConditionalMatcher<MatcherTrue, MatcherFalse> Conditional(
+    bool condition, MatcherTrue matcher_true, MatcherFalse matcher_false) {
+  return internal::ConditionalMatcher<MatcherTrue, MatcherFalse>(
+      condition, std::move(matcher_true), std::move(matcher_false));
+}
+
 // FieldsAre(matchers...) matches piecewise the fields of compatible structs.
 // These include those that support `get<I>(obj)`, and when structured bindings
 // are enabled any class that supports them.
@@ -4836,6 +5031,14 @@ inline internal::AddressMatcher<InnerMatcher> Address(
     const InnerMatcher& inner_matcher) {
   return internal::AddressMatcher<InnerMatcher>(inner_matcher);
 }
+
+// Matches a base64 escaped string, when the unescaped string matches the
+// internal matcher.
+template <typename MatcherType>
+internal::WhenBase64UnescapedMatcher WhenBase64Unescaped(
+    const MatcherType& internal_matcher) {
+  return internal::WhenBase64UnescapedMatcher(internal_matcher);
+}
 }  // namespace no_adl
 
 // Returns a predicate that is satisfied by anything that matches the
@@ -4854,8 +5057,8 @@ inline bool Value(const T& value, M matcher) {
 // Matches the value against the given matcher and explains the match
 // result to listener.
 template <typename T, typename M>
-inline bool ExplainMatchResult(
-    M matcher, const T& value, MatchResultListener* listener) {
+inline bool ExplainMatchResult(M matcher, const T& value,
+                               MatchResultListener* listener) {
   return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
 }
 
@@ -4865,7 +5068,8 @@ inline bool ExplainMatchResult(
 //
 // MATCHER_P(XAndYThat, matcher,
 //           "X that " + DescribeMatcher<int>(matcher, negation) +
-//               " and Y that " + DescribeMatcher<double>(matcher, negation)) {
+//               (negation ? " or" : " and") + " Y that " +
+//               DescribeMatcher<double>(matcher, negation)) {
 //   return ExplainMatchResult(matcher, arg.x(), result_listener) &&
 //          ExplainMatchResult(matcher, arg.y(), result_listener);
 // }
@@ -5014,7 +5218,9 @@ internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...> Args(
 //
 //   EXPECT_CALL(foo, Bar(_, _)).With(Eq());
 template <typename InnerMatcher>
-inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
+inline InnerMatcher AllArgs(const InnerMatcher& matcher) {
+  return matcher;
+}
 
 // Returns a matcher that matches the value of an optional<> type variable.
 // The matcher implementation only uses '!arg' and requires that the optional<>
@@ -5032,7 +5238,7 @@ inline internal::OptionalMatcher<ValueMatcher> Optional(
 
 // Returns a matcher that matches the value of a absl::any type variable.
 template <typename T>
-PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith(
+PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T>> AnyWith(
     const Matcher<const T&>& matcher) {
   return MakePolymorphicMatcher(
       internal::any_cast_matcher::AnyCastMatcher<T>(matcher));
@@ -5043,7 +5249,7 @@ PolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T> > AnyWith(
 // functions.
 // It is compatible with std::variant.
 template <typename T>
-PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
+PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T>> VariantWith(
     const Matcher<const T&>& matcher) {
   return MakePolymorphicMatcher(
       internal::variant_matcher::VariantMatcher<T>(matcher));
@@ -5072,7 +5278,8 @@ class WithWhatMatcherImpl {
 
   template <typename Err>
   bool MatchAndExplain(const Err& err, MatchResultListener* listener) const {
-    *listener << "which contains .what() that ";
+    *listener << "which contains .what() (of value = " << err.what()
+              << ") that ";
     return matcher_.MatchAndExplain(err.what(), listener);
   }
 
@@ -5222,12 +5429,14 @@ PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
 // tests.  ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
 // succeed if and only if the value matches the matcher.  If the assertion
 // fails, the value and the description of the matcher will be printed.
-#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
-    ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
-#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
-    ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
-
-// MATCHER* macroses itself are listed below.
+#define ASSERT_THAT(value, matcher) \
+  ASSERT_PRED_FORMAT1(              \
+      ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
+#define EXPECT_THAT(value, matcher) \
+  EXPECT_PRED_FORMAT1(              \
+      ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
+
+// MATCHER* macros itself are listed below.
 #define MATCHER(name, description)                                             \
   class name##Matcher                                                          \
       : public ::testing::internal::MatcherBaseImpl<name##Matcher> {           \
@@ -5248,12 +5457,13 @@ PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
                                                                                \
      private:                                                                  \
       ::std::string FormatDescription(bool negation) const {                   \
+        /* NOLINTNEXTLINE readability-redundant-string-init */                 \
         ::std::string gmock_description = (description);                       \
         if (!gmock_description.empty()) {                                      \
           return gmock_description;                                            \
         }                                                                      \
         return ::testing::internal::FormatMatcherDescription(negation, #name,  \
-                                                             {});              \
+                                                             {}, {});          \
       }                                                                        \
     };                                                                         \
   };                                                                           \
@@ -5265,33 +5475,41 @@ PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
       const
 
 #define MATCHER_P(name, p0, description) \
-  GMOCK_INTERNAL_MATCHER(name, name##MatcherP, description, (p0))
-#define MATCHER_P2(name, p0, p1, description) \
-  GMOCK_INTERNAL_MATCHER(name, name##MatcherP2, description, (p0, p1))
-#define MATCHER_P3(name, p0, p1, p2, description) \
-  GMOCK_INTERNAL_MATCHER(name, name##MatcherP3, description, (p0, p1, p2))
-#define MATCHER_P4(name, p0, p1, p2, p3, description) \
-  GMOCK_INTERNAL_MATCHER(name, name##MatcherP4, description, (p0, p1, p2, p3))
+  GMOCK_INTERNAL_MATCHER(name, name##MatcherP, description, (#p0), (p0))
+#define MATCHER_P2(name, p0, p1, description)                            \
+  GMOCK_INTERNAL_MATCHER(name, name##MatcherP2, description, (#p0, #p1), \
+                         (p0, p1))
+#define MATCHER_P3(name, p0, p1, p2, description)                             \
+  GMOCK_INTERNAL_MATCHER(name, name##MatcherP3, description, (#p0, #p1, #p2), \
+                         (p0, p1, p2))
+#define MATCHER_P4(name, p0, p1, p2, p3, description)        \
+  GMOCK_INTERNAL_MATCHER(name, name##MatcherP4, description, \
+                         (#p0, #p1, #p2, #p3), (p0, p1, p2, p3))
 #define MATCHER_P5(name, p0, p1, p2, p3, p4, description)    \
   GMOCK_INTERNAL_MATCHER(name, name##MatcherP5, description, \
-                         (p0, p1, p2, p3, p4))
+                         (#p0, #p1, #p2, #p3, #p4), (p0, p1, p2, p3, p4))
 #define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description) \
   GMOCK_INTERNAL_MATCHER(name, name##MatcherP6, description,  \
+                         (#p0, #p1, #p2, #p3, #p4, #p5),      \
                          (p0, p1, p2, p3, p4, p5))
 #define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description) \
   GMOCK_INTERNAL_MATCHER(name, name##MatcherP7, description,      \
+                         (#p0, #p1, #p2, #p3, #p4, #p5, #p6),     \
                          (p0, p1, p2, p3, p4, p5, p6))
 #define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description) \
   GMOCK_INTERNAL_MATCHER(name, name##MatcherP8, description,          \
+                         (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7),    \
                          (p0, p1, p2, p3, p4, p5, p6, p7))
 #define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description) \
   GMOCK_INTERNAL_MATCHER(name, name##MatcherP9, description,              \
+                         (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8),   \
                          (p0, p1, p2, p3, p4, p5, p6, p7, p8))
 #define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description) \
   GMOCK_INTERNAL_MATCHER(name, name##MatcherP10, description,                  \
+                         (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8, #p9),   \
                          (p0, p1, p2, p3, p4, p5, p6, p7, p8, p9))
 
-#define GMOCK_INTERNAL_MATCHER(name, full_name, description, args)             \
+#define GMOCK_INTERNAL_MATCHER(name, full_name, description, arg_names, args)  \
   template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)>                      \
   class full_name : public ::testing::internal::MatcherBaseImpl<               \
                         full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>> { \
@@ -5320,7 +5538,7 @@ PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
           return gmock_description;                                            \
         }                                                                      \
         return ::testing::internal::FormatMatcherDescription(                  \
-            negation, #name,                                                   \
+            negation, #name, {GMOCK_PP_REMOVE_PARENS(arg_names)},              \
             ::testing::internal::UniversalTersePrintTupleFieldsToStrings(      \
                 ::std::tuple<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>(        \
                     GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args))));             \
index fd293358a28ef3643ef8224d3a7bd47213eee3cf..148ac017210cecce46d789219267360f6989e1aa 100644 (file)
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file implements some commonly used variadic actions.
 
-// GOOGLETEST_CM0002 DO NOT DELETE
+// IWYU pragma: private, include "gmock/gmock.h"
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
 
 // Declares the template parameters.
 #define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0
-#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
-    name1) kind0 name0, kind1 name1
+#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \
+  kind0 name0, kind1 name1
 #define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2) kind0 name0, kind1 name1, kind2 name2
+                                                  kind2, name2)               \
+  kind0 name0, kind1 name1, kind2 name2
 #define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \
-    kind3 name3
-#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \
-    kind2 name2, kind3 name3, kind4 name4
+                                                  kind2, name2, kind3, name3) \
+  kind0 name0, kind1 name1, kind2 name2, kind3 name3
+#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(                        \
+    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \
+  kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4
 #define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \
-    kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5
-#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
-    name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
-    kind5 name5, kind6 name6
-#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
-    kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \
-    kind4 name4, kind5 name5, kind6 name6, kind7 name7
-#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
-    kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \
-    kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \
-    kind8 name8
-#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
-    name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
-    name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \
-    kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \
-    kind6 name6, kind7 name7, kind8 name8, kind9 name9
+                                                  kind2, name2, kind3, name3, \
+                                                  kind4, name4, kind5, name5) \
+  kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5
+#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(                        \
+    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
+    kind5, name5, kind6, name6)                                           \
+  kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4,        \
+      kind5 name5, kind6 name6
+#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(                        \
+    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
+    kind5, name5, kind6, name6, kind7, name7)                             \
+  kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4,        \
+      kind5 name5, kind6 name6, kind7 name7
+#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(                        \
+    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
+    kind5, name5, kind6, name6, kind7, name7, kind8, name8)               \
+  kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4,        \
+      kind5 name5, kind6 name6, kind7 name7, kind8 name8
+#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(                       \
+    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
+    kind5, name5, kind6, name6, kind7, name7, kind8, name8, kind9, name9) \
+  kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4,        \
+      kind5 name5, kind6 name6, kind7 name7, kind8 name8, kind9 name9
 
 // Lists the template parameters.
 #define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0
-#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
-    name1) name0, name1
+#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \
+  name0, name1
 #define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2) name0, name1, name2
+                                                  kind2, name2)               \
+  name0, name1, name2
 #define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3) name0, name1, name2, name3
-#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \
-    name4
+                                                  kind2, name2, kind3, name3) \
+  name0, name1, name2, name3
+#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(                        \
+    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \
+  name0, name1, name2, name3, name4
 #define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \
-    name2, name3, name4, name5
-#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
-    name6) name0, name1, name2, name3, name4, name5, name6
-#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
-    kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7
-#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
-    kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
-    kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \
-    name6, name7, name8
-#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
-    name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
-    name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \
-    name3, name4, name5, name6, name7, name8, name9
+                                                  kind2, name2, kind3, name3, \
+                                                  kind4, name4, kind5, name5) \
+  name0, name1, name2, name3, name4, name5
+#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(                        \
+    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
+    kind5, name5, kind6, name6)                                           \
+  name0, name1, name2, name3, name4, name5, name6
+#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(                        \
+    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
+    kind5, name5, kind6, name6, kind7, name7)                             \
+  name0, name1, name2, name3, name4, name5, name6, name7
+#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(                        \
+    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
+    kind5, name5, kind6, name6, kind7, name7, kind8, name8)               \
+  name0, name1, name2, name3, name4, name5, name6, name7, name8
+#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(                       \
+    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \
+    kind5, name5, kind6, name6, kind7, name7, kind8, name8, kind9, name9) \
+  name0, name1, name2, name3, name4, name5, name6, name7, name8, name9
 
 // Declares the types of value parameters.
 #define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS()
 #define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) \
-    typename p0##_type, typename p1##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \
-    typename p0##_type, typename p1##_type, typename p2##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
-    typename p0##_type, typename p1##_type, typename p2##_type, \
-    typename p3##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
-    typename p0##_type, typename p1##_type, typename p2##_type, \
-    typename p3##_type, typename p4##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
-    typename p0##_type, typename p1##_type, typename p2##_type, \
-    typename p3##_type, typename p4##_type, typename p5##_type
+#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) \
+  , typename p0##_type, typename p1##_type
+#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \
+  , typename p0##_type, typename p1##_type, typename p2##_type
+#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
+  , typename p0##_type, typename p1##_type, typename p2##_type,     \
+      typename p3##_type
+#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
+  , typename p0##_type, typename p1##_type, typename p2##_type,         \
+      typename p3##_type, typename p4##_type
+#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
+  , typename p0##_type, typename p1##_type, typename p2##_type,             \
+      typename p3##_type, typename p4##_type, typename p5##_type
 #define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6) , typename p0##_type, typename p1##_type, typename p2##_type, \
-    typename p3##_type, typename p4##_type, typename p5##_type, \
-    typename p6##_type
+                                                    p6)                     \
+  , typename p0##_type, typename p1##_type, typename p2##_type,             \
+      typename p3##_type, typename p4##_type, typename p5##_type,           \
+      typename p6##_type
 #define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \
-    typename p3##_type, typename p4##_type, typename p5##_type, \
-    typename p6##_type, typename p7##_type
+                                                    p6, p7)                 \
+  , typename p0##_type, typename p1##_type, typename p2##_type,             \
+      typename p3##_type, typename p4##_type, typename p5##_type,           \
+      typename p6##_type, typename p7##_type
 #define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \
-    typename p3##_type, typename p4##_type, typename p5##_type, \
-    typename p6##_type, typename p7##_type, typename p8##_type
+                                                    p6, p7, p8)             \
+  , typename p0##_type, typename p1##_type, typename p2##_type,             \
+      typename p3##_type, typename p4##_type, typename p5##_type,           \
+      typename p6##_type, typename p7##_type, typename p8##_type
 #define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \
-    typename p2##_type, typename p3##_type, typename p4##_type, \
-    typename p5##_type, typename p6##_type, typename p7##_type, \
-    typename p8##_type, typename p9##_type
+                                                     p6, p7, p8, p9)         \
+  , typename p0##_type, typename p1##_type, typename p2##_type,              \
+      typename p3##_type, typename p4##_type, typename p5##_type,            \
+      typename p6##_type, typename p7##_type, typename p8##_type,            \
+      typename p9##_type
 
 // Initializes the value parameters.
-#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\
-    ()
-#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\
-    (p0##_type gmock_p0) : p0(::std::move(gmock_p0))
-#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\
-    (p0##_type gmock_p0, p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \
-        p1(::std::move(gmock_p1))
-#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\
-    (p0##_type gmock_p0, p1##_type gmock_p1, \
-        p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \
-        p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2))
-#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\
-    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-        p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \
-        p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
+#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS() ()
+#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0) \
+  (p0##_type gmock_p0) : p0(::std::move(gmock_p0))
+#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1) \
+  (p0##_type gmock_p0, p1##_type gmock_p1)             \
+      : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1))
+#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)     \
+  (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2) \
+      : p0(::std::move(gmock_p0)),                             \
+        p1(::std::move(gmock_p1)),                             \
+        p2(::std::move(gmock_p2))
+#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
+  (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
+   p3##_type gmock_p3)                                         \
+      : p0(::std::move(gmock_p0)),                             \
+        p1(::std::move(gmock_p1)),                             \
+        p2(::std::move(gmock_p2)),                             \
         p3(::std::move(gmock_p3))
-#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\
-    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-        p3##_type gmock_p3, p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \
-        p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
-        p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4))
-#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\
-    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-        p3##_type gmock_p3, p4##_type gmock_p4, \
-        p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \
-        p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
-        p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
+#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
+  (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2,     \
+   p3##_type gmock_p3, p4##_type gmock_p4)                         \
+      : p0(::std::move(gmock_p0)),                                 \
+        p1(::std::move(gmock_p1)),                                 \
+        p2(::std::move(gmock_p2)),                                 \
+        p3(::std::move(gmock_p3)),                                 \
+        p4(::std::move(gmock_p4))
+#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
+  (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2,         \
+   p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5)         \
+      : p0(::std::move(gmock_p0)),                                     \
+        p1(::std::move(gmock_p1)),                                     \
+        p2(::std::move(gmock_p2)),                                     \
+        p3(::std::move(gmock_p3)),                                     \
+        p4(::std::move(gmock_p4)),                                     \
         p5(::std::move(gmock_p5))
-#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\
-    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-        p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
-        p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \
-        p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
-        p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
-        p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6))
-#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\
-    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-        p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
-        p6##_type gmock_p6, p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \
-        p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
-        p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
-        p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
+#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \
+  (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2,             \
+   p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5,             \
+   p6##_type gmock_p6)                                                     \
+      : p0(::std::move(gmock_p0)),                                         \
+        p1(::std::move(gmock_p1)),                                         \
+        p2(::std::move(gmock_p2)),                                         \
+        p3(::std::move(gmock_p3)),                                         \
+        p4(::std::move(gmock_p4)),                                         \
+        p5(::std::move(gmock_p5)),                                         \
+        p6(::std::move(gmock_p6))
+#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \
+  (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2,                 \
+   p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5,                 \
+   p6##_type gmock_p6, p7##_type gmock_p7)                                     \
+      : p0(::std::move(gmock_p0)),                                             \
+        p1(::std::move(gmock_p1)),                                             \
+        p2(::std::move(gmock_p2)),                                             \
+        p3(::std::move(gmock_p3)),                                             \
+        p4(::std::move(gmock_p4)),                                             \
+        p5(::std::move(gmock_p5)),                                             \
+        p6(::std::move(gmock_p6)),                                             \
         p7(::std::move(gmock_p7))
-#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8)\
-    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-        p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
-        p6##_type gmock_p6, p7##_type gmock_p7, \
-        p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \
-        p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
-        p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
-        p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
-        p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8))
+#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \
+                                               p8)                             \
+  (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2,                 \
+   p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5,                 \
+   p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8)                 \
+      : p0(::std::move(gmock_p0)),                                             \
+        p1(::std::move(gmock_p1)),                                             \
+        p2(::std::move(gmock_p2)),                                             \
+        p3(::std::move(gmock_p3)),                                             \
+        p4(::std::move(gmock_p4)),                                             \
+        p5(::std::move(gmock_p5)),                                             \
+        p6(::std::move(gmock_p6)),                                             \
+        p7(::std::move(gmock_p7)),                                             \
+        p8(::std::move(gmock_p8))
 #define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8, p9)\
-    (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
-        p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
-        p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
-        p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \
-        p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
-        p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
-        p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
-        p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \
+                                                p7, p8, p9)                 \
+  (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2,              \
+   p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5,              \
+   p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8,              \
+   p9##_type gmock_p9)                                                      \
+      : p0(::std::move(gmock_p0)),                                          \
+        p1(::std::move(gmock_p1)),                                          \
+        p2(::std::move(gmock_p2)),                                          \
+        p3(::std::move(gmock_p3)),                                          \
+        p4(::std::move(gmock_p4)),                                          \
+        p5(::std::move(gmock_p5)),                                          \
+        p6(::std::move(gmock_p6)),                                          \
+        p7(::std::move(gmock_p7)),                                          \
+        p8(::std::move(gmock_p8)),                                          \
         p9(::std::move(gmock_p9))
 
 // Defines the copy constructor
 #define GMOCK_INTERNAL_DEFN_COPY_AND_0_VALUE_PARAMS() \
-    {}  // Avoid https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82134
+  {}  // Avoid https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82134
 #define GMOCK_INTERNAL_DEFN_COPY_AND_1_VALUE_PARAMS(...) = default;
 #define GMOCK_INTERNAL_DEFN_COPY_AND_2_VALUE_PARAMS(...) = default;
 #define GMOCK_INTERNAL_DEFN_COPY_AND_3_VALUE_PARAMS(...) = default;
 // Declares the fields for storing the value parameters.
 #define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS()
 #define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0;
-#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \
-    p1##_type p1;
-#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \
-    p1##_type p1; p2##_type p2;
-#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \
-    p1##_type p1; p2##_type p2; p3##_type p3;
-#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
-    p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4;
-#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
-    p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
-    p5##_type p5;
-#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
-    p5##_type p5; p6##_type p6;
-#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
-    p5##_type p5; p6##_type p6; p7##_type p7;
-#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
-    p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8;
+#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) \
+  p0##_type p0;                                        \
+  p1##_type p1;
+#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) \
+  p0##_type p0;                                            \
+  p1##_type p1;                                            \
+  p2##_type p2;
+#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
+  p0##_type p0;                                                \
+  p1##_type p1;                                                \
+  p2##_type p2;                                                \
+  p3##_type p3;
+#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
+  p0##_type p0;                                                    \
+  p1##_type p1;                                                    \
+  p2##_type p2;                                                    \
+  p3##_type p3;                                                    \
+  p4##_type p4;
+#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
+  p0##_type p0;                                                        \
+  p1##_type p1;                                                        \
+  p2##_type p2;                                                        \
+  p3##_type p3;                                                        \
+  p4##_type p4;                                                        \
+  p5##_type p5;
+#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \
+  p0##_type p0;                                                            \
+  p1##_type p1;                                                            \
+  p2##_type p2;                                                            \
+  p3##_type p3;                                                            \
+  p4##_type p4;                                                            \
+  p5##_type p5;                                                            \
+  p6##_type p6;
+#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \
+  p0##_type p0;                                                                \
+  p1##_type p1;                                                                \
+  p2##_type p2;                                                                \
+  p3##_type p3;                                                                \
+  p4##_type p4;                                                                \
+  p5##_type p5;                                                                \
+  p6##_type p6;                                                                \
+  p7##_type p7;
+#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \
+                                               p8)                             \
+  p0##_type p0;                                                                \
+  p1##_type p1;                                                                \
+  p2##_type p2;                                                                \
+  p3##_type p3;                                                                \
+  p4##_type p4;                                                                \
+  p5##_type p5;                                                                \
+  p6##_type p6;                                                                \
+  p7##_type p7;                                                                \
+  p8##_type p8;
 #define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
-    p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \
-    p9##_type p9;
+                                                p7, p8, p9)                 \
+  p0##_type p0;                                                             \
+  p1##_type p1;                                                             \
+  p2##_type p2;                                                             \
+  p3##_type p3;                                                             \
+  p4##_type p4;                                                             \
+  p5##_type p5;                                                             \
+  p6##_type p6;                                                             \
+  p7##_type p7;                                                             \
+  p8##_type p8;                                                             \
+  p9##_type p9;
 
 // Lists the value parameters.
 #define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS()
 #define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1
 #define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2
 #define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3
-#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \
-    p2, p3, p4
-#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \
-    p1, p2, p3, p4, p5
-#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6) p0, p1, p2, p3, p4, p5, p6
-#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7) p0, p1, p2, p3, p4, p5, p6, p7
-#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8
+#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
+  p0, p1, p2, p3, p4
+#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
+  p0, p1, p2, p3, p4, p5
+#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \
+  p0, p1, p2, p3, p4, p5, p6
+#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \
+  p0, p1, p2, p3, p4, p5, p6, p7
+#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \
+                                               p8)                             \
+  p0, p1, p2, p3, p4, p5, p6, p7, p8
 #define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9
+                                                p7, p8, p9)                 \
+  p0, p1, p2, p3, p4, p5, p6, p7, p8, p9
 
 // Lists the value parameter types.
 #define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS()
 #define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \
-    p1##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \
-    p1##_type, p2##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
-    p0##_type, p1##_type, p2##_type, p3##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
-    p0##_type, p1##_type, p2##_type, p3##_type, p4##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
-    p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type
+#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) \
+  , p0##_type, p1##_type
+#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \
+  , p0##_type, p1##_type, p2##_type
+#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
+  , p0##_type, p1##_type, p2##_type, p3##_type
+#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
+  , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type
+#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \
+  , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type
 #define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
-    p6##_type
+                                                    p6)                     \
+  , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, p6##_type
 #define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
-    p5##_type, p6##_type, p7##_type
+                                                    p6, p7)                 \
+  , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type,       \
+      p6##_type, p7##_type
 #define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
-    p5##_type, p6##_type, p7##_type, p8##_type
+                                                    p6, p7, p8)             \
+  , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type,       \
+      p6##_type, p7##_type, p8##_type
 #define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
-    p5##_type, p6##_type, p7##_type, p8##_type, p9##_type
+                                                     p6, p7, p8, p9)         \
+  , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type,        \
+      p6##_type, p7##_type, p8##_type, p9##_type
 
 // Declares the value parameters.
 #define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS()
 #define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0
-#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \
-    p1##_type p1
-#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \
-    p1##_type p1, p2##_type p2
-#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \
-    p1##_type p1, p2##_type p2, p3##_type p3
-#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
-    p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4
-#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
-    p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
-    p5##_type p5
-#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
-    p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
-    p5##_type p5, p6##_type p6
-#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
-    p5##_type p5, p6##_type p6, p7##_type p7
-#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
-    p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8
+#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) \
+  p0##_type p0, p1##_type p1
+#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) \
+  p0##_type p0, p1##_type p1, p2##_type p2
+#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \
+  p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3
+#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \
+  p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4
+#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)  \
+  p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
+      p5##_type p5
+#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \
+  p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4,    \
+      p5##_type p5, p6##_type p6
+#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \
+  p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4,        \
+      p5##_type p5, p6##_type p6, p7##_type p7
+#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \
+                                               p8)                             \
+  p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4,        \
+      p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8
 #define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
-    p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
-    p9##_type p9
+                                                p7, p8, p9)                 \
+  p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4,     \
+      p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, p9##_type p9
 
 // The suffix of the class template implementing the action template.
 #define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS()
 #define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6
 #define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7
 #define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7) P8
+                                                p7)                         \
+  P8
 #define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8) P9
+                                                p7, p8)                     \
+  P9
 #define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
-    p7, p8, p9) P10
+                                                 p7, p8, p9)                 \
+  P10
 
 // The name of the class template implementing the action template.
-#define GMOCK_ACTION_CLASS_(name, value_params)\
-    GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
+#define GMOCK_ACTION_CLASS_(name, value_params) \
+  GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
 
 #define ACTION_TEMPLATE(name, template_params, value_params)                   \
   template <GMOCK_INTERNAL_DECL_##template_params                              \
-            GMOCK_INTERNAL_DECL_TYPE_##value_params>                           \
+                GMOCK_INTERNAL_DECL_TYPE_##value_params>                       \
   class GMOCK_ACTION_CLASS_(name, value_params) {                              \
    public:                                                                     \
     explicit GMOCK_ACTION_CLASS_(name, value_params)(                          \
         GMOCK_INTERNAL_DECL_##value_params)                                    \
         GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params),    \
-                    = default; ,                                               \
+                    = default;                                                 \
+                    ,                                                          \
                     : impl_(std::make_shared<gmock_Impl>(                      \
-                                GMOCK_INTERNAL_LIST_##value_params)) { })      \
-    GMOCK_ACTION_CLASS_(name, value_params)(                                   \
-        const GMOCK_ACTION_CLASS_(name, value_params)&) noexcept               \
-        GMOCK_INTERNAL_DEFN_COPY_##value_params                                \
-    GMOCK_ACTION_CLASS_(name, value_params)(                                   \
-        GMOCK_ACTION_CLASS_(name, value_params)&&) noexcept                    \
-        GMOCK_INTERNAL_DEFN_COPY_##value_params                                \
-    template <typename F>                                                      \
-    operator ::testing::Action<F>() const {                                    \
+                        GMOCK_INTERNAL_LIST_##value_params)){})                \
+            GMOCK_ACTION_CLASS_(name, value_params)(const GMOCK_ACTION_CLASS_( \
+                name, value_params) &) noexcept GMOCK_INTERNAL_DEFN_COPY_      \
+        ##value_params GMOCK_ACTION_CLASS_(name, value_params)(                \
+            GMOCK_ACTION_CLASS_(name, value_params) &&) noexcept               \
+        GMOCK_INTERNAL_DEFN_COPY_##value_params template <typename F>          \
+        operator ::testing::Action<F>() const {                                \
       return GMOCK_PP_IF(                                                      \
           GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params),              \
-                      (::testing::internal::MakeAction<F, gmock_Impl>()),      \
-                      (::testing::internal::MakeAction<F>(impl_)));            \
+          (::testing::internal::MakeAction<F, gmock_Impl>()),                  \
+          (::testing::internal::MakeAction<F>(impl_)));                        \
     }                                                                          \
+                                                                               \
    private:                                                                    \
     class gmock_Impl {                                                         \
      public:                                                                   \
       return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const;  \
       GMOCK_INTERNAL_DEFN_##value_params                                       \
     };                                                                         \
-    GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params),        \
-                , std::shared_ptr<const gmock_Impl> impl_;)                    \
+    GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), ,      \
+                std::shared_ptr<const gmock_Impl> impl_;)                      \
   };                                                                           \
   template <GMOCK_INTERNAL_DECL_##template_params                              \
-            GMOCK_INTERNAL_DECL_TYPE_##value_params>                           \
-  GMOCK_ACTION_CLASS_(name, value_params)<                                     \
-      GMOCK_INTERNAL_LIST_##template_params                                    \
-      GMOCK_INTERNAL_LIST_TYPE_##value_params> name(                           \
-          GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_;          \
+                GMOCK_INTERNAL_DECL_TYPE_##value_params>                       \
+  GMOCK_ACTION_CLASS_(                                                         \
+      name, value_params)<GMOCK_INTERNAL_LIST_##template_params                \
+                              GMOCK_INTERNAL_LIST_TYPE_##value_params>         \
+      name(GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_;         \
   template <GMOCK_INTERNAL_DECL_##template_params                              \
-            GMOCK_INTERNAL_DECL_TYPE_##value_params>                           \
-  inline GMOCK_ACTION_CLASS_(name, value_params)<                              \
-      GMOCK_INTERNAL_LIST_##template_params                                    \
-      GMOCK_INTERNAL_LIST_TYPE_##value_params> name(                           \
-          GMOCK_INTERNAL_DECL_##value_params) {                                \
-    return GMOCK_ACTION_CLASS_(name, value_params)<                            \
-        GMOCK_INTERNAL_LIST_##template_params                                  \
-        GMOCK_INTERNAL_LIST_TYPE_##value_params>(                              \
-            GMOCK_INTERNAL_LIST_##value_params);                               \
+                GMOCK_INTERNAL_DECL_TYPE_##value_params>                       \
+  inline GMOCK_ACTION_CLASS_(                                                  \
+      name, value_params)<GMOCK_INTERNAL_LIST_##template_params                \
+                              GMOCK_INTERNAL_LIST_TYPE_##value_params>         \
+  name(GMOCK_INTERNAL_DECL_##value_params) {                                   \
+    return GMOCK_ACTION_CLASS_(                                                \
+        name, value_params)<GMOCK_INTERNAL_LIST_##template_params              \
+                                GMOCK_INTERNAL_LIST_TYPE_##value_params>(      \
+        GMOCK_INTERNAL_LIST_##value_params);                                   \
   }                                                                            \
   template <GMOCK_INTERNAL_DECL_##template_params                              \
-            GMOCK_INTERNAL_DECL_TYPE_##value_params>                           \
+                GMOCK_INTERNAL_DECL_TYPE_##value_params>                       \
   template <typename function_type, typename return_type, typename args_type,  \
             GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>                                 \
-  return_type GMOCK_ACTION_CLASS_(name, value_params)<                         \
-      GMOCK_INTERNAL_LIST_##template_params                                    \
-      GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::gmock_PerformImpl( \
-          GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
+  return_type GMOCK_ACTION_CLASS_(                                             \
+      name, value_params)<GMOCK_INTERNAL_LIST_##template_params                \
+                              GMOCK_INTERNAL_LIST_TYPE_##value_params>::       \
+      gmock_Impl::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_)  \
+          const
 
 namespace testing {
 
@@ -495,8 +583,8 @@ namespace testing {
 // is expanded and macro expansion cannot contain #pragma.  Therefore
 // we suppress them here.
 #ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
+#pragma warning(push)
+#pragma warning(disable : 4100)
 #endif
 
 namespace internal {
@@ -512,7 +600,8 @@ auto InvokeArgument(F f, Args... args) -> decltype(f(args...)) {
 
 template <std::size_t index, typename... Params>
 struct InvokeArgumentAction {
-  template <typename... Args>
+  template <typename... Args,
+            typename = typename std::enable_if<(index < sizeof...(Args))>::type>
   auto operator()(Args&&... args) const -> decltype(internal::InvokeArgument(
       std::get<index>(std::forward_as_tuple(std::forward<Args>(args)...)),
       std::declval<const Params&>()...)) {
@@ -565,7 +654,7 @@ InvokeArgument(Params&&... params) {
 }
 
 #ifdef _MSC_VER
-# pragma warning(pop)
+#pragma warning(pop)
 #endif
 
 }  // namespace testing
index dfc77e359c726bd771c18ba2d98454ac3d35dd13..47aaf98461ed23ee4af9416b694177eb887b26e0 100644 (file)
@@ -27,7 +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.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file implements some matchers that depend on gmock-matchers.h.
@@ -35,7 +34,8 @@
 // Note that tests are implemented in gmock-matchers_test.cc rather than
 // gmock-more-matchers-test.cc.
 
-// GOOGLETEST_CM0002 DO NOT DELETE
+// IWYU pragma: private, include "gmock/gmock.h"
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
@@ -47,13 +47,13 @@ namespace testing {
 // Silence C4100 (unreferenced formal
 // parameter) for MSVC
 #ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
+#pragma warning(push)
+#pragma warning(disable : 4100)
 #if (_MSC_VER == 1900)
 // and silence C4800 (C4800: 'int *const ': forcing value
 // to bool 'true' or 'false') for MSVC 14
-# pragma warning(disable:4800)
-  #endif
+#pragma warning(disable : 4800)
+#endif
 #endif
 
 // Defines a matcher that matches an empty container. The container must
@@ -83,10 +83,9 @@ MATCHER(IsFalse, negation ? "is true" : "is false") {
 }
 
 #ifdef _MSC_VER
-# pragma warning(pop)
+#pragma warning(pop)
 #endif
 
-
 }  // namespace testing
 
 #endif  // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
index b03b770c757af1bc4c1099f544d984a4e8fdbc14..4f0eb35db72ada705bee4b6ac19926f0598003c1 100644 (file)
@@ -27,7 +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.
 
-
 // Implements class templates NiceMock, NaggyMock, and StrictMock.
 //
 // Given a mock class MockFoo that is created using Google Mock,
 // In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT
 // supported.
 
-// GOOGLETEST_CM0002 DO NOT DELETE
+// IWYU pragma: private, include "gmock/gmock.h"
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
 
+#include <cstdint>
 #include <type_traits>
 
 #include "gmock/gmock-spec-builders.h"
@@ -109,25 +110,37 @@ constexpr bool HasStrictnessModifier() {
 template <typename Base>
 class NiceMockImpl {
  public:
-  NiceMockImpl() { ::testing::Mock::AllowUninterestingCalls(this); }
+  NiceMockImpl() {
+    ::testing::Mock::AllowUninterestingCalls(reinterpret_cast<uintptr_t>(this));
+  }
 
-  ~NiceMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
+  ~NiceMockImpl() {
+    ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));
+  }
 };
 
 template <typename Base>
 class NaggyMockImpl {
  public:
-  NaggyMockImpl() { ::testing::Mock::WarnUninterestingCalls(this); }
+  NaggyMockImpl() {
+    ::testing::Mock::WarnUninterestingCalls(reinterpret_cast<uintptr_t>(this));
+  }
 
-  ~NaggyMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
+  ~NaggyMockImpl() {
+    ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));
+  }
 };
 
 template <typename Base>
 class StrictMockImpl {
  public:
-  StrictMockImpl() { ::testing::Mock::FailUninterestingCalls(this); }
+  StrictMockImpl() {
+    ::testing::Mock::FailUninterestingCalls(reinterpret_cast<uintptr_t>(this));
+  }
 
-  ~StrictMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
+  ~StrictMockImpl() {
+    ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));
+  }
 };
 
 }  // namespace internal
@@ -169,7 +182,8 @@ class GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock
   }
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock);
+  NiceMock(const NiceMock&) = delete;
+  NiceMock& operator=(const NiceMock&) = delete;
 };
 
 template <class MockClass>
@@ -210,7 +224,8 @@ class GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock
   }
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock);
+  NaggyMock(const NaggyMock&) = delete;
+  NaggyMock& operator=(const NaggyMock&) = delete;
 };
 
 template <class MockClass>
@@ -251,7 +266,8 @@ class GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock
   }
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock);
+  StrictMock(const StrictMock&) = delete;
+  StrictMock& operator=(const StrictMock&) = delete;
 };
 
 #undef GTEST_INTERNAL_EMPTY_BASE_CLASS
index 41323c1cc03c298a7d9ba6101efa6476e2ef5dac..45cc605183cc8b9bb5cb7d3d2dd5ffef6de1c0c6 100644 (file)
@@ -27,7 +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.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file implements the ON_CALL() and EXPECT_CALL() macros.
 // where all clauses are optional, and .InSequence()/.After()/
 // .WillOnce() can appear any number of times.
 
-// GOOGLETEST_CM0002 DO NOT DELETE
+// IWYU pragma: private, include "gmock/gmock.h"
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
 
+#include <cstdint>
 #include <functional>
 #include <map>
 #include <memory>
@@ -70,6 +71,7 @@
 #include <type_traits>
 #include <utility>
 #include <vector>
+
 #include "gmock/gmock-actions.h"
 #include "gmock/gmock-cardinalities.h"
 #include "gmock/gmock-matchers.h"
@@ -78,7 +80,7 @@
 #include "gtest/gtest.h"
 
 #if GTEST_HAS_EXCEPTIONS
-# include <stdexcept>  // NOLINT
+#include <stdexcept>  // NOLINT
 #endif
 
 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
@@ -97,13 +99,15 @@ class ExpectationSet;
 namespace internal {
 
 // Implements a mock function.
-template <typename F> class FunctionMocker;
+template <typename F>
+class FunctionMocker;
 
 // Base class for expectations.
 class ExpectationBase;
 
 // Implements an expectation.
-template <typename F> class TypedExpectation;
+template <typename F>
+class TypedExpectation;
 
 // Helper class for testing the Expectation class template.
 class ExpectationTester;
@@ -129,9 +133,6 @@ class NaggyMockImpl;
 // calls to ensure the integrity of the mock objects' states.
 GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
 
-// Untyped base class for ActionResultHolder<R>.
-class UntypedActionResultHolderBase;
-
 // Abstract base class of FunctionMocker.  This is the
 // type-agnostic part of the function mocker interface.  Its pure
 // virtual methods are implemented by FunctionMocker.
@@ -154,27 +155,12 @@ class GTEST_API_ UntypedFunctionMockerBase {
   // responsibility to guarantee the correctness of the arguments'
   // types.
 
-  // Performs the default action with the given arguments and returns
-  // the action's result.  The call description string will be used in
-  // the error message to describe the call in the case the default
-  // action fails.
-  // L = *
-  virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
-      void* untyped_args, const std::string& call_description) const = 0;
-
-  // Performs the given action with the given arguments and returns
-  // the action's result.
-  // L = *
-  virtual UntypedActionResultHolderBase* UntypedPerformAction(
-      const void* untyped_action, void* untyped_args) const = 0;
-
   // Writes a message that the call is uninteresting (i.e. neither
   // explicitly expected nor explicitly unexpected) to the given
   // ostream.
-  virtual void UntypedDescribeUninterestingCall(
-      const void* untyped_args,
-      ::std::ostream* os) const
-          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
+  virtual void UntypedDescribeUninterestingCall(const void* untyped_args,
+                                                ::std::ostream* os) const
+      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
 
   // Returns the expectation that matches the given function arguments
   // (or NULL is there's no match); when a match is found,
@@ -183,10 +169,9 @@ class GTEST_API_ UntypedFunctionMockerBase {
   // is_excessive is modified to indicate whether the call exceeds the
   // expected number.
   virtual const ExpectationBase* UntypedFindMatchingExpectation(
-      const void* untyped_args,
-      const void** untyped_action, bool* is_excessive,
+      const void* untyped_args, const void** untyped_action, bool* is_excessive,
       ::std::ostream* what, ::std::ostream* why)
-          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
+      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
 
   // Prints the given function arguments to the ostream.
   virtual void UntypedPrintArgs(const void* untyped_args,
@@ -196,8 +181,7 @@ class GTEST_API_ UntypedFunctionMockerBase {
   // this information in the global mock registry.  Will be called
   // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
   // method.
-  void RegisterOwner(const void* mock_obj)
-      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
+  void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
 
   // Sets the mock object this mock method belongs to, and sets the
   // name of the mock function.  Will be called upon each invocation
@@ -208,20 +192,11 @@ class GTEST_API_ UntypedFunctionMockerBase {
   // Returns the mock object this mock method belongs to.  Must be
   // called after RegisterOwner() or SetOwnerAndName() has been
   // called.
-  const void* MockObject() const
-      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
+  const void* MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
 
   // Returns the name of this mock method.  Must be called after
   // SetOwnerAndName() has been called.
-  const char* Name() const
-      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
-
-  // Returns the result of invoking this mock function with the given
-  // arguments.  This function can be safely called from multiple
-  // threads concurrently.  The caller is responsible for deleting the
-  // result.
-  UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
-      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
+  const char* Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
 
  protected:
   typedef std::vector<const void*> UntypedOnCallSpecs;
@@ -430,29 +405,28 @@ class GTEST_API_ Mock {
 
   // Tells Google Mock to allow uninteresting calls on the given mock
   // object.
-  static void AllowUninterestingCalls(const void* mock_obj)
+  static void AllowUninterestingCalls(uintptr_t mock_obj)
       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
 
   // Tells Google Mock to warn the user about uninteresting calls on
   // the given mock object.
-  static void WarnUninterestingCalls(const void* mock_obj)
+  static void WarnUninterestingCalls(uintptr_t mock_obj)
       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
 
   // Tells Google Mock to fail uninteresting calls on the given mock
   // object.
-  static void FailUninterestingCalls(const void* mock_obj)
+  static void FailUninterestingCalls(uintptr_t mock_obj)
       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
 
   // Tells Google Mock the given mock object is being destroyed and
   // its entry in the call-reaction table should be removed.
-  static void UnregisterCallReaction(const void* mock_obj)
+  static void UnregisterCallReaction(uintptr_t mock_obj)
       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
 
   // Returns the reaction Google Mock will have on uninteresting calls
   // made on the given mock object.
   static internal::CallReaction GetReactionOnUninterestingCalls(
-      const void* mock_obj)
-          GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
+      const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
 
   // Verifies that all expectations on the given mock object have been
   // satisfied.  Reports one or more Google Test non-fatal failures
@@ -465,17 +439,16 @@ class GTEST_API_ Mock {
       GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
 
   // Registers a mock object and a mock method it owns.
-  static void Register(
-      const void* mock_obj,
-      internal::UntypedFunctionMockerBase* mocker)
-          GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
+  static void Register(const void* mock_obj,
+                       internal::UntypedFunctionMockerBase* mocker)
+      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
 
   // Tells Google Mock where in the source code mock_obj is used in an
   // ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this
   // information helps the user identify which object it is.
-  static void RegisterUseByOnCallOrExpectCall(
-      const void* mock_obj, const char* file, int line)
-          GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
+  static void RegisterUseByOnCallOrExpectCall(const void* mock_obj,
+                                              const char* file, int line)
+      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
 
   // Unregisters a mock method; removes the owning mock object from
   // the registry when the last mock method associated with it has
@@ -632,7 +605,6 @@ class ExpectationSet {
   Expectation::Set expectations_;
 };
 
-
 // Sequence objects are used by a user to specify the relative order
 // in which the expectations should match.  They are copyable (we rely
 // on the compiler-defined copy constructor and assignment operator).
@@ -678,10 +650,12 @@ class GTEST_API_ InSequence {
  public:
   InSequence();
   ~InSequence();
+
  private:
   bool sequence_created_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence);  // NOLINT
+  InSequence(const InSequence&) = delete;
+  InSequence& operator=(const InSequence&) = delete;
 } GTEST_ATTRIBUTE_UNUSED_;
 
 namespace internal {
@@ -784,40 +758,34 @@ class GTEST_API_ ExpectationBase {
   // the current thread.
 
   // Retires all pre-requisites of this expectation.
-  void RetireAllPreRequisites()
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
+  void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
 
   // Returns true if and only if this expectation is retired.
-  bool is_retired() const
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
+  bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
     g_gmock_mutex.AssertHeld();
     return retired_;
   }
 
   // Retires this expectation.
-  void Retire()
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
+  void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
     g_gmock_mutex.AssertHeld();
     retired_ = true;
   }
 
   // Returns true if and only if this expectation is satisfied.
-  bool IsSatisfied() const
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
+  bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
     g_gmock_mutex.AssertHeld();
     return cardinality().IsSatisfiedByCallCount(call_count_);
   }
 
   // Returns true if and only if this expectation is saturated.
-  bool IsSaturated() const
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
+  bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
     g_gmock_mutex.AssertHeld();
     return cardinality().IsSaturatedByCallCount(call_count_);
   }
 
   // Returns true if and only if this expectation is over-saturated.
-  bool IsOverSaturated() const
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
+  bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
     g_gmock_mutex.AssertHeld();
     return cardinality().IsOverSaturatedByCallCount(call_count_);
   }
@@ -832,15 +800,13 @@ class GTEST_API_ ExpectationBase {
       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
 
   // Returns the number this expectation has been invoked.
-  int call_count() const
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
+  int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
     g_gmock_mutex.AssertHeld();
     return call_count_;
   }
 
   // Increments the number this expectation has been invoked.
-  void IncrementCallCount()
-      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
+  void IncrementCallCount() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
     g_gmock_mutex.AssertHeld();
     call_count_++;
   }
@@ -849,8 +815,7 @@ class GTEST_API_ ExpectationBase {
   // WillRepeatedly() clauses) against the cardinality if this hasn't
   // been done before.  Prints a warning if there are too many or too
   // few actions.
-  void CheckActionCountIfNotDone() const
-      GTEST_LOCK_EXCLUDED_(mutex_);
+  void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_);
 
   friend class ::testing::Sequence;
   friend class ::testing::internal::ExpectationTester;
@@ -863,12 +828,12 @@ class GTEST_API_ ExpectationBase {
 
   // This group of fields are part of the spec and won't change after
   // an EXPECT_CALL() statement finishes.
-  const char* file_;          // The file that contains the expectation.
-  int line_;                  // The line number of the expectation.
+  const char* file_;               // The file that contains the expectation.
+  int line_;                       // The line number of the expectation.
   const std::string source_text_;  // The EXPECT_CALL(...) source text.
   // True if and only if the cardinality is specified explicitly.
   bool cardinality_specified_;
-  Cardinality cardinality_;            // The cardinality of the expectation.
+  Cardinality cardinality_;  // The cardinality of the expectation.
   // The immediate pre-requisites (i.e. expectations that must be
   // satisfied before this expectation can be matched) of this
   // expectation.  We use std::shared_ptr in the set because we want an
@@ -887,12 +852,18 @@ class GTEST_API_ ExpectationBase {
   bool retires_on_saturation_;
   Clause last_clause_;
   mutable bool action_count_checked_;  // Under mutex_.
-  mutable Mutex mutex_;  // Protects action_count_checked_.
-};  // class ExpectationBase
+  mutable Mutex mutex_;                // Protects action_count_checked_.
+};                                     // class ExpectationBase
 
-// Impements an expectation for the given function type.
 template <typename F>
-class TypedExpectation : public ExpectationBase {
+class TypedExpectation;
+
+// Implements an expectation for the given function type.
+template <typename R, typename... Args>
+class TypedExpectation<R(Args...)> : public ExpectationBase {
+ private:
+  using F = R(Args...);
+
  public:
   typedef typename Function<F>::ArgumentTuple ArgumentTuple;
   typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
@@ -945,9 +916,7 @@ class TypedExpectation : public ExpectationBase {
   }
 
   // Implements the .Times() clause.
-  TypedExpectation& Times(int n) {
-    return Times(Exactly(n));
-  }
+  TypedExpectation& Times(int n) { return Times(Exactly(n)); }
 
   // Implements the .InSequence() clause.
   TypedExpectation& InSequence(const Sequence& s) {
@@ -1007,14 +976,31 @@ class TypedExpectation : public ExpectationBase {
     return After(s1, s2, s3, s4).After(s5);
   }
 
-  // Implements the .WillOnce() clause.
-  TypedExpectation& WillOnce(const Action<F>& action) {
+  // Preferred, type-safe overload: consume anything that can be directly
+  // converted to a OnceAction, except for Action<F> objects themselves.
+  TypedExpectation& WillOnce(OnceAction<F> once_action) {
+    // Call the overload below, smuggling the OnceAction as a copyable callable.
+    // We know this is safe because a WillOnce action will not be called more
+    // than once.
+    return WillOnce(Action<F>(ActionAdaptor{
+        std::make_shared<OnceAction<F>>(std::move(once_action)),
+    }));
+  }
+
+  // Fallback overload: accept Action<F> objects and those actions that define
+  // `operator Action<F>` but not `operator OnceAction<F>`.
+  //
+  // This is templated in order to cause the overload above to be preferred
+  // when the input is convertible to either type.
+  template <int&... ExplicitArgumentBarrier, typename = void>
+  TypedExpectation& WillOnce(Action<F> action) {
     ExpectSpecProperty(last_clause_ <= kWillOnce,
                        ".WillOnce() cannot appear after "
                        ".WillRepeatedly() or .RetiresOnSaturation().");
     last_clause_ = kWillOnce;
 
-    untyped_actions_.push_back(new Action<F>(action));
+    untyped_actions_.push_back(new Action<F>(std::move(action)));
+
     if (!cardinality_specified()) {
       set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
     }
@@ -1062,9 +1048,7 @@ class TypedExpectation : public ExpectationBase {
 
   // Returns the matchers for the arguments as specified inside the
   // EXPECT_CALL() macro.
-  const ArgumentMatcherTuple& matchers() const {
-    return matchers_;
-  }
+  const ArgumentMatcherTuple& matchers() const { return matchers_; }
 
   // Returns the matcher specified by the .With() clause.
   const Matcher<const ArgumentTuple&>& extra_matcher() const {
@@ -1088,6 +1072,16 @@ class TypedExpectation : public ExpectationBase {
   template <typename Function>
   friend class FunctionMocker;
 
+  // An adaptor that turns a OneAction<F> into something compatible with
+  // Action<F>. Must be called at most once.
+  struct ActionAdaptor {
+    std::shared_ptr<OnceAction<R(Args...)>> once_action;
+
+    R operator()(Args&&... args) const {
+      return std::move(*once_action).Call(std::forward<Args>(args)...);
+    }
+  };
+
   // Returns an Expectation object that references and co-owns this
   // expectation.
   Expectation GetHandle() override { return owner_->GetHandleOf(this); }
@@ -1119,10 +1113,8 @@ class TypedExpectation : public ExpectationBase {
 
   // Describes the result of matching the arguments against this
   // expectation to the given ostream.
-  void ExplainMatchResultTo(
-      const ArgumentTuple& args,
-      ::std::ostream* os) const
-          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
+  void ExplainMatchResultTo(const ArgumentTuple& args, ::std::ostream* os) const
+      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
     g_gmock_mutex.AssertHeld();
 
     if (is_retired()) {
@@ -1181,9 +1173,9 @@ class TypedExpectation : public ExpectationBase {
       ::std::stringstream ss;
       DescribeLocationTo(&ss);
       ss << "Actions ran out in " << source_text() << "...\n"
-         << "Called " << count << " times, but only "
-         << action_count << " WillOnce()"
-         << (action_count == 1 ? " is" : "s are") << " specified - ";
+         << "Called " << count << " times, but only " << action_count
+         << " WillOnce()" << (action_count == 1 ? " is" : "s are")
+         << " specified - ";
       mocker->DescribeDefaultActionTo(args, &ss);
       Log(kWarning, ss.str(), 1);
     }
@@ -1225,7 +1217,7 @@ class TypedExpectation : public ExpectationBase {
     }
 
     // Must be done after IncrementCount()!
-    *what << "Mock function call matches " << source_text() <<"...\n";
+    *what << "Mock function call matches " << source_text() << "...\n";
     return &(GetCurrentAction(mocker, args));
   }
 
@@ -1236,7 +1228,8 @@ class TypedExpectation : public ExpectationBase {
   Matcher<const ArgumentTuple&> extra_matcher_;
   Action<F> repeated_action_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
+  TypedExpectation(const TypedExpectation&) = delete;
+  TypedExpectation& operator=(const TypedExpectation&) = delete;
 };  // class TypedExpectation
 
 // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
@@ -1258,8 +1251,8 @@ template <typename F>
 class MockSpec {
  public:
   typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
-  typedef typename internal::Function<F>::ArgumentMatcherTuple
-      ArgumentMatcherTuple;
+  typedef
+      typename internal::Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
 
   // Constructs a MockSpec object, given the function mocker object
   // that the spec is associated with.
@@ -1269,8 +1262,9 @@ class MockSpec {
 
   // Adds a new default action spec to the function mocker and returns
   // the newly created spec.
-  internal::OnCallSpec<F>& InternalDefaultActionSetAt(
-      const char* file, int line, const char* obj, const char* call) {
+  internal::OnCallSpec<F>& InternalDefaultActionSetAt(const char* file,
+                                                      int line, const char* obj,
+                                                      const char* call) {
     LogWithLocation(internal::kInfo, file, line,
                     std::string("ON_CALL(") + obj + ", " + call + ") invoked");
     return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
@@ -1278,13 +1272,14 @@ class MockSpec {
 
   // Adds a new expectation spec to the function mocker and returns
   // the newly created spec.
-  internal::TypedExpectation<F>& InternalExpectedAt(
-      const char* file, int line, const char* obj, const char* call) {
+  internal::TypedExpectation<F>& InternalExpectedAt(const char* file, int line,
+                                                    const char* obj,
+                                                    const char* call) {
     const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
                                   call + ")");
     LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
-    return function_mocker_->AddNewExpectation(
-        file, line, source_text, matchers_);
+    return function_mocker_->AddNewExpectation(file, line, source_text,
+                                               matchers_);
   }
 
   // This operator overload is used to swallow the superfluous parameter list
@@ -1317,9 +1312,7 @@ template <typename T>
 class ReferenceOrValueWrapper {
  public:
   // Constructs a wrapper from the given value/reference.
-  explicit ReferenceOrValueWrapper(T value)
-      : value_(std::move(value)) {
-  }
+  explicit ReferenceOrValueWrapper(T value) : value_(std::move(value)) {}
 
   // Unwraps and returns the underlying value/reference, exactly as
   // originally passed. The behavior of calling this more than once on
@@ -1330,9 +1323,7 @@ class ReferenceOrValueWrapper {
   // Always returns a const reference (more precisely,
   // const std::add_lvalue_reference<T>::type). The behavior of calling this
   // after calling Unwrap on the same object is unspecified.
-  const T& Peek() const {
-    return value_;
-  }
+  const T& Peek() const { return value_; }
 
  private:
   T value_;
@@ -1346,8 +1337,7 @@ class ReferenceOrValueWrapper<T&> {
   // Workaround for debatable pass-by-reference lint warning (c-library-team
   // policy precludes NOLINT in this context)
   typedef T& reference;
-  explicit ReferenceOrValueWrapper(reference ref)
-      : value_ptr_(&ref) {}
+  explicit ReferenceOrValueWrapper(reference ref) : value_ptr_(&ref) {}
   T& Unwrap() { return *value_ptr_; }
   const T& Peek() const { return *value_ptr_; }
 
@@ -1355,102 +1345,27 @@ class ReferenceOrValueWrapper<T&> {
   T* value_ptr_;
 };
 
-// C++ treats the void type specially.  For example, you cannot define
-// a void-typed variable or pass a void value to a function.
-// ActionResultHolder<T> holds a value of type T, where T must be a
-// copyable type or void (T doesn't need to be default-constructable).
-// It hides the syntactic difference between void and other types, and
-// is used to unify the code for invoking both void-returning and
-// non-void-returning mock functions.
-
-// Untyped base class for ActionResultHolder<T>.
-class UntypedActionResultHolderBase {
- public:
-  virtual ~UntypedActionResultHolderBase() {}
-
-  // Prints the held value as an action's result to os.
-  virtual void PrintAsActionResult(::std::ostream* os) const = 0;
-};
-
-// This generic definition is used when T is not void.
+// Prints the held value as an action's result to os.
 template <typename T>
-class ActionResultHolder : public UntypedActionResultHolderBase {
- public:
-  // Returns the held value. Must not be called more than once.
-  T Unwrap() {
-    return result_.Unwrap();
-  }
-
-  // Prints the held value as an action's result to os.
-  void PrintAsActionResult(::std::ostream* os) const override {
-    *os << "\n          Returns: ";
-    // T may be a reference type, so we don't use UniversalPrint().
-    UniversalPrinter<T>::Print(result_.Peek(), os);
-  }
-
-  // Performs the given mock function's default action and returns the
-  // result in a new-ed ActionResultHolder.
-  template <typename F>
-  static ActionResultHolder* PerformDefaultAction(
-      const FunctionMocker<F>* func_mocker,
-      typename Function<F>::ArgumentTuple&& args,
-      const std::string& call_description) {
-    return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
-        std::move(args), call_description)));
-  }
-
-  // Performs the given action and returns the result in a new-ed
-  // ActionResultHolder.
-  template <typename F>
-  static ActionResultHolder* PerformAction(
-      const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
-    return new ActionResultHolder(
-        Wrapper(action.Perform(std::move(args))));
-  }
-
- private:
-  typedef ReferenceOrValueWrapper<T> Wrapper;
-
-  explicit ActionResultHolder(Wrapper result)
-      : result_(std::move(result)) {
-  }
-
-  Wrapper result_;
+void PrintAsActionResult(const T& result, std::ostream& os) {
+  os << "\n          Returns: ";
+  // T may be a reference type, so we don't use UniversalPrint().
+  UniversalPrinter<T>::Print(result, &os);
+}
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
-};
+// Reports an uninteresting call (whose description is in msg) in the
+// manner specified by 'reaction'.
+GTEST_API_ void ReportUninterestingCall(CallReaction reaction,
+                                        const std::string& msg);
 
-// Specialization for T = void.
-template <>
-class ActionResultHolder<void> : public UntypedActionResultHolderBase {
+// A generic RAII type that runs a user-provided function in its destructor.
+class Cleanup final {
  public:
-  void Unwrap() { }
-
-  void PrintAsActionResult(::std::ostream* /* os */) const override {}
-
-  // Performs the given mock function's default action and returns ownership
-  // of an empty ActionResultHolder*.
-  template <typename F>
-  static ActionResultHolder* PerformDefaultAction(
-      const FunctionMocker<F>* func_mocker,
-      typename Function<F>::ArgumentTuple&& args,
-      const std::string& call_description) {
-    func_mocker->PerformDefaultAction(std::move(args), call_description);
-    return new ActionResultHolder;
-  }
-
-  // Performs the given action and returns ownership of an empty
-  // ActionResultHolder*.
-  template <typename F>
-  static ActionResultHolder* PerformAction(
-      const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
-    action.Perform(std::move(args));
-    return new ActionResultHolder;
-  }
+  explicit Cleanup(std::function<void()> f) : f_(std::move(f)) {}
+  ~Cleanup() { f_(); }
 
  private:
-  ActionResultHolder() {}
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
+  std::function<void()> f_;
 };
 
 template <typename F>
@@ -1495,14 +1410,12 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
   // Returns the ON_CALL spec that matches this mock function with the
   // given arguments; returns NULL if no matching ON_CALL is found.
   // L = *
-  const OnCallSpec<F>* FindOnCallSpec(
-      const ArgumentTuple& args) const {
-    for (UntypedOnCallSpecs::const_reverse_iterator it
-             = untyped_on_call_specs_.rbegin();
+  const OnCallSpec<F>* FindOnCallSpec(const ArgumentTuple& args) const {
+    for (UntypedOnCallSpecs::const_reverse_iterator it =
+             untyped_on_call_specs_.rbegin();
          it != untyped_on_call_specs_.rend(); ++it) {
       const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
-      if (spec->Matches(args))
-        return spec;
+      if (spec->Matches(args)) return spec;
     }
 
     return nullptr;
@@ -1510,15 +1423,14 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
 
   // Performs the default action of this mock function on the given
   // arguments and returns the result. Asserts (or throws if
-  // exceptions are enabled) with a helpful call descrption if there
+  // exceptions are enabled) with a helpful call description if there
   // is no valid return value. This method doesn't depend on the
   // mutable state of this object, and thus can be called concurrently
   // without locking.
   // L = *
   Result PerformDefaultAction(ArgumentTuple&& args,
                               const std::string& call_description) const {
-    const OnCallSpec<F>* const spec =
-        this->FindOnCallSpec(args);
+    const OnCallSpec<F>* const spec = this->FindOnCallSpec(args);
     if (spec != nullptr) {
       return spec->GetAction().Perform(std::move(args));
     }
@@ -1536,32 +1448,6 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
     return DefaultValue<Result>::Get();
   }
 
-  // Performs the default action with the given arguments and returns
-  // the action's result.  The call description string will be used in
-  // the error message to describe the call in the case the default
-  // action fails.  The caller is responsible for deleting the result.
-  // L = *
-  UntypedActionResultHolderBase* UntypedPerformDefaultAction(
-      void* untyped_args,  // must point to an ArgumentTuple
-      const std::string& call_description) const override {
-    ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
-    return ResultHolder::PerformDefaultAction(this, std::move(*args),
-                                              call_description);
-  }
-
-  // Performs the given action with the given arguments and returns
-  // the action's result.  The caller is responsible for deleting the
-  // result.
-  // L = *
-  UntypedActionResultHolderBase* UntypedPerformAction(
-      const void* untyped_action, void* untyped_args) const override {
-    // Make a copy of the action before performing it, in case the
-    // action deletes the mock object (and thus deletes itself).
-    const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
-    ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
-    return ResultHolder::PerformAction(action, std::move(*args));
-  }
-
   // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
   // clears the ON_CALL()s set on this mock function.
   void ClearDefaultActionsLocked() override
@@ -1579,8 +1465,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
     untyped_on_call_specs_.swap(specs_to_delete);
 
     g_gmock_mutex.Unlock();
-    for (UntypedOnCallSpecs::const_iterator it =
-             specs_to_delete.begin();
+    for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin();
          it != specs_to_delete.end(); ++it) {
       delete static_cast<const OnCallSpec<F>*>(*it);
     }
@@ -1594,10 +1479,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
   // arguments.  This function can be safely called from multiple
   // threads concurrently.
   Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
-    ArgumentTuple tuple(std::forward<Args>(args)...);
-    std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>(
-        this->UntypedInvokeWith(static_cast<void*>(&tuple))));
-    return holder->Unwrap();
+    return InvokeWith(ArgumentTuple(std::forward<Args>(args)...));
   }
 
   MockSpec<F> With(Matcher<Args>... m) {
@@ -1608,13 +1490,10 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
   template <typename Function>
   friend class MockSpec;
 
-  typedef ActionResultHolder<Result> ResultHolder;
-
   // Adds and returns a default action spec for this mock function.
-  OnCallSpec<F>& AddNewOnCallSpec(
-      const char* file, int line,
-      const ArgumentMatcherTuple& m)
-          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
+  OnCallSpec<F>& AddNewOnCallSpec(const char* file, int line,
+                                  const ArgumentMatcherTuple& m)
+      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
     Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
     OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
     untyped_on_call_specs_.push_back(on_call_spec);
@@ -1644,7 +1523,8 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
   }
 
  private:
-  template <typename Func> friend class TypedExpectation;
+  template <typename Func>
+  friend class TypedExpectation;
 
   // Some utilities needed for implementing UntypedInvokeWith().
 
@@ -1728,9 +1608,8 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
 
   // Returns the expectation that matches the arguments, or NULL if no
   // expectation matches them.
-  TypedExpectation<F>* FindMatchingExpectationLocked(
-      const ArgumentTuple& args) const
-          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
+  TypedExpectation<F>* FindMatchingExpectationLocked(const ArgumentTuple& args)
+      const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
     g_gmock_mutex.AssertHeld();
     // See the definition of untyped_expectations_ for why access to
     // it is unprotected here.
@@ -1747,11 +1626,10 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
   }
 
   // Returns a message that the arguments don't match any expectation.
-  void FormatUnexpectedCallMessageLocked(
-      const ArgumentTuple& args,
-      ::std::ostream* os,
-      ::std::ostream* why) const
-          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
+  void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,
+                                         ::std::ostream* os,
+                                         ::std::ostream* why) const
+      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
     g_gmock_mutex.AssertHeld();
     *os << "\nUnexpected mock function call - ";
     DescribeDefaultActionTo(args, os);
@@ -1760,15 +1638,14 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
 
   // Prints a list of expectations that have been tried against the
   // current mock function call.
-  void PrintTriedExpectationsLocked(
-      const ArgumentTuple& args,
-      ::std::ostream* why) const
-          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
+  void PrintTriedExpectationsLocked(const ArgumentTuple& args,
+                                    ::std::ostream* why) const
+      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
     g_gmock_mutex.AssertHeld();
     const size_t count = untyped_expectations_.size();
     *why << "Google Mock tried the following " << count << " "
-         << (count == 1 ? "expectation, but it didn't match" :
-             "expectations, but none matched")
+         << (count == 1 ? "expectation, but it didn't match"
+                        : "expectations, but none matched")
          << ":\n";
     for (size_t i = 0; i < count; i++) {
       TypedExpectation<F>* const expectation =
@@ -1783,11 +1660,177 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
       expectation->DescribeCallCountTo(why);
     }
   }
+
+  // Performs the given action (or the default if it's null) with the given
+  // arguments and returns the action's result.
+  // L = *
+  R PerformAction(const void* untyped_action, ArgumentTuple&& args,
+                  const std::string& call_description) const {
+    if (untyped_action == nullptr) {
+      return PerformDefaultAction(std::move(args), call_description);
+    }
+
+    // Make a copy of the action before performing it, in case the
+    // action deletes the mock object (and thus deletes itself).
+    const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
+    return action.Perform(std::move(args));
+  }
+
+  // Is it possible to store an object of the supplied type in a local variable
+  // for the sake of printing it, then return it on to the caller?
+  template <typename T>
+  using can_print_result = internal::conjunction<
+      // void can't be stored as an object (and we also don't need to print it).
+      internal::negation<std::is_void<T>>,
+      // Non-moveable types can't be returned on to the user, so there's no way
+      // for us to intercept and print them.
+      std::is_move_constructible<T>>;
+
+  // Perform the supplied action, printing the result to os.
+  template <typename T = R,
+            typename std::enable_if<can_print_result<T>::value, int>::type = 0>
+  R PerformActionAndPrintResult(const void* const untyped_action,
+                                ArgumentTuple&& args,
+                                const std::string& call_description,
+                                std::ostream& os) {
+    R result = PerformAction(untyped_action, std::move(args), call_description);
+
+    PrintAsActionResult(result, os);
+    return std::forward<R>(result);
+  }
+
+  // An overload for when it's not possible to print the result. In this case we
+  // simply perform the action.
+  template <typename T = R,
+            typename std::enable_if<
+                internal::negation<can_print_result<T>>::value, int>::type = 0>
+  R PerformActionAndPrintResult(const void* const untyped_action,
+                                ArgumentTuple&& args,
+                                const std::string& call_description,
+                                std::ostream&) {
+    return PerformAction(untyped_action, std::move(args), call_description);
+  }
+
+  // Returns the result of invoking this mock function with the given
+  // arguments. This function can be safely called from multiple
+  // threads concurrently.
+  R InvokeWith(ArgumentTuple&& args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
 };  // class FunctionMocker
 
-// Reports an uninteresting call (whose description is in msg) in the
-// manner specified by 'reaction'.
-void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
+// Calculates the result of invoking this mock function with the given
+// arguments, prints it, and returns it.
+template <typename R, typename... Args>
+R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args)
+    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
+  // See the definition of untyped_expectations_ for why access to it
+  // is unprotected here.
+  if (untyped_expectations_.size() == 0) {
+    // No expectation is set on this mock method - we have an
+    // uninteresting call.
+
+    // We must get Google Mock's reaction on uninteresting calls
+    // made on this mock object BEFORE performing the action,
+    // because the action may DELETE the mock object and make the
+    // following expression meaningless.
+    const CallReaction reaction =
+        Mock::GetReactionOnUninterestingCalls(MockObject());
+
+    // True if and only if we need to print this call's arguments and return
+    // value.  This definition must be kept in sync with
+    // the behavior of ReportUninterestingCall().
+    const bool need_to_report_uninteresting_call =
+        // If the user allows this uninteresting call, we print it
+        // only when they want informational messages.
+        reaction == kAllow ? LogIsVisible(kInfo) :
+                           // If the user wants this to be a warning, we print
+                           // it only when they want to see warnings.
+            reaction == kWarn
+            ? LogIsVisible(kWarning)
+            :
+            // Otherwise, the user wants this to be an error, and we
+            // should always print detailed information in the error.
+            true;
+
+    if (!need_to_report_uninteresting_call) {
+      // Perform the action without printing the call information.
+      return this->PerformDefaultAction(
+          std::move(args), "Function call: " + std::string(Name()));
+    }
+
+    // Warns about the uninteresting call.
+    ::std::stringstream ss;
+    this->UntypedDescribeUninterestingCall(&args, &ss);
+
+    // Perform the action, print the result, and then report the uninteresting
+    // call.
+    //
+    // We use RAII to do the latter in case R is void or a non-moveable type. In
+    // either case we can't assign it to a local variable.
+    const Cleanup report_uninteresting_call(
+        [&] { ReportUninterestingCall(reaction, ss.str()); });
+
+    return PerformActionAndPrintResult(nullptr, std::move(args), ss.str(), ss);
+  }
+
+  bool is_excessive = false;
+  ::std::stringstream ss;
+  ::std::stringstream why;
+  ::std::stringstream loc;
+  const void* untyped_action = nullptr;
+
+  // The UntypedFindMatchingExpectation() function acquires and
+  // releases g_gmock_mutex.
+
+  const ExpectationBase* const untyped_expectation =
+      this->UntypedFindMatchingExpectation(&args, &untyped_action,
+                                           &is_excessive, &ss, &why);
+  const bool found = untyped_expectation != nullptr;
+
+  // True if and only if we need to print the call's arguments
+  // and return value.
+  // This definition must be kept in sync with the uses of Expect()
+  // and Log() in this function.
+  const bool need_to_report_call =
+      !found || is_excessive || LogIsVisible(kInfo);
+  if (!need_to_report_call) {
+    // Perform the action without printing the call information.
+    return PerformAction(untyped_action, std::move(args), "");
+  }
+
+  ss << "    Function call: " << Name();
+  this->UntypedPrintArgs(&args, &ss);
+
+  // In case the action deletes a piece of the expectation, we
+  // generate the message beforehand.
+  if (found && !is_excessive) {
+    untyped_expectation->DescribeLocationTo(&loc);
+  }
+
+  // Perform the action, print the result, and then fail or log in whatever way
+  // is appropriate.
+  //
+  // We use RAII to do the latter in case R is void or a non-moveable type. In
+  // either case we can't assign it to a local variable.
+  const Cleanup handle_failures([&] {
+    ss << "\n" << why.str();
+
+    if (!found) {
+      // No expectation matches this call - reports a failure.
+      Expect(false, nullptr, -1, ss.str());
+    } else if (is_excessive) {
+      // We had an upper-bound violation and the failure message is in ss.
+      Expect(false, untyped_expectation->file(), untyped_expectation->line(),
+             ss.str());
+    } else {
+      // We had an expected call and the matching expectation is
+      // described in ss.
+      Log(kInfo, loc.str() + ss.str(), 2);
+    }
+  });
+
+  return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(),
+                                     ss);
+}
 
 }  // namespace internal
 
@@ -1952,7 +1995,9 @@ using internal::MockSpec;
 //   // Expects a call to const MockFoo::Bar().
 //   EXPECT_CALL(Const(foo), Bar());
 template <typename T>
-inline const T& Const(const T& x) { return x; }
+inline const T& Const(const T& x) {
+  return x;
+}
 
 // Constructs an Expectation object that references and co-owns exp.
 inline Expectation::Expectation(internal::ExpectationBase& exp)  // NOLINT
index 12469bc466ebdfede2b8736be0f6f6c67277ebfc..568c8c71d78578ffab629c3634fea890c5accfd6 100644 (file)
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This is the main header file a user should include.
 
-// GOOGLETEST_CM0002 DO NOT DELETE
-
 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
 
 #include "gmock/gmock-more-matchers.h"
 #include "gmock/gmock-nice-strict.h"
 #include "gmock/internal/gmock-internal-utils.h"
-
-namespace testing {
+#include "gmock/internal/gmock-port.h"
 
 // Declares Google Mock flags that we want a user to use programmatically.
 GMOCK_DECLARE_bool_(catch_leaked_mocks);
 GMOCK_DECLARE_string_(verbose);
 GMOCK_DECLARE_int32_(default_mock_behavior);
 
+namespace testing {
+
 // Initializes Google Mock.  This must be called before running the
 // tests.  In particular, it parses the command line for the flags
 // that Google Mock recognizes.  Whenever a Google Mock flag is seen,
index f6c93f616d62414bc599efa06cd76742eb9977b8..9c4874fd0cb31e89682088eb1a91cc7a43857bee 100644 (file)
@@ -14,3 +14,5 @@ The following macros can be defined:
 *   `GMOCK_DEFINE_bool_(name, default_val, doc)`
 *   `GMOCK_DEFINE_int32_(name, default_val, doc)`
 *   `GMOCK_DEFINE_string_(name, default_val, doc)`
+*   `GMOCK_FLAG_GET(flag_name)`
+*   `GMOCK_FLAG_SET(flag_name, value)`
index 63f899962e39eeba01adc70cea5bdc03da8fde89..bbcad31c76efa9a05a9acb4032f73f6fd656b42e 100644 (file)
@@ -1,4 +1,5 @@
-// GOOGLETEST_CM0002 DO NOT DELETE
+// IWYU pragma: private, include "gmock/gmock.h"
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
index 638429488e216831d68b08c6be526feb51a910a4..bb7dcbaa4cb20035c897d55ba5e58f8c5d4c9cb3 100644 (file)
 // 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.
-//
+
 // Injection point for custom user configurations. See README for details
-//
-// GOOGLETEST_CM0002 DO NOT DELETE
+
+// IWYU pragma: private, include "gmock/gmock.h"
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
index 14378692aefe4dbb3f5a17d0393d9a5f39e01ba7..f055f7506b82ec481b295881a2c3f7f1b0a685e4 100644 (file)
 // 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.
-//
+
 // Injection point for custom user configurations. See README for details
 //
 // ** Custom implementation starts here **
 
-// GOOGLETEST_CM0002 DO NOT DELETE
+// IWYU pragma: private, include "gmock/gmock.h"
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
index 317544a7daf5da7ba9a28db1e991f071ef762960..b1343fdc82dc673d2b5084e6bae9394af41e0e50 100644 (file)
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file defines some utilities useful for implementing Google
 // Mock.  They are subject to change without notice, so please DO NOT
 // USE THEM IN USER CODE.
 
-// GOOGLETEST_CM0002 DO NOT DELETE
+// IWYU pragma: private, include "gmock/gmock.h"
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
 
 #include <stdio.h>
+
 #include <ostream>  // NOLINT
 #include <string>
 #include <type_traits>
+#include <vector>
+
 #include "gmock/internal/gmock-port.h"
 #include "gtest/gtest.h"
 
@@ -56,14 +59,15 @@ namespace internal {
 // Silence MSVC C4100 (unreferenced formal parameter) and
 // C4805('==': unsafe mix of type 'const int' and type 'const bool')
 #ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
-# pragma warning(disable:4805)
+#pragma warning(push)
+#pragma warning(disable : 4100)
+#pragma warning(disable : 4805)
 #endif
 
 // Joins a vector of strings as if they are fields of a tuple; returns
 // the joined string.
-GTEST_API_ std::string JoinAsTuple(const Strings& fields);
+GTEST_API_ std::string JoinAsKeyValueTuple(
+    const std::vector<const char*>& names, const Strings& values);
 
 // Converts an identifier name to a space-separated list of lower-case
 // words.  Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
@@ -78,9 +82,18 @@ template <typename Pointer>
 inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
   return p.get();
 }
+// This overload version is for std::reference_wrapper, which does not work with
+// the overload above, as it does not have an `element_type`.
+template <typename Element>
+inline const Element* GetRawPointer(const std::reference_wrapper<Element>& r) {
+  return &r.get();
+}
+
 // This overloaded version is for the raw pointer case.
 template <typename Element>
-inline Element* GetRawPointer(Element* p) { return p; }
+inline Element* GetRawPointer(Element* p) {
+  return p;
+}
 
 // MSVC treats wchar_t as a native type usually, but treats it as the
 // same as unsigned short when the compiler option /Zc:wchar_t- is
@@ -89,7 +102,7 @@ inline Element* GetRawPointer(Element* p) { return p; }
 #if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)
 // wchar_t is a typedef.
 #else
-# define GMOCK_WCHAR_T_IS_NATIVE_ 1
+#define GMOCK_WCHAR_T_IS_NATIVE_ 1
 #endif
 
 // In what follows, we use the term "kind" to indicate whether a type
@@ -97,18 +110,20 @@ inline Element* GetRawPointer(Element* p) { return p; }
 // or none of them.  This categorization is useful for determining
 // when a matcher argument type can be safely converted to another
 // type in the implementation of SafeMatcherCast.
-enum TypeKind {
-  kBool, kInteger, kFloatingPoint, kOther
-};
+enum TypeKind { kBool, kInteger, kFloatingPoint, kOther };
 
 // KindOf<T>::value is the kind of type T.
-template <typename T> struct KindOf {
+template <typename T>
+struct KindOf {
   enum { value = kOther };  // The default kind.
 };
 
 // This macro declares that the kind of 'type' is 'kind'.
 #define GMOCK_DECLARE_KIND_(type, kind) \
-  template <> struct KindOf<type> { enum { value = kind }; }
+  template <>                           \
+  struct KindOf<type> {                 \
+    enum { value = kind };              \
+  }
 
 GMOCK_DECLARE_KIND_(bool, kBool);
 
@@ -116,13 +131,13 @@ GMOCK_DECLARE_KIND_(bool, kBool);
 GMOCK_DECLARE_KIND_(char, kInteger);
 GMOCK_DECLARE_KIND_(signed char, kInteger);
 GMOCK_DECLARE_KIND_(unsigned char, kInteger);
-GMOCK_DECLARE_KIND_(short, kInteger);  // NOLINT
+GMOCK_DECLARE_KIND_(short, kInteger);           // NOLINT
 GMOCK_DECLARE_KIND_(unsigned short, kInteger);  // NOLINT
 GMOCK_DECLARE_KIND_(int, kInteger);
 GMOCK_DECLARE_KIND_(unsigned int, kInteger);
-GMOCK_DECLARE_KIND_(long, kInteger);  // NOLINT
-GMOCK_DECLARE_KIND_(unsigned long, kInteger);  // NOLINT
-GMOCK_DECLARE_KIND_(long long, kInteger);  // NOLINT
+GMOCK_DECLARE_KIND_(long, kInteger);                // NOLINT
+GMOCK_DECLARE_KIND_(unsigned long, kInteger);       // NOLINT
+GMOCK_DECLARE_KIND_(long long, kInteger);           // NOLINT
 GMOCK_DECLARE_KIND_(unsigned long long, kInteger);  // NOLINT
 
 #if GMOCK_WCHAR_T_IS_NATIVE_
@@ -137,7 +152,7 @@ GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
 #undef GMOCK_DECLARE_KIND_
 
 // Evaluates to the kind of 'type'.
-#define GMOCK_KIND_OF_(type) \
+#define GMOCK_KIND_OF_(type)                   \
   static_cast< ::testing::internal::TypeKind>( \
       ::testing::internal::KindOf<type>::value)
 
@@ -193,9 +208,7 @@ using LosslessArithmeticConvertible =
 class FailureReporterInterface {
  public:
   // The type of a failure (either non-fatal or fatal).
-  enum FailureType {
-    kNonfatal, kFatal
-  };
+  enum FailureType { kNonfatal, kFatal };
 
   virtual ~FailureReporterInterface() {}
 
@@ -215,8 +228,8 @@ GTEST_API_ FailureReporterInterface* GetFailureReporter();
 inline void Assert(bool condition, const char* file, int line,
                    const std::string& msg) {
   if (!condition) {
-    GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal,
-                                        file, line, msg);
+    GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file,
+                                        line, msg);
   }
 }
 inline void Assert(bool condition, const char* file, int line) {
@@ -237,10 +250,7 @@ inline void Expect(bool condition, const char* file, int line) {
 }
 
 // Severity level of a log.
-enum LogSeverity {
-  kInfo = 0,
-  kWarning = 1
-};
+enum LogSeverity { kInfo = 0, kWarning = 1 };
 
 // Valid values for the --gmock_verbose flag.
 
@@ -281,10 +291,10 @@ class WithoutMatchers {
 GTEST_API_ WithoutMatchers GetWithoutMatchers();
 
 // Disable MSVC warnings for infinite recursion, since in this case the
-// the recursion is unreachable.
+// recursion is unreachable.
 #ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4717)
+#pragma warning(push)
+#pragma warning(disable : 4717)
 #endif
 
 // Invalid<T>() is usable as an expression of type T, but will terminate
@@ -295,14 +305,17 @@ GTEST_API_ WithoutMatchers GetWithoutMatchers();
 template <typename T>
 inline T Invalid() {
   Assert(false, "", -1, "Internal error: attempt to return invalid value");
-  // This statement is unreachable, and would never terminate even if it
-  // could be reached. It is provided only to placate compiler warnings
-  // about missing return statements.
+#if defined(__GNUC__) || defined(__clang__)
+  __builtin_unreachable();
+#elif defined(_MSC_VER)
+  __assume(0);
+#else
   return Invalid<T>();
+#endif
 }
 
 #ifdef _MSC_VER
-# pragma warning(pop)
+#pragma warning(pop)
 #endif
 
 // Given a raw type (i.e. having no top-level reference or const
@@ -381,7 +394,8 @@ class StlContainerView< ::std::tuple<ElementPointer, Size> > {
 
 // The following specialization prevents the user from instantiating
 // StlContainer with a reference type.
-template <typename T> class StlContainerView<T&>;
+template <typename T>
+class StlContainerView<T&>;
 
 // A type transform to remove constness from the first part of a pair.
 // Pairs like that are used as the value_type of associative containers,
@@ -402,17 +416,18 @@ struct RemoveConstFromKey<std::pair<const K, V> > {
 GTEST_API_ void IllegalDoDefault(const char* file, int line);
 
 template <typename F, typename Tuple, size_t... Idx>
-auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>) -> decltype(
-    std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) {
+auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>)
+    -> decltype(std::forward<F>(f)(
+        std::get<Idx>(std::forward<Tuple>(args))...)) {
   return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
 }
 
 // Apply the function to a tuple of arguments.
 template <typename F, typename Tuple>
-auto Apply(F&& f, Tuple&& args) -> decltype(
-    ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
-              MakeIndexSequence<std::tuple_size<
-                  typename std::remove_reference<Tuple>::type>::value>())) {
+auto Apply(F&& f, Tuple&& args) -> decltype(ApplyImpl(
+    std::forward<F>(f), std::forward<Tuple>(args),
+    MakeIndexSequence<std::tuple_size<
+        typename std::remove_reference<Tuple>::type>::value>())) {
   return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
                    MakeIndexSequence<std::tuple_size<
                        typename std::remove_reference<Tuple>::type>::value>());
@@ -449,8 +464,10 @@ struct Function<R(Args...)> {
 template <typename R, typename... Args>
 constexpr size_t Function<R(Args...)>::ArgumentCount;
 
+bool Base64Unescape(const std::string& encoded, std::string* decoded);
+
 #ifdef _MSC_VER
-# pragma warning(pop)
+#pragma warning(pop)
 #endif
 
 }  // namespace internal
index 367a44d366a7485cff9601ed1ff1ed39f354072e..bc18a25f348c32bcea02b033c9f10bdd10bdbb66 100644 (file)
@@ -27,7 +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.
 
-//
 // Low-level types and utilities for porting Google Mock to various
 // platforms.  All macros ending with _ and symbols defined in an
 // internal namespace are subject to change without notice.  Code
@@ -35,7 +34,8 @@
 // end with _ are part of Google Mock's public API and can be used by
 // code outside Google Mock.
 
-// GOOGLETEST_CM0002 DO NOT DELETE
+// IWYU pragma: private, include "gmock/gmock.h"
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
 #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
 // here, as Google Mock depends on Google Test.  Only add a utility
 // here if it's truly specific to Google Mock.
 
-#include "gtest/internal/gtest-port.h"
 #include "gmock/internal/custom/gmock-port.h"
+#include "gtest/internal/gtest-port.h"
+
+#if GTEST_HAS_ABSL
+#include "absl/flags/declare.h"
+#include "absl/flags/flag.h"
+#endif
 
 // For MS Visual C++, check the compiler version. At least VS 2015 is
 // required to compile Google Mock.
 #if defined(_MSC_VER) && _MSC_VER < 1900
-# error "At least Visual C++ 2015 (14.0) is required to compile Google Mock."
+#error "At least Visual C++ 2015 (14.0) is required to compile Google Mock."
 #endif
 
 // Macro for referencing flags.  This is public as we want the user to
 // use this syntax to reference Google Mock flags.
+#define GMOCK_FLAG_NAME_(name) gmock_##name
 #define GMOCK_FLAG(name) FLAGS_gmock_##name
 
-#if !defined(GMOCK_DECLARE_bool_)
+// Pick a command line flags implementation.
+#if GTEST_HAS_ABSL
+
+// Macros for defining flags.
+#define GMOCK_DEFINE_bool_(name, default_val, doc) \
+  ABSL_FLAG(bool, GMOCK_FLAG_NAME_(name), default_val, doc)
+#define GMOCK_DEFINE_int32_(name, default_val, doc) \
+  ABSL_FLAG(int32_t, GMOCK_FLAG_NAME_(name), default_val, doc)
+#define GMOCK_DEFINE_string_(name, default_val, doc) \
+  ABSL_FLAG(std::string, GMOCK_FLAG_NAME_(name), default_val, doc)
 
 // Macros for declaring flags.
-# define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name)
-# define GMOCK_DECLARE_int32_(name) extern GTEST_API_ int32_t GMOCK_FLAG(name)
-# define GMOCK_DECLARE_string_(name) \
-    extern GTEST_API_ ::std::string GMOCK_FLAG(name)
+#define GMOCK_DECLARE_bool_(name) \
+  ABSL_DECLARE_FLAG(bool, GMOCK_FLAG_NAME_(name))
+#define GMOCK_DECLARE_int32_(name) \
+  ABSL_DECLARE_FLAG(int32_t, GMOCK_FLAG_NAME_(name))
+#define GMOCK_DECLARE_string_(name) \
+  ABSL_DECLARE_FLAG(std::string, GMOCK_FLAG_NAME_(name))
+
+#define GMOCK_FLAG_GET(name) ::absl::GetFlag(GMOCK_FLAG(name))
+#define GMOCK_FLAG_SET(name, value) \
+  (void)(::absl::SetFlag(&GMOCK_FLAG(name), value))
+
+#else  // GTEST_HAS_ABSL
 
 // Macros for defining flags.
-# define GMOCK_DEFINE_bool_(name, default_val, doc) \
-    GTEST_API_ bool GMOCK_FLAG(name) = (default_val)
-# define GMOCK_DEFINE_int32_(name, default_val, doc) \
-    GTEST_API_ int32_t GMOCK_FLAG(name) = (default_val)
-# define GMOCK_DEFINE_string_(name, default_val, doc) \
-    GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val)
-
-#endif  // !defined(GMOCK_DECLARE_bool_)
+#define GMOCK_DEFINE_bool_(name, default_val, doc)  \
+  namespace testing {                               \
+  GTEST_API_ bool GMOCK_FLAG(name) = (default_val); \
+  }                                                 \
+  static_assert(true, "no-op to require trailing semicolon")
+#define GMOCK_DEFINE_int32_(name, default_val, doc)    \
+  namespace testing {                                  \
+  GTEST_API_ int32_t GMOCK_FLAG(name) = (default_val); \
+  }                                                    \
+  static_assert(true, "no-op to require trailing semicolon")
+#define GMOCK_DEFINE_string_(name, default_val, doc)         \
+  namespace testing {                                        \
+  GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val); \
+  }                                                          \
+  static_assert(true, "no-op to require trailing semicolon")
+
+// Macros for declaring flags.
+#define GMOCK_DECLARE_bool_(name)          \
+  namespace testing {                      \
+  GTEST_API_ extern bool GMOCK_FLAG(name); \
+  }                                        \
+  static_assert(true, "no-op to require trailing semicolon")
+#define GMOCK_DECLARE_int32_(name)            \
+  namespace testing {                         \
+  GTEST_API_ extern int32_t GMOCK_FLAG(name); \
+  }                                           \
+  static_assert(true, "no-op to require trailing semicolon")
+#define GMOCK_DECLARE_string_(name)                 \
+  namespace testing {                               \
+  GTEST_API_ extern ::std::string GMOCK_FLAG(name); \
+  }                                                 \
+  static_assert(true, "no-op to require trailing semicolon")
+
+#define GMOCK_FLAG_GET(name) ::testing::GMOCK_FLAG(name)
+#define GMOCK_FLAG_SET(name, value) (void)(::testing::GMOCK_FLAG(name) = value)
+
+#endif  // GTEST_HAS_ABSL
 
 #endif  // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
diff --git a/googlemock/scripts/README.md b/googlemock/scripts/README.md
deleted file mode 100644 (file)
index a3301e5..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-# Please Note:
-
-Files in this directory are no longer supported by the maintainers. They
-represent mostly historical artifacts and supported by the community only. There
-is no guarantee whatsoever that these scripts still work.
diff --git a/googlemock/scripts/fuse_gmock_files.py b/googlemock/scripts/fuse_gmock_files.py
deleted file mode 100755 (executable)
index 7fa9b3a..0000000
+++ /dev/null
@@ -1,256 +0,0 @@
-#!/usr/bin/env python
-#
-# 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.
-"""fuse_gmock_files.py v0.1.0.
-
-Fuses Google Mock and Google Test source code into two .h files and a .cc file.
-
-SYNOPSIS
-       fuse_gmock_files.py [GMOCK_ROOT_DIR] OUTPUT_DIR
-
-       Scans GMOCK_ROOT_DIR for Google Mock and Google Test source
-       code, assuming Google Test is in the GMOCK_ROOT_DIR/../googletest
-       directory, and generates three files:
-       OUTPUT_DIR/gtest/gtest.h, OUTPUT_DIR/gmock/gmock.h, and
-       OUTPUT_DIR/gmock-gtest-all.cc.  Then you can build your tests
-       by adding OUTPUT_DIR to the include search path and linking
-       with OUTPUT_DIR/gmock-gtest-all.cc.  These three files contain
-       everything you need to use Google Mock.  Hence you can
-       "install" Google Mock by copying them to wherever you want.
-
-       GMOCK_ROOT_DIR can be omitted and defaults to the parent
-       directory of the directory holding this script.
-
-EXAMPLES
-       ./fuse_gmock_files.py fused_gmock
-       ./fuse_gmock_files.py path/to/unpacked/gmock fused_gmock
-
-This tool is experimental.  In particular, it assumes that there is no
-conditional inclusion of Google Mock or Google Test headers.  Please
-report any problems to googlemock@googlegroups.com.  You can read
-https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
-for more
-information.
-"""
-
-from __future__ import print_function
-
-import os
-import re
-import sys
-
-__author__ = 'wan@google.com (Zhanyong Wan)'
-
-# We assume that this file is in the scripts/ directory in the Google
-# Mock root directory.
-DEFAULT_GMOCK_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
-
-# We need to call into googletest/scripts/fuse_gtest_files.py.
-sys.path.append(os.path.join(DEFAULT_GMOCK_ROOT_DIR, '../googletest/scripts'))
-import fuse_gtest_files as gtest  # pylint:disable=g-import-not-at-top
-
-# Regex for matching
-# '#include "gmock/..."'.
-INCLUDE_GMOCK_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gmock/.+)"')
-
-# Where to find the source seed files.
-GMOCK_H_SEED = 'include/gmock/gmock.h'
-GMOCK_ALL_CC_SEED = 'src/gmock-all.cc'
-
-# Where to put the generated files.
-GTEST_H_OUTPUT = 'gtest/gtest.h'
-GMOCK_H_OUTPUT = 'gmock/gmock.h'
-GMOCK_GTEST_ALL_CC_OUTPUT = 'gmock-gtest-all.cc'
-
-
-def GetGTestRootDir(gmock_root):
-  """Returns the root directory of Google Test."""
-
-  return os.path.join(gmock_root, '../googletest')
-
-
-def ValidateGMockRootDir(gmock_root):
-  """Makes sure gmock_root points to a valid gmock root directory.
-
-  The function aborts the program on failure.
-
-  Args:
-    gmock_root: A string with the mock root directory.
-  """
-
-  gtest.ValidateGTestRootDir(GetGTestRootDir(gmock_root))
-  gtest.VerifyFileExists(gmock_root, GMOCK_H_SEED)
-  gtest.VerifyFileExists(gmock_root, GMOCK_ALL_CC_SEED)
-
-
-def ValidateOutputDir(output_dir):
-  """Makes sure output_dir points to a valid output directory.
-
-  The function aborts the program on failure.
-
-  Args:
-    output_dir: A string representing the output directory.
-  """
-
-  gtest.VerifyOutputFile(output_dir, gtest.GTEST_H_OUTPUT)
-  gtest.VerifyOutputFile(output_dir, GMOCK_H_OUTPUT)
-  gtest.VerifyOutputFile(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT)
-
-
-def FuseGMockH(gmock_root, output_dir):
-  """Scans folder gmock_root to generate gmock/gmock.h in output_dir."""
-
-  output_file = open(os.path.join(output_dir, GMOCK_H_OUTPUT), 'w')
-  processed_files = set()  # Holds all gmock headers we've processed.
-
-  def ProcessFile(gmock_header_path):
-    """Processes the given gmock header file."""
-
-    # We don't process the same header twice.
-    if gmock_header_path in processed_files:
-      return
-
-    processed_files.add(gmock_header_path)
-
-    # Reads each line in the given gmock header.
-
-    with open(os.path.join(gmock_root, gmock_header_path), 'r') as fh:
-      for line in fh:
-        m = INCLUDE_GMOCK_FILE_REGEX.match(line)
-        if m:
-          # '#include "gmock/..."'
-          # - let's process it recursively.
-          ProcessFile('include/' + m.group(1))
-        else:
-          m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
-          if m:
-            # '#include "gtest/foo.h"'
-            # We translate it to "gtest/gtest.h", regardless of what foo is,
-            # since all gtest headers are fused into gtest/gtest.h.
-
-            # There is no need to #include gtest.h twice.
-            if gtest.GTEST_H_SEED not in processed_files:
-              processed_files.add(gtest.GTEST_H_SEED)
-              output_file.write('#include "%s"\n' % (gtest.GTEST_H_OUTPUT,))
-          else:
-            # Otherwise we copy the line unchanged to the output file.
-            output_file.write(line)
-
-  ProcessFile(GMOCK_H_SEED)
-  output_file.close()
-
-
-def FuseGMockAllCcToFile(gmock_root, output_file):
-  """Scans folder gmock_root to fuse gmock-all.cc into output_file."""
-
-  processed_files = set()
-
-  def ProcessFile(gmock_source_file):
-    """Processes the given gmock source file."""
-
-    # We don't process the same #included file twice.
-    if gmock_source_file in processed_files:
-      return
-
-    processed_files.add(gmock_source_file)
-
-    # Reads each line in the given gmock source file.
-
-    with open(os.path.join(gmock_root, gmock_source_file), 'r') as fh:
-      for line in fh:
-        m = INCLUDE_GMOCK_FILE_REGEX.match(line)
-        if m:
-          # '#include "gmock/foo.h"'
-          # We treat it as '#include  "gmock/gmock.h"', as all other gmock
-          # headers are being fused into gmock.h and cannot be
-          # included directly.  No need to
-          # #include "gmock/gmock.h"
-          # more than once.
-
-          if GMOCK_H_SEED not in processed_files:
-            processed_files.add(GMOCK_H_SEED)
-            output_file.write('#include "%s"\n' % (GMOCK_H_OUTPUT,))
-        else:
-          m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
-          if m:
-            # '#include "gtest/..."'
-            # There is no need to #include gtest.h as it has been
-            # #included by gtest-all.cc.
-
-            pass
-          else:
-            m = gtest.INCLUDE_SRC_FILE_REGEX.match(line)
-            if m:
-              # It's '#include "src/foo"' - let's process it recursively.
-              ProcessFile(m.group(1))
-            else:
-              # Otherwise we copy the line unchanged to the output file.
-              output_file.write(line)
-
-  ProcessFile(GMOCK_ALL_CC_SEED)
-
-
-def FuseGMockGTestAllCc(gmock_root, output_dir):
-  """Scans folder gmock_root to generate gmock-gtest-all.cc in output_dir."""
-
-  with open(os.path.join(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT),
-            'w') as output_file:
-    # First, fuse gtest-all.cc into gmock-gtest-all.cc.
-    gtest.FuseGTestAllCcToFile(GetGTestRootDir(gmock_root), output_file)
-    # Next, append fused gmock-all.cc to gmock-gtest-all.cc.
-    FuseGMockAllCcToFile(gmock_root, output_file)
-
-
-def FuseGMock(gmock_root, output_dir):
-  """Fuses gtest.h, gmock.h, and gmock-gtest-all.h."""
-
-  ValidateGMockRootDir(gmock_root)
-  ValidateOutputDir(output_dir)
-
-  gtest.FuseGTestH(GetGTestRootDir(gmock_root), output_dir)
-  FuseGMockH(gmock_root, output_dir)
-  FuseGMockGTestAllCc(gmock_root, output_dir)
-
-
-def main():
-  argc = len(sys.argv)
-  if argc == 2:
-    # fuse_gmock_files.py OUTPUT_DIR
-    FuseGMock(DEFAULT_GMOCK_ROOT_DIR, sys.argv[1])
-  elif argc == 3:
-    # fuse_gmock_files.py GMOCK_ROOT_DIR OUTPUT_DIR
-    FuseGMock(sys.argv[1], sys.argv[2])
-  else:
-    print(__doc__)
-    sys.exit(1)
-
-
-if __name__ == '__main__':
-  main()
diff --git a/googlemock/scripts/generator/LICENSE b/googlemock/scripts/generator/LICENSE
deleted file mode 100644 (file)
index 87ea063..0000000
+++ /dev/null
@@ -1,203 +0,0 @@
-
-                                 Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
-
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
-
-   END OF TERMS AND CONDITIONS
-
-   APPENDIX: How to apply the Apache License to your work.
-
-      To apply the Apache License to your work, attach the following
-      boilerplate notice, with the fields enclosed by brackets "[]"
-      replaced with your own identifying information. (Don't include
-      the brackets!)  The text should be enclosed in the appropriate
-      comment syntax for the file format. We also recommend that a
-      file or class name and description of purpose be included on the
-      same "printed page" as the copyright notice for easier
-      identification within third-party archives.
-
-   Copyright [2007] Neal Norwitz
-   Portions Copyright [2007] Google Inc.
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-   you may not use this file except in compliance with the License.
-   You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
diff --git a/googlemock/scripts/generator/README b/googlemock/scripts/generator/README
deleted file mode 100644 (file)
index 01fd463..0000000
+++ /dev/null
@@ -1,34 +0,0 @@
-
-The Google Mock class generator is an application that is part of cppclean.
-For more information about cppclean, visit http://code.google.com/p/cppclean/
-
-The mock generator requires Python 2.3.5 or later.  If you don't have Python
-installed on your system, you will also need to install it.  You can download
-Python from:  http://www.python.org/download/releases/
-
-To use the Google Mock class generator, you need to call it
-on the command line passing the header file and class for which you want
-to generate a Google Mock class.
-
-Make sure to install the scripts somewhere in your path.  Then you can
-run the program.
-
-  gmock_gen.py header-file.h [ClassName]...
-
-If no ClassNames are specified, all classes in the file are emitted.
-
-To change the indentation from the default of 2, set INDENT in
-the environment.  For example to use an indent of 4 spaces:
-
-INDENT=4 gmock_gen.py header-file.h ClassName
-
-This version was made from SVN revision 281 in the cppclean repository.
-
-Known Limitations
------------------
-Not all code will be generated properly.  For example, when mocking templated
-classes, the template information is lost.  You will need to add the template
-information manually.
-
-Not all permutations of using multiple pointers/references will be rendered
-properly.  These will also have to be fixed manually.
diff --git a/googlemock/scripts/generator/README.cppclean b/googlemock/scripts/generator/README.cppclean
deleted file mode 100644 (file)
index 65431b6..0000000
+++ /dev/null
@@ -1,115 +0,0 @@
-Goal:
------
-  CppClean attempts to find problems in C++ source that slow development
-  in large code bases, for example various forms of unused code.
-  Unused code can be unused functions, methods, data members, types, etc
-  to unnecessary #include directives.  Unnecessary #includes can cause
-  considerable extra compiles increasing the edit-compile-run cycle.
-
-  The project home page is:   http://code.google.com/p/cppclean/
-
-
-Features:
----------
- * Find and print C++ language constructs: classes, methods, functions, etc.
- * Find classes with virtual methods, no virtual destructor, and no bases
- * Find global/static data that are potential problems when using threads
- * Unnecessary forward class declarations
- * Unnecessary function declarations
- * Undeclared function definitions
- * (planned) Find unnecessary header files #included
-   - No direct reference to anything in the header
-   - Header is unnecessary if classes were forward declared instead
- * (planned) Source files that reference headers not directly #included,
-   ie, files that rely on a transitive #include from another header
- * (planned) Unused members (private, protected, & public) methods and data
- * (planned) Store AST in a SQL database so relationships can be queried
-
-AST is Abstract Syntax Tree, a representation of parsed source code.
-http://en.wikipedia.org/wiki/Abstract_syntax_tree
-
-
-System Requirements:
---------------------
- * Python 2.4 or later (2.3 probably works too)
- * Works on Windows (untested), Mac OS X, and Unix
-
-
-How to Run:
------------
-  For all examples, it is assumed that cppclean resides in a directory called
-  /cppclean.
-
-  To print warnings for classes with virtual methods, no virtual destructor and
-  no base classes:
-
-      /cppclean/run.sh nonvirtual_dtors.py file1.h file2.h file3.cc ...
-
-  To print all the functions defined in header file(s):
-
-      /cppclean/run.sh functions.py file1.h file2.h ...
-
-  All the commands take multiple files on the command line.  Other programs
-  include: find_warnings, headers, methods, and types.  Some other programs
-  are available, but used primarily for debugging.
-
-  run.sh is a simple wrapper that sets PYTHONPATH to /cppclean and then
-  runs the program in /cppclean/cpp/PROGRAM.py.  There is currently
-  no equivalent for Windows.  Contributions for a run.bat file
-  would be greatly appreciated.
-
-
-How to Configure:
------------------
-  You can add a siteheaders.py file in /cppclean/cpp to configure where
-  to look for other headers (typically -I options passed to a compiler).
-  Currently two values are supported:  _TRANSITIVE and GetIncludeDirs.
-  _TRANSITIVE should be set to a boolean value (True or False) indicating
-  whether to transitively process all header files.  The default is False.
-
-  GetIncludeDirs is a function that takes a single argument and returns
-  a sequence of directories to include.  This can be a generator or
-  return a static list.
-
-      def GetIncludeDirs(filename):
-          return ['/some/path/with/other/headers']
-
-      # Here is a more complicated example.
-      def GetIncludeDirs(filename):
-          yield '/path1'
-          yield os.path.join('/path2', os.path.dirname(filename))
-          yield '/path3'
-
-
-How to Test:
-------------
-  For all examples, it is assumed that cppclean resides in a directory called
-  /cppclean.  The tests require
-
-  cd /cppclean
-  make test
-  # To generate expected results after a change:
-  make expected
-
-
-Current Status:
----------------
-  The parser works pretty well for header files, parsing about 99% of Google's
-  header files.  Anything which inspects structure of C++ source files should
-  work reasonably well.  Function bodies are not transformed to an AST,
-  but left as tokens.  Much work is still needed on finding unused header files
-  and storing an AST in a database.
-
-
-Non-goals:
-----------
- * Parsing all valid C++ source
- * Handling invalid C++ source gracefully
- * Compiling to machine code (or anything beyond an AST)
-
-
-Contact:
---------
-  If you used cppclean, I would love to hear about your experiences
-  cppclean@googlegroups.com.  Even if you don't use cppclean, I'd like to
-  hear from you.  :-)  (You can contact me directly at:  nnorwitz@gmail.com)
diff --git a/googlemock/scripts/generator/cpp/__init__.py b/googlemock/scripts/generator/cpp/__init__.py
deleted file mode 100755 (executable)
index e69de29..0000000
diff --git a/googlemock/scripts/generator/cpp/ast.py b/googlemock/scripts/generator/cpp/ast.py
deleted file mode 100755 (executable)
index 0e77016..0000000
+++ /dev/null
@@ -1,1773 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2007 Neal Norwitz
-# Portions Copyright 2007 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Generate an Abstract Syntax Tree (AST) for C++."""
-
-# FIXME:
-#  * Tokens should never be exported, need to convert to Nodes
-#    (return types, parameters, etc.)
-#  * Handle static class data for templatized classes
-#  * Handle casts (both C++ and C-style)
-#  * Handle conditions and loops (if/else, switch, for, while/do)
-#
-# TODO much, much later:
-#  * Handle #define
-#  * exceptions
-
-
-try:
-  # Python 3.x
-  import builtins
-except ImportError:
-  # Python 2.x
-  import __builtin__ as builtins
-
-import collections
-import sys
-import traceback
-
-from cpp import keywords
-from cpp import tokenize
-from cpp import utils
-
-
-if not hasattr(builtins, 'reversed'):
-  # Support Python 2.3 and earlier.
-  def reversed(seq):
-    for i in range(len(seq)-1, -1, -1):
-      yield seq[i]
-
-if not hasattr(builtins, 'next'):
-  # Support Python 2.5 and earlier.
-  def next(obj):
-    return obj.next()
-
-
-VISIBILITY_PUBLIC, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE = range(3)
-
-FUNCTION_NONE = 0x00
-FUNCTION_CONST = 0x01
-FUNCTION_VIRTUAL = 0x02
-FUNCTION_PURE_VIRTUAL = 0x04
-FUNCTION_CTOR = 0x08
-FUNCTION_DTOR = 0x10
-FUNCTION_ATTRIBUTE = 0x20
-FUNCTION_UNKNOWN_ANNOTATION = 0x40
-FUNCTION_THROW = 0x80
-FUNCTION_OVERRIDE = 0x100
-
-"""
-These are currently unused.  Should really handle these properly at some point.
-
-TYPE_MODIFIER_INLINE   = 0x010000
-TYPE_MODIFIER_EXTERN   = 0x020000
-TYPE_MODIFIER_STATIC   = 0x040000
-TYPE_MODIFIER_CONST    = 0x080000
-TYPE_MODIFIER_REGISTER = 0x100000
-TYPE_MODIFIER_VOLATILE = 0x200000
-TYPE_MODIFIER_MUTABLE  = 0x400000
-
-TYPE_MODIFIER_MAP = {
-    'inline': TYPE_MODIFIER_INLINE,
-    'extern': TYPE_MODIFIER_EXTERN,
-    'static': TYPE_MODIFIER_STATIC,
-    'const': TYPE_MODIFIER_CONST,
-    'register': TYPE_MODIFIER_REGISTER,
-    'volatile': TYPE_MODIFIER_VOLATILE,
-    'mutable': TYPE_MODIFIER_MUTABLE,
-    }
-"""
-
-_INTERNAL_TOKEN = 'internal'
-_NAMESPACE_POP = 'ns-pop'
-
-
-# TODO(nnorwitz): use this as a singleton for templated_types, etc
-# where we don't want to create a new empty dict each time.  It is also const.
-class _NullDict(object):
-  __contains__ = lambda self: False
-  keys = values = items = iterkeys = itervalues = iteritems = lambda self: ()
-
-
-# TODO(nnorwitz): move AST nodes into a separate module.
-class Node(object):
-  """Base AST node."""
-
-  def __init__(self, start, end):
-    self.start = start
-    self.end = end
-
-  def IsDeclaration(self):
-    """Returns bool if this node is a declaration."""
-    return False
-
-  def IsDefinition(self):
-    """Returns bool if this node is a definition."""
-    return False
-
-  def IsExportable(self):
-    """Returns bool if this node exportable from a header file."""
-    return False
-
-  def Requires(self, node):
-    """Does this AST node require the definition of the node passed in?"""
-    return False
-
-  def XXX__str__(self):
-    return self._StringHelper(self.__class__.__name__, '')
-
-  def _StringHelper(self, name, suffix):
-    if not utils.DEBUG:
-      return '%s(%s)' % (name, suffix)
-    return '%s(%d, %d, %s)' % (name, self.start, self.end, suffix)
-
-  def __repr__(self):
-    return str(self)
-
-
-class Define(Node):
-  def __init__(self, start, end, name, definition):
-    Node.__init__(self, start, end)
-    self.name = name
-    self.definition = definition
-
-  def __str__(self):
-    value = '%s %s' % (self.name, self.definition)
-    return self._StringHelper(self.__class__.__name__, value)
-
-
-class Include(Node):
-  def __init__(self, start, end, filename, system):
-    Node.__init__(self, start, end)
-    self.filename = filename
-    self.system = system
-
-  def __str__(self):
-    fmt = '"%s"'
-    if self.system:
-      fmt = '<%s>'
-    return self._StringHelper(self.__class__.__name__, fmt % self.filename)
-
-
-class Goto(Node):
-  def __init__(self, start, end, label):
-    Node.__init__(self, start, end)
-    self.label = label
-
-  def __str__(self):
-    return self._StringHelper(self.__class__.__name__, str(self.label))
-
-
-class Expr(Node):
-  def __init__(self, start, end, expr):
-    Node.__init__(self, start, end)
-    self.expr = expr
-
-  def Requires(self, node):
-    # TODO(nnorwitz): impl.
-    return False
-
-  def __str__(self):
-    return self._StringHelper(self.__class__.__name__, str(self.expr))
-
-
-class Return(Expr):
-  pass
-
-
-class Delete(Expr):
-  pass
-
-
-class Friend(Expr):
-  def __init__(self, start, end, expr, namespace):
-    Expr.__init__(self, start, end, expr)
-    self.namespace = namespace[:]
-
-
-class Using(Node):
-  def __init__(self, start, end, names):
-    Node.__init__(self, start, end)
-    self.names = names
-
-  def __str__(self):
-    return self._StringHelper(self.__class__.__name__, str(self.names))
-
-
-class Parameter(Node):
-  def __init__(self, start, end, name, parameter_type, default):
-    Node.__init__(self, start, end)
-    self.name = name
-    self.type = parameter_type
-    self.default = default
-
-  def Requires(self, node):
-    # TODO(nnorwitz): handle namespaces, etc.
-    return self.type.name == node.name
-
-  def __str__(self):
-    name = str(self.type)
-    suffix = '%s %s' % (name, self.name)
-    if self.default:
-      suffix += ' = ' + ''.join([d.name for d in self.default])
-    return self._StringHelper(self.__class__.__name__, suffix)
-
-
-class _GenericDeclaration(Node):
-  def __init__(self, start, end, name, namespace):
-    Node.__init__(self, start, end)
-    self.name = name
-    self.namespace = namespace[:]
-
-  def FullName(self):
-    prefix = ''
-    if self.namespace and self.namespace[-1]:
-      prefix = '::'.join(self.namespace) + '::'
-    return prefix + self.name
-
-  def _TypeStringHelper(self, suffix):
-    if self.namespace:
-      names = [n or '<anonymous>' for n in self.namespace]
-      suffix += ' in ' + '::'.join(names)
-    return self._StringHelper(self.__class__.__name__, suffix)
-
-
-# TODO(nnorwitz): merge with Parameter in some way?
-class VariableDeclaration(_GenericDeclaration):
-  def __init__(self, start, end, name, var_type, initial_value, namespace):
-    _GenericDeclaration.__init__(self, start, end, name, namespace)
-    self.type = var_type
-    self.initial_value = initial_value
-
-  def Requires(self, node):
-    # TODO(nnorwitz): handle namespaces, etc.
-    return self.type.name == node.name
-
-  def ToString(self):
-    """Return a string that tries to reconstitute the variable decl."""
-    suffix = '%s %s' % (self.type, self.name)
-    if self.initial_value:
-      suffix += ' = ' + self.initial_value
-    return suffix
-
-  def __str__(self):
-    return self._StringHelper(self.__class__.__name__, self.ToString())
-
-
-class Typedef(_GenericDeclaration):
-  def __init__(self, start, end, name, alias, namespace):
-    _GenericDeclaration.__init__(self, start, end, name, namespace)
-    self.alias = alias
-
-  def IsDefinition(self):
-    return True
-
-  def IsExportable(self):
-    return True
-
-  def Requires(self, node):
-    # TODO(nnorwitz): handle namespaces, etc.
-    name = node.name
-    for token in self.alias:
-      if token is not None and name == token.name:
-        return True
-    return False
-
-  def __str__(self):
-    suffix = '%s, %s' % (self.name, self.alias)
-    return self._TypeStringHelper(suffix)
-
-
-class _NestedType(_GenericDeclaration):
-  def __init__(self, start, end, name, fields, namespace):
-    _GenericDeclaration.__init__(self, start, end, name, namespace)
-    self.fields = fields
-
-  def IsDefinition(self):
-    return True
-
-  def IsExportable(self):
-    return True
-
-  def __str__(self):
-    suffix = '%s, {%s}' % (self.name, self.fields)
-    return self._TypeStringHelper(suffix)
-
-
-class Union(_NestedType):
-  pass
-
-
-class Enum(_NestedType):
-  pass
-
-
-class Class(_GenericDeclaration):
-  def __init__(self, start, end, name, bases, templated_types, body, namespace):
-    _GenericDeclaration.__init__(self, start, end, name, namespace)
-    self.bases = bases
-    self.body = body
-    self.templated_types = templated_types
-
-  def IsDeclaration(self):
-    return self.bases is None and self.body is None
-
-  def IsDefinition(self):
-    return not self.IsDeclaration()
-
-  def IsExportable(self):
-    return not self.IsDeclaration()
-
-  def Requires(self, node):
-    # TODO(nnorwitz): handle namespaces, etc.
-    if self.bases:
-      for token_list in self.bases:
-        # TODO(nnorwitz): bases are tokens, do name comparison.
-        for token in token_list:
-          if token.name == node.name:
-            return True
-    # TODO(nnorwitz): search in body too.
-    return False
-
-  def __str__(self):
-    name = self.name
-    if self.templated_types:
-      name += '<%s>' % self.templated_types
-    suffix = '%s, %s, %s' % (name, self.bases, self.body)
-    return self._TypeStringHelper(suffix)
-
-
-class Struct(Class):
-  pass
-
-
-class Function(_GenericDeclaration):
-  def __init__(self, start, end, name, return_type, parameters,
-               modifiers, templated_types, body, namespace):
-    _GenericDeclaration.__init__(self, start, end, name, namespace)
-    converter = TypeConverter(namespace)
-    self.return_type = converter.CreateReturnType(return_type)
-    self.parameters = converter.ToParameters(parameters)
-    self.modifiers = modifiers
-    self.body = body
-    self.templated_types = templated_types
-
-  def IsDeclaration(self):
-    return self.body is None
-
-  def IsDefinition(self):
-    return self.body is not None
-
-  def IsExportable(self):
-    if self.return_type and 'static' in self.return_type.modifiers:
-      return False
-    return None not in self.namespace
-
-  def Requires(self, node):
-    if self.parameters:
-      # TODO(nnorwitz): parameters are tokens, do name comparison.
-      for p in self.parameters:
-        if p.name == node.name:
-          return True
-    # TODO(nnorwitz): search in body too.
-    return False
-
-  def __str__(self):
-    # TODO(nnorwitz): add templated_types.
-    suffix = ('%s %s(%s), 0x%02x, %s' %
-              (self.return_type, self.name, self.parameters,
-               self.modifiers, self.body))
-    return self._TypeStringHelper(suffix)
-
-
-class Method(Function):
-  def __init__(self, start, end, name, in_class, return_type, parameters,
-               modifiers, templated_types, body, namespace):
-    Function.__init__(self, start, end, name, return_type, parameters,
-                      modifiers, templated_types, body, namespace)
-    # TODO(nnorwitz): in_class could also be a namespace which can
-    # mess up finding functions properly.
-    self.in_class = in_class
-
-
-class Type(_GenericDeclaration):
-  """Type used for any variable (eg class, primitive, struct, etc)."""
-
-  def __init__(self, start, end, name, templated_types, modifiers,
-               reference, pointer, array):
-    """
-        Args:
-          name: str name of main type
-          templated_types: [Class (Type?)] template type info between <>
-          modifiers: [str] type modifiers (keywords) eg, const, mutable, etc.
-          reference, pointer, array: bools
-        """
-    _GenericDeclaration.__init__(self, start, end, name, [])
-    self.templated_types = templated_types
-    if not name and modifiers:
-      self.name = modifiers.pop()
-    self.modifiers = modifiers
-    self.reference = reference
-    self.pointer = pointer
-    self.array = array
-
-  def __str__(self):
-    prefix = ''
-    if self.modifiers:
-      prefix = ' '.join(self.modifiers) + ' '
-    name = str(self.name)
-    if self.templated_types:
-      name += '<%s>' % self.templated_types
-    suffix = prefix + name
-    if self.reference:
-      suffix += '&'
-    if self.pointer:
-      suffix += '*'
-    if self.array:
-      suffix += '[]'
-    return self._TypeStringHelper(suffix)
-
-  # By definition, Is* are always False.  A Type can only exist in
-  # some sort of variable declaration, parameter, or return value.
-  def IsDeclaration(self):
-    return False
-
-  def IsDefinition(self):
-    return False
-
-  def IsExportable(self):
-    return False
-
-
-class TypeConverter(object):
-
-  def __init__(self, namespace_stack):
-    self.namespace_stack = namespace_stack
-
-  def _GetTemplateEnd(self, tokens, start):
-    count = 1
-    end = start
-    while 1:
-      token = tokens[end]
-      end += 1
-      if token.name == '<':
-        count += 1
-      elif token.name == '>':
-        count -= 1
-        if count == 0:
-          break
-    return tokens[start:end-1], end
-
-  def ToType(self, tokens):
-    """Convert [Token,...] to [Class(...), ] useful for base classes.
-        For example, code like class Foo : public Bar<x, y> { ... };
-        the "Bar<x, y>" portion gets converted to an AST.
-
-        Returns:
-          [Class(...), ...]
-        """
-    result = []
-    name_tokens = []
-    reference = pointer = array = False
-
-    def AddType(templated_types):
-      # Partition tokens into name and modifier tokens.
-      names = []
-      modifiers = []
-      for t in name_tokens:
-        if keywords.IsKeyword(t.name):
-          modifiers.append(t.name)
-        else:
-          names.append(t.name)
-      name = ''.join(names)
-      if name_tokens:
-        result.append(Type(name_tokens[0].start, name_tokens[-1].end,
-                           name, templated_types, modifiers,
-                           reference, pointer, array))
-      del name_tokens[:]
-
-    i = 0
-    end = len(tokens)
-    while i < end:
-      token = tokens[i]
-      if token.name == '<':
-        new_tokens, new_end = self._GetTemplateEnd(tokens, i+1)
-        AddType(self.ToType(new_tokens))
-        # If there is a comma after the template, we need to consume
-        # that here otherwise it becomes part of the name.
-        i = new_end
-        reference = pointer = array = False
-      elif token.name == ',':
-        AddType([])
-        reference = pointer = array = False
-      elif token.name == '*':
-        pointer = True
-      elif token.name == '&':
-        reference = True
-      elif token.name == '[':
-        pointer = True
-      elif token.name == ']':
-        pass
-      else:
-        name_tokens.append(token)
-      i += 1
-
-    if name_tokens:
-      # No '<' in the tokens, just a simple name and no template.
-      AddType([])
-    return result
-
-  def DeclarationToParts(self, parts, needs_name_removed):
-    name = None
-    default = []
-    if needs_name_removed:
-      # Handle default (initial) values properly.
-      for i, t in enumerate(parts):
-        if t.name == '=':
-          default = parts[i+1:]
-          name = parts[i-1].name
-          if name == ']' and parts[i-2].name == '[':
-            name = parts[i-3].name
-            i -= 1
-          parts = parts[:i-1]
-          break
-      else:
-        if parts[-1].token_type == tokenize.NAME:
-          name = parts.pop().name
-        else:
-          # TODO(nnorwitz): this is a hack that happens for code like
-          # Register(Foo<T>); where it thinks this is a function call
-          # but it's actually a declaration.
-          name = '???'
-    modifiers = []
-    type_name = []
-    other_tokens = []
-    templated_types = []
-    i = 0
-    end = len(parts)
-    while i < end:
-      p = parts[i]
-      if keywords.IsKeyword(p.name):
-        modifiers.append(p.name)
-      elif p.name == '<':
-        templated_tokens, new_end = self._GetTemplateEnd(parts, i+1)
-        templated_types = self.ToType(templated_tokens)
-        i = new_end - 1
-        # Don't add a spurious :: to data members being initialized.
-        next_index = i + 1
-        if next_index < end and parts[next_index].name == '::':
-          i += 1
-      elif p.name in ('[', ']', '='):
-        # These are handled elsewhere.
-        other_tokens.append(p)
-      elif p.name not in ('*', '&', '>'):
-        # Ensure that names have a space between them.
-        if (type_name and type_name[-1].token_type == tokenize.NAME and
-                p.token_type == tokenize.NAME):
-          type_name.append(tokenize.Token(tokenize.SYNTAX, ' ', 0, 0))
-        type_name.append(p)
-      else:
-        other_tokens.append(p)
-      i += 1
-    type_name = ''.join([t.name for t in type_name])
-    return name, type_name, templated_types, modifiers, default, other_tokens
-
-  def ToParameters(self, tokens):
-    if not tokens:
-      return []
-
-    result = []
-    name = type_name = ''
-    type_modifiers = []
-    pointer = reference = array = False
-    first_token = None
-    default = []
-
-    def AddParameter(end):
-      if default:
-        del default[0]  # Remove flag.
-      parts = self.DeclarationToParts(type_modifiers, True)
-      (name, type_name, templated_types, modifiers,
-       unused_default, unused_other_tokens) = parts
-      parameter_type = Type(first_token.start, first_token.end,
-                            type_name, templated_types, modifiers,
-                            reference, pointer, array)
-      p = Parameter(first_token.start, end, name,
-                    parameter_type, default)
-      result.append(p)
-
-    template_count = 0
-    brace_count = 0
-    for s in tokens:
-      if not first_token:
-        first_token = s
-
-      # Check for braces before templates, as we can have unmatched '<>'
-      # inside default arguments.
-      if s.name == '{':
-        brace_count += 1
-      elif s.name == '}':
-        brace_count -= 1
-      if brace_count > 0:
-        type_modifiers.append(s)
-        continue
-
-      if s.name == '<':
-        template_count += 1
-      elif s.name == '>':
-        template_count -= 1
-      if template_count > 0:
-        type_modifiers.append(s)
-        continue
-
-      if s.name == ',':
-        AddParameter(s.start)
-        name = type_name = ''
-        type_modifiers = []
-        pointer = reference = array = False
-        first_token = None
-        default = []
-      elif s.name == '*':
-        pointer = True
-      elif s.name == '&':
-        reference = True
-      elif s.name == '[':
-        array = True
-      elif s.name == ']':
-        pass  # Just don't add to type_modifiers.
-      elif s.name == '=':
-        # Got a default value.  Add any value (None) as a flag.
-        default.append(None)
-      elif default:
-        default.append(s)
-      else:
-        type_modifiers.append(s)
-    AddParameter(tokens[-1].end)
-    return result
-
-  def CreateReturnType(self, return_type_seq):
-    if not return_type_seq:
-      return None
-    start = return_type_seq[0].start
-    end = return_type_seq[-1].end
-    _, name, templated_types, modifiers, default, other_tokens = \
-        self.DeclarationToParts(return_type_seq, False)
-    names = [n.name for n in other_tokens]
-    reference = '&' in names
-    pointer = '*' in names
-    array = '[' in names
-    return Type(start, end, name, templated_types, modifiers,
-                reference, pointer, array)
-
-  def GetTemplateIndices(self, names):
-    # names is a list of strings.
-    start = names.index('<')
-    end = len(names) - 1
-    while end > 0:
-      if names[end] == '>':
-        break
-      end -= 1
-    return start, end+1
-
-class AstBuilder(object):
-  def __init__(self, token_stream, filename, in_class='', visibility=None,
-               namespace_stack=[]):
-    self.tokens = token_stream
-    self.filename = filename
-    # TODO(nnorwitz): use a better data structure (deque) for the queue.
-    # Switching directions of the "queue" improved perf by about 25%.
-    # Using a deque should be even better since we access from both sides.
-    self.token_queue = []
-    self.namespace_stack = namespace_stack[:]
-    self.in_class = in_class
-    if in_class is None:
-      self.in_class_name_only = None
-    else:
-      self.in_class_name_only = in_class.split('::')[-1]
-    self.visibility = visibility
-    self.in_function = False
-    self.current_token = None
-    # Keep the state whether we are currently handling a typedef or not.
-    self._handling_typedef = False
-
-    self.converter = TypeConverter(self.namespace_stack)
-
-  def HandleError(self, msg, token):
-    printable_queue = list(reversed(self.token_queue[-20:]))
-    sys.stderr.write('Got %s in %s @ %s %s\n' %
-                     (msg, self.filename, token, printable_queue))
-
-  def Generate(self):
-    while 1:
-      token = self._GetNextToken()
-      if not token:
-        break
-
-      # Get the next token.
-      self.current_token = token
-
-      # Dispatch on the next token type.
-      if token.token_type == _INTERNAL_TOKEN:
-        if token.name == _NAMESPACE_POP:
-          self.namespace_stack.pop()
-        continue
-
-      try:
-        result = self._GenerateOne(token)
-        if result is not None:
-          yield result
-      except:
-        self.HandleError('exception', token)
-        raise
-
-  def _CreateVariable(self, pos_token, name, type_name, type_modifiers,
-                      ref_pointer_name_seq, templated_types, value=None):
-    reference = '&' in ref_pointer_name_seq
-    pointer = '*' in ref_pointer_name_seq
-    array = '[' in ref_pointer_name_seq
-    var_type = Type(pos_token.start, pos_token.end, type_name,
-                    templated_types, type_modifiers,
-                    reference, pointer, array)
-    return VariableDeclaration(pos_token.start, pos_token.end,
-                               name, var_type, value, self.namespace_stack)
-
-  def _GenerateOne(self, token):
-    if token.token_type == tokenize.NAME:
-      if (keywords.IsKeyword(token.name) and
-          not keywords.IsBuiltinType(token.name)):
-        if token.name == 'enum':
-          # Pop the next token and only put it back if it's not
-          # 'class'.  This allows us to support the two-token
-          # 'enum class' keyword as if it were simply 'enum'.
-          next = self._GetNextToken()
-          if next.name != 'class':
-            self._AddBackToken(next)
-
-        method = getattr(self, 'handle_' + token.name)
-        return method()
-      elif token.name == self.in_class_name_only:
-        # The token name is the same as the class, must be a ctor if
-        # there is a paren.  Otherwise, it's the return type.
-        # Peek ahead to get the next token to figure out which.
-        next = self._GetNextToken()
-        self._AddBackToken(next)
-        if next.token_type == tokenize.SYNTAX and next.name == '(':
-          return self._GetMethod([token], FUNCTION_CTOR, None, True)
-        # Fall through--handle like any other method.
-
-      # Handle data or function declaration/definition.
-      syntax = tokenize.SYNTAX
-      temp_tokens, last_token = \
-          self._GetVarTokensUpToIgnoringTemplates(syntax,
-                                                  '(', ';', '{', '[')
-      temp_tokens.insert(0, token)
-      if last_token.name == '(':
-        # If there is an assignment before the paren,
-        # this is an expression, not a method.
-        expr = bool([e for e in temp_tokens if e.name == '='])
-        if expr:
-          new_temp = self._GetTokensUpTo(tokenize.SYNTAX, ';')
-          temp_tokens.append(last_token)
-          temp_tokens.extend(new_temp)
-          last_token = tokenize.Token(tokenize.SYNTAX, ';', 0, 0)
-
-      if last_token.name == '[':
-        # Handle array, this isn't a method, unless it's an operator.
-        # TODO(nnorwitz): keep the size somewhere.
-        # unused_size = self._GetTokensUpTo(tokenize.SYNTAX, ']')
-        temp_tokens.append(last_token)
-        if temp_tokens[-2].name == 'operator':
-          temp_tokens.append(self._GetNextToken())
-        else:
-          temp_tokens2, last_token = \
-              self._GetVarTokensUpTo(tokenize.SYNTAX, ';')
-          temp_tokens.extend(temp_tokens2)
-
-      if last_token.name == ';':
-        # Handle data, this isn't a method.
-        parts = self.converter.DeclarationToParts(temp_tokens, True)
-        (name, type_name, templated_types, modifiers, default,
-         unused_other_tokens) = parts
-
-        t0 = temp_tokens[0]
-        names = [t.name for t in temp_tokens]
-        if templated_types:
-          start, end = self.converter.GetTemplateIndices(names)
-          names = names[:start] + names[end:]
-        default = ''.join([t.name for t in default])
-        return self._CreateVariable(t0, name, type_name, modifiers,
-                                    names, templated_types, default)
-      if last_token.name == '{':
-        self._AddBackTokens(temp_tokens[1:])
-        self._AddBackToken(last_token)
-        method_name = temp_tokens[0].name
-        method = getattr(self, 'handle_' + method_name, None)
-        if not method:
-          # Must be declaring a variable.
-          # TODO(nnorwitz): handle the declaration.
-          return None
-        return method()
-      return self._GetMethod(temp_tokens, 0, None, False)
-    elif token.token_type == tokenize.SYNTAX:
-      if token.name == '~' and self.in_class:
-        # Must be a dtor (probably not in method body).
-        token = self._GetNextToken()
-        # self.in_class can contain A::Name, but the dtor will only
-        # be Name.  Make sure to compare against the right value.
-        if (token.token_type == tokenize.NAME and
-                token.name == self.in_class_name_only):
-          return self._GetMethod([token], FUNCTION_DTOR, None, True)
-      # TODO(nnorwitz): handle a lot more syntax.
-    elif token.token_type == tokenize.PREPROCESSOR:
-      # TODO(nnorwitz): handle more preprocessor directives.
-      # token starts with a #, so remove it and strip whitespace.
-      name = token.name[1:].lstrip()
-      if name.startswith('include'):
-        # Remove "include".
-        name = name[7:].strip()
-        assert name
-        # Handle #include \<newline> "header-on-second-line.h".
-        if name.startswith('\\'):
-          name = name[1:].strip()
-        assert name[0] in '<"', token
-        assert name[-1] in '>"', token
-        system = name[0] == '<'
-        filename = name[1:-1]
-        return Include(token.start, token.end, filename, system)
-      if name.startswith('define'):
-        # Remove "define".
-        name = name[6:].strip()
-        assert name
-        value = ''
-        for i, c in enumerate(name):
-          if c.isspace():
-            value = name[i:].lstrip()
-            name = name[:i]
-            break
-        return Define(token.start, token.end, name, value)
-      if name.startswith('if') and name[2:3].isspace():
-        condition = name[3:].strip()
-        if condition.startswith('0') or condition.startswith('(0)'):
-          self._SkipIf0Blocks()
-    return None
-
-  def _GetTokensUpTo(self, expected_token_type, expected_token):
-    return self._GetVarTokensUpTo(expected_token_type, expected_token)[0]
-
-  def _GetVarTokensUpTo(self, expected_token_type, *expected_tokens):
-    last_token = self._GetNextToken()
-    tokens = []
-    while (last_token.token_type != expected_token_type or
-           last_token.name not in expected_tokens):
-      tokens.append(last_token)
-      last_token = self._GetNextToken()
-    return tokens, last_token
-
-  # Same as _GetVarTokensUpTo, but skips over '<...>' which could contain an
-  # expected token.
-  def _GetVarTokensUpToIgnoringTemplates(self, expected_token_type,
-                                         *expected_tokens):
-    last_token = self._GetNextToken()
-    tokens = []
-    nesting = 0
-    while (nesting > 0 or
-           last_token.token_type != expected_token_type or
-           last_token.name not in expected_tokens):
-      tokens.append(last_token)
-      last_token = self._GetNextToken()
-      if last_token.name == '<':
-        nesting += 1
-      elif last_token.name == '>':
-        nesting -= 1
-    return tokens, last_token
-
-  # TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necessary.
-  def _IgnoreUpTo(self, token_type, token):
-    unused_tokens = self._GetTokensUpTo(token_type, token)
-
-  def _SkipIf0Blocks(self):
-    count = 1
-    while 1:
-      token = self._GetNextToken()
-      if token.token_type != tokenize.PREPROCESSOR:
-        continue
-
-      name = token.name[1:].lstrip()
-      if name.startswith('endif'):
-        count -= 1
-        if count == 0:
-          break
-      elif name.startswith('if'):
-        count += 1
-
-  def _GetMatchingChar(self, open_paren, close_paren, GetNextToken=None):
-    if GetNextToken is None:
-      GetNextToken = self._GetNextToken
-    # Assumes the current token is open_paren and we will consume
-    # and return up to the close_paren.
-    count = 1
-    token = GetNextToken()
-    while 1:
-      if token.token_type == tokenize.SYNTAX:
-        if token.name == open_paren:
-          count += 1
-        elif token.name == close_paren:
-          count -= 1
-          if count == 0:
-            break
-      yield token
-      token = GetNextToken()
-    yield token
-
-  def _GetParameters(self):
-    return self._GetMatchingChar('(', ')')
-
-  def GetScope(self):
-    return self._GetMatchingChar('{', '}')
-
-  def _GetNextToken(self):
-    if self.token_queue:
-      return self.token_queue.pop()
-    try:
-      return next(self.tokens)
-    except StopIteration:
-      return
-
-  def _AddBackToken(self, token):
-    if token.whence == tokenize.WHENCE_STREAM:
-      token.whence = tokenize.WHENCE_QUEUE
-      self.token_queue.insert(0, token)
-    else:
-      assert token.whence == tokenize.WHENCE_QUEUE, token
-      self.token_queue.append(token)
-
-  def _AddBackTokens(self, tokens):
-    if tokens:
-      if tokens[-1].whence == tokenize.WHENCE_STREAM:
-        for token in tokens:
-          token.whence = tokenize.WHENCE_QUEUE
-        self.token_queue[:0] = reversed(tokens)
-      else:
-        assert tokens[-1].whence == tokenize.WHENCE_QUEUE, tokens
-        self.token_queue.extend(reversed(tokens))
-
-  def GetName(self, seq=None):
-    """Returns ([tokens], next_token_info)."""
-    GetNextToken = self._GetNextToken
-    if seq is not None:
-      it = iter(seq)
-      GetNextToken = lambda: next(it)
-    next_token = GetNextToken()
-    tokens = []
-    last_token_was_name = False
-    while (next_token.token_type == tokenize.NAME or
-           (next_token.token_type == tokenize.SYNTAX and
-            next_token.name in ('::', '<'))):
-      # Two NAMEs in a row means the identifier should terminate.
-      # It's probably some sort of variable declaration.
-      if last_token_was_name and next_token.token_type == tokenize.NAME:
-        break
-      last_token_was_name = next_token.token_type == tokenize.NAME
-      tokens.append(next_token)
-      # Handle templated names.
-      if next_token.name == '<':
-        tokens.extend(self._GetMatchingChar('<', '>', GetNextToken))
-        last_token_was_name = True
-      next_token = GetNextToken()
-    return tokens, next_token
-
-  def GetMethod(self, modifiers, templated_types):
-    return_type_and_name = self._GetTokensUpTo(tokenize.SYNTAX, '(')
-    assert len(return_type_and_name) >= 1
-    return self._GetMethod(return_type_and_name, modifiers, templated_types,
-                           False)
-
-  def _GetMethod(self, return_type_and_name, modifiers, templated_types,
-                 get_paren):
-    template_portion = None
-    if get_paren:
-      token = self._GetNextToken()
-      assert token.token_type == tokenize.SYNTAX, token
-      if token.name == '<':
-        # Handle templatized dtors.
-        template_portion = [token]
-        template_portion.extend(self._GetMatchingChar('<', '>'))
-        token = self._GetNextToken()
-      assert token.token_type == tokenize.SYNTAX, token
-      assert token.name == '(', token
-
-    name = return_type_and_name.pop()
-    # Handle templatized ctors.
-    if name.name == '>':
-      index = 1
-      while return_type_and_name[index].name != '<':
-        index += 1
-      template_portion = return_type_and_name[index:] + [name]
-      del return_type_and_name[index:]
-      name = return_type_and_name.pop()
-    elif name.name == ']':
-      rt = return_type_and_name
-      assert rt[-1].name == '[', return_type_and_name
-      assert rt[-2].name == 'operator', return_type_and_name
-      name_seq = return_type_and_name[-2:]
-      del return_type_and_name[-2:]
-      name = tokenize.Token(tokenize.NAME, 'operator[]',
-                            name_seq[0].start, name.end)
-      # Get the open paren so _GetParameters() below works.
-      unused_open_paren = self._GetNextToken()
-
-    # TODO(nnorwitz): store template_portion.
-    return_type = return_type_and_name
-    indices = name
-    if return_type:
-      indices = return_type[0]
-
-    # Force ctor for templatized ctors.
-    if name.name == self.in_class and not modifiers:
-      modifiers |= FUNCTION_CTOR
-    parameters = list(self._GetParameters())
-    del parameters[-1]              # Remove trailing ')'.
-
-    # Handling operator() is especially weird.
-    if name.name == 'operator' and not parameters:
-      token = self._GetNextToken()
-      assert token.name == '(', token
-      parameters = list(self._GetParameters())
-      del parameters[-1]          # Remove trailing ')'.
-
-    token = self._GetNextToken()
-    while token.token_type == tokenize.NAME:
-      modifier_token = token
-      token = self._GetNextToken()
-      if modifier_token.name == 'const':
-        modifiers |= FUNCTION_CONST
-      elif modifier_token.name == '__attribute__':
-        # TODO(nnorwitz): handle more __attribute__ details.
-        modifiers |= FUNCTION_ATTRIBUTE
-        assert token.name == '(', token
-        # Consume everything between the (parens).
-        unused_tokens = list(self._GetMatchingChar('(', ')'))
-        token = self._GetNextToken()
-      elif modifier_token.name == 'throw':
-        modifiers |= FUNCTION_THROW
-        assert token.name == '(', token
-        # Consume everything between the (parens).
-        unused_tokens = list(self._GetMatchingChar('(', ')'))
-        token = self._GetNextToken()
-      elif modifier_token.name == 'override':
-        modifiers |= FUNCTION_OVERRIDE
-      elif modifier_token.name == modifier_token.name.upper():
-        # HACK(nnorwitz):  assume that all upper-case names
-        # are some macro we aren't expanding.
-        modifiers |= FUNCTION_UNKNOWN_ANNOTATION
-      else:
-        self.HandleError('unexpected token', modifier_token)
-
-    assert token.token_type == tokenize.SYNTAX, token
-    # Handle ctor initializers.
-    if token.name == ':':
-      # TODO(nnorwitz): anything else to handle for initializer list?
-      while token.name != ';' and token.name != '{':
-        token = self._GetNextToken()
-
-    # Handle pointer to functions that are really data but look
-    # like method declarations.
-    if token.name == '(':
-      if parameters[0].name == '*':
-        # name contains the return type.
-        name = parameters.pop()
-        # parameters contains the name of the data.
-        modifiers = [p.name for p in parameters]
-        # Already at the ( to open the parameter list.
-        function_parameters = list(self._GetMatchingChar('(', ')'))
-        del function_parameters[-1]  # Remove trailing ')'.
-        # TODO(nnorwitz): store the function_parameters.
-        token = self._GetNextToken()
-        assert token.token_type == tokenize.SYNTAX, token
-        assert token.name == ';', token
-        return self._CreateVariable(indices, name.name, indices.name,
-                                    modifiers, '', None)
-      # At this point, we got something like:
-      #  return_type (type::*name_)(params);
-      # This is a data member called name_ that is a function pointer.
-      # With this code: void (sq_type::*field_)(string&);
-      # We get: name=void return_type=[] parameters=sq_type ... field_
-      # TODO(nnorwitz): is return_type always empty?
-      # TODO(nnorwitz): this isn't even close to being correct.
-      # Just put in something so we don't crash and can move on.
-      real_name = parameters[-1]
-      modifiers = [p.name for p in self._GetParameters()]
-      del modifiers[-1]           # Remove trailing ')'.
-      return self._CreateVariable(indices, real_name.name, indices.name,
-                                  modifiers, '', None)
-
-    if token.name == '{':
-      body = list(self.GetScope())
-      del body[-1]                # Remove trailing '}'.
-    else:
-      body = None
-      if token.name == '=':
-        token = self._GetNextToken()
-
-        if token.name == 'default' or token.name == 'delete':
-          # Ignore explicitly defaulted and deleted special members
-          # in C++11.
-          token = self._GetNextToken()
-        else:
-          # Handle pure-virtual declarations.
-          assert token.token_type == tokenize.CONSTANT, token
-          assert token.name == '0', token
-          modifiers |= FUNCTION_PURE_VIRTUAL
-          token = self._GetNextToken()
-
-      if token.name == '[':
-        # TODO(nnorwitz): store tokens and improve parsing.
-        # template <typename T, size_t N> char (&ASH(T (&seq)[N]))[N];
-        tokens = list(self._GetMatchingChar('[', ']'))
-        token = self._GetNextToken()
-
-      assert token.name == ';', (token, return_type_and_name, parameters)
-
-    # Looks like we got a method, not a function.
-    if len(return_type) > 2 and return_type[-1].name == '::':
-      return_type, in_class = \
-          self._GetReturnTypeAndClassName(return_type)
-      return Method(indices.start, indices.end, name.name, in_class,
-                    return_type, parameters, modifiers, templated_types,
-                    body, self.namespace_stack)
-    return Function(indices.start, indices.end, name.name, return_type,
-                    parameters, modifiers, templated_types, body,
-                    self.namespace_stack)
-
-  def _GetReturnTypeAndClassName(self, token_seq):
-    # Splitting the return type from the class name in a method
-    # can be tricky.  For example, Return::Type::Is::Hard::To::Find().
-    # Where is the return type and where is the class name?
-    # The heuristic used is to pull the last name as the class name.
-    # This includes all the templated type info.
-    # TODO(nnorwitz): if there is only One name like in the
-    # example above, punt and assume the last bit is the class name.
-
-    # Ignore a :: prefix, if exists so we can find the first real name.
-    i = 0
-    if token_seq[0].name == '::':
-      i = 1
-    # Ignore a :: suffix, if exists.
-    end = len(token_seq) - 1
-    if token_seq[end-1].name == '::':
-      end -= 1
-
-    # Make a copy of the sequence so we can append a sentinel
-    # value. This is required for GetName will has to have some
-    # terminating condition beyond the last name.
-    seq_copy = token_seq[i:end]
-    seq_copy.append(tokenize.Token(tokenize.SYNTAX, '', 0, 0))
-    names = []
-    while i < end:
-      # Iterate through the sequence parsing out each name.
-      new_name, next = self.GetName(seq_copy[i:])
-      assert new_name, 'Got empty new_name, next=%s' % next
-      # We got a pointer or ref.  Add it to the name.
-      if next and next.token_type == tokenize.SYNTAX:
-        new_name.append(next)
-      names.append(new_name)
-      i += len(new_name)
-
-    # Now that we have the names, it's time to undo what we did.
-
-    # Remove the sentinel value.
-    names[-1].pop()
-    # Flatten the token sequence for the return type.
-    return_type = [e for seq in names[:-1] for e in seq]
-    # The class name is the last name.
-    class_name = names[-1]
-    return return_type, class_name
-
-  def handle_bool(self):
-    pass
-
-  def handle_char(self):
-    pass
-
-  def handle_int(self):
-    pass
-
-  def handle_long(self):
-    pass
-
-  def handle_short(self):
-    pass
-
-  def handle_double(self):
-    pass
-
-  def handle_float(self):
-    pass
-
-  def handle_void(self):
-    pass
-
-  def handle_wchar_t(self):
-    pass
-
-  def handle_unsigned(self):
-    pass
-
-  def handle_signed(self):
-    pass
-
-  def _GetNestedType(self, ctor):
-    name = None
-    name_tokens, token = self.GetName()
-    if name_tokens:
-      name = ''.join([t.name for t in name_tokens])
-
-    # Handle forward declarations.
-    if token.token_type == tokenize.SYNTAX and token.name == ';':
-      return ctor(token.start, token.end, name, None,
-                  self.namespace_stack)
-
-    if token.token_type == tokenize.NAME and self._handling_typedef:
-      self._AddBackToken(token)
-      return ctor(token.start, token.end, name, None,
-                  self.namespace_stack)
-
-    # Must be the type declaration.
-    fields = list(self._GetMatchingChar('{', '}'))
-    del fields[-1]                  # Remove trailing '}'.
-    if token.token_type == tokenize.SYNTAX and token.name == '{':
-      next = self._GetNextToken()
-      new_type = ctor(token.start, token.end, name, fields,
-                      self.namespace_stack)
-      # A name means this is an anonymous type and the name
-      # is the variable declaration.
-      if next.token_type != tokenize.NAME:
-        return new_type
-      name = new_type
-      token = next
-
-    # Must be variable declaration using the type prefixed with keyword.
-    assert token.token_type == tokenize.NAME, token
-    return self._CreateVariable(token, token.name, name, [], '', None)
-
-  def handle_struct(self):
-    # Special case the handling typedef/aliasing of structs here.
-    # It would be a pain to handle in the class code.
-    name_tokens, var_token = self.GetName()
-    if name_tokens:
-      next_token = self._GetNextToken()
-      is_syntax = (var_token.token_type == tokenize.SYNTAX and
-                   var_token.name[0] in '*&')
-      is_variable = (var_token.token_type == tokenize.NAME and
-                     next_token.name == ';')
-      variable = var_token
-      if is_syntax and not is_variable:
-        variable = next_token
-        temp = self._GetNextToken()
-        if temp.token_type == tokenize.SYNTAX and temp.name == '(':
-          # Handle methods declared to return a struct.
-          t0 = name_tokens[0]
-          struct = tokenize.Token(tokenize.NAME, 'struct',
-                                  t0.start-7, t0.start-2)
-          type_and_name = [struct]
-          type_and_name.extend(name_tokens)
-          type_and_name.extend((var_token, next_token))
-          return self._GetMethod(type_and_name, 0, None, False)
-        assert temp.name == ';', (temp, name_tokens, var_token)
-      if is_syntax or (is_variable and not self._handling_typedef):
-        modifiers = ['struct']
-        type_name = ''.join([t.name for t in name_tokens])
-        position = name_tokens[0]
-        return self._CreateVariable(position, variable.name, type_name,
-                                    modifiers, var_token.name, None)
-      name_tokens.extend((var_token, next_token))
-      self._AddBackTokens(name_tokens)
-    else:
-      self._AddBackToken(var_token)
-    return self._GetClass(Struct, VISIBILITY_PUBLIC, None)
-
-  def handle_union(self):
-    return self._GetNestedType(Union)
-
-  def handle_enum(self):
-    return self._GetNestedType(Enum)
-
-  def handle_auto(self):
-    # TODO(nnorwitz): warn about using auto?  Probably not since it
-    # will be reclaimed and useful for C++0x.
-    pass
-
-  def handle_register(self):
-    pass
-
-  def handle_const(self):
-    pass
-
-  def handle_inline(self):
-    pass
-
-  def handle_extern(self):
-    pass
-
-  def handle_static(self):
-    pass
-
-  def handle_virtual(self):
-    # What follows must be a method.
-    token = token2 = self._GetNextToken()
-    if token.name == 'inline':
-      # HACK(nnorwitz): handle inline dtors by ignoring 'inline'.
-      token2 = self._GetNextToken()
-    if token2.token_type == tokenize.SYNTAX and token2.name == '~':
-      return self.GetMethod(FUNCTION_VIRTUAL + FUNCTION_DTOR, None)
-    assert token.token_type == tokenize.NAME or token.name == '::', token
-    return_type_and_name, _ = self._GetVarTokensUpToIgnoringTemplates(
-        tokenize.SYNTAX, '(')  # )
-    return_type_and_name.insert(0, token)
-    if token2 is not token:
-      return_type_and_name.insert(1, token2)
-    return self._GetMethod(return_type_and_name, FUNCTION_VIRTUAL,
-                           None, False)
-
-  def handle_volatile(self):
-    pass
-
-  def handle_mutable(self):
-    pass
-
-  def handle_public(self):
-    assert self.in_class
-    self.visibility = VISIBILITY_PUBLIC
-
-  def handle_protected(self):
-    assert self.in_class
-    self.visibility = VISIBILITY_PROTECTED
-
-  def handle_private(self):
-    assert self.in_class
-    self.visibility = VISIBILITY_PRIVATE
-
-  def handle_friend(self):
-    tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
-    assert tokens
-    t0 = tokens[0]
-    return Friend(t0.start, t0.end, tokens, self.namespace_stack)
-
-  def handle_static_cast(self):
-    pass
-
-  def handle_const_cast(self):
-    pass
-
-  def handle_dynamic_cast(self):
-    pass
-
-  def handle_reinterpret_cast(self):
-    pass
-
-  def handle_new(self):
-    pass
-
-  def handle_delete(self):
-    tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
-    assert tokens
-    return Delete(tokens[0].start, tokens[0].end, tokens)
-
-  def handle_typedef(self):
-    token = self._GetNextToken()
-    if (token.token_type == tokenize.NAME and
-            keywords.IsKeyword(token.name)):
-      # Token must be struct/enum/union/class.
-      method = getattr(self, 'handle_' + token.name)
-      self._handling_typedef = True
-      tokens = [method()]
-      self._handling_typedef = False
-    else:
-      tokens = [token]
-
-    # Get the remainder of the typedef up to the semi-colon.
-    tokens.extend(self._GetTokensUpTo(tokenize.SYNTAX, ';'))
-
-    # TODO(nnorwitz): clean all this up.
-    assert tokens
-    name = tokens.pop()
-    indices = name
-    if tokens:
-      indices = tokens[0]
-    if not indices:
-      indices = token
-    if name.name == ')':
-      # HACK(nnorwitz): Handle pointers to functions "properly".
-      if (len(tokens) >= 4 and
-              tokens[1].name == '(' and tokens[2].name == '*'):
-        tokens.append(name)
-        name = tokens[3]
-    elif name.name == ']':
-      # HACK(nnorwitz): Handle arrays properly.
-      if len(tokens) >= 2:
-        tokens.append(name)
-        name = tokens[1]
-    new_type = tokens
-    if tokens and isinstance(tokens[0], tokenize.Token):
-      new_type = self.converter.ToType(tokens)[0]
-    return Typedef(indices.start, indices.end, name.name,
-                   new_type, self.namespace_stack)
-
-  def handle_typeid(self):
-    pass  # Not needed yet.
-
-  def handle_typename(self):
-    pass  # Not needed yet.
-
-  def _GetTemplatedTypes(self):
-    result = collections.OrderedDict()
-    tokens = list(self._GetMatchingChar('<', '>'))
-    len_tokens = len(tokens) - 1    # Ignore trailing '>'.
-    i = 0
-    while i < len_tokens:
-      key = tokens[i].name
-      i += 1
-      if keywords.IsKeyword(key) or key == ',':
-        continue
-      type_name = default = None
-      if i < len_tokens:
-        i += 1
-        if tokens[i-1].name == '=':
-          assert i < len_tokens, '%s %s' % (i, tokens)
-          default, unused_next_token = self.GetName(tokens[i:])
-          i += len(default)
-        else:
-          if tokens[i-1].name != ',':
-            # We got something like: Type variable.
-            # Re-adjust the key (variable) and type_name (Type).
-            key = tokens[i-1].name
-            type_name = tokens[i-2]
-
-      result[key] = (type_name, default)
-    return result
-
-  def handle_template(self):
-    token = self._GetNextToken()
-    assert token.token_type == tokenize.SYNTAX, token
-    assert token.name == '<', token
-    templated_types = self._GetTemplatedTypes()
-    # TODO(nnorwitz): for now, just ignore the template params.
-    token = self._GetNextToken()
-    if token.token_type == tokenize.NAME:
-      if token.name == 'class':
-        return self._GetClass(Class, VISIBILITY_PRIVATE, templated_types)
-      elif token.name == 'struct':
-        return self._GetClass(Struct, VISIBILITY_PUBLIC, templated_types)
-      elif token.name == 'friend':
-        return self.handle_friend()
-    self._AddBackToken(token)
-    tokens, last = self._GetVarTokensUpTo(tokenize.SYNTAX, '(', ';')
-    tokens.append(last)
-    self._AddBackTokens(tokens)
-    if last.name == '(':
-      return self.GetMethod(FUNCTION_NONE, templated_types)
-    # Must be a variable definition.
-    return None
-
-  def handle_true(self):
-    pass  # Nothing to do.
-
-  def handle_false(self):
-    pass  # Nothing to do.
-
-  def handle_asm(self):
-    pass  # Not needed yet.
-
-  def handle_class(self):
-    return self._GetClass(Class, VISIBILITY_PRIVATE, None)
-
-  def _GetBases(self):
-    # Get base classes.
-    bases = []
-    while 1:
-      token = self._GetNextToken()
-      assert token.token_type == tokenize.NAME, token
-      # TODO(nnorwitz): store kind of inheritance...maybe.
-      if token.name not in ('public', 'protected', 'private'):
-        # If inheritance type is not specified, it is private.
-        # Just put the token back so we can form a name.
-        # TODO(nnorwitz): it would be good to warn about this.
-        self._AddBackToken(token)
-      else:
-        # Check for virtual inheritance.
-        token = self._GetNextToken()
-        if token.name != 'virtual':
-          self._AddBackToken(token)
-        else:
-          # TODO(nnorwitz): store that we got virtual for this base.
-          pass
-      base, next_token = self.GetName()
-      bases_ast = self.converter.ToType(base)
-      assert len(bases_ast) == 1, bases_ast
-      bases.append(bases_ast[0])
-      assert next_token.token_type == tokenize.SYNTAX, next_token
-      if next_token.name == '{':
-        token = next_token
-        break
-      # Support multiple inheritance.
-      assert next_token.name == ',', next_token
-    return bases, token
-
-  def _GetClass(self, class_type, visibility, templated_types):
-    class_name = None
-    class_token = self._GetNextToken()
-    if class_token.token_type != tokenize.NAME:
-      assert class_token.token_type == tokenize.SYNTAX, class_token
-      token = class_token
-    else:
-      # Skip any macro (e.g. storage class specifiers) after the
-      # 'class' keyword.
-      next_token = self._GetNextToken()
-      if next_token.token_type == tokenize.NAME:
-        self._AddBackToken(next_token)
-      else:
-        self._AddBackTokens([class_token, next_token])
-      name_tokens, token = self.GetName()
-      class_name = ''.join([t.name for t in name_tokens])
-    bases = None
-    if token.token_type == tokenize.SYNTAX:
-      if token.name == ';':
-        # Forward declaration.
-        return class_type(class_token.start, class_token.end,
-                          class_name, None, templated_types, None,
-                          self.namespace_stack)
-      if token.name in '*&':
-        # Inline forward declaration.  Could be method or data.
-        name_token = self._GetNextToken()
-        next_token = self._GetNextToken()
-        if next_token.name == ';':
-          # Handle data
-          modifiers = ['class']
-          return self._CreateVariable(class_token, name_token.name,
-                                      class_name,
-                                      modifiers, token.name, None)
-        else:
-          # Assume this is a method.
-          tokens = (class_token, token, name_token, next_token)
-          self._AddBackTokens(tokens)
-          return self.GetMethod(FUNCTION_NONE, None)
-      if token.name == ':':
-        bases, token = self._GetBases()
-
-    body = None
-    if token.token_type == tokenize.SYNTAX and token.name == '{':
-      assert token.token_type == tokenize.SYNTAX, token
-      assert token.name == '{', token
-
-      ast = AstBuilder(self.GetScope(), self.filename, class_name,
-                       visibility, self.namespace_stack)
-      body = list(ast.Generate())
-
-      if not self._handling_typedef:
-        token = self._GetNextToken()
-        if token.token_type != tokenize.NAME:
-          assert token.token_type == tokenize.SYNTAX, token
-          assert token.name == ';', token
-        else:
-          new_class = class_type(class_token.start, class_token.end,
-                                 class_name, bases, None,
-                                 body, self.namespace_stack)
-
-          modifiers = []
-          return self._CreateVariable(class_token,
-                                      token.name, new_class,
-                                      modifiers, token.name, None)
-    else:
-      if not self._handling_typedef:
-        self.HandleError('non-typedef token', token)
-      self._AddBackToken(token)
-
-    return class_type(class_token.start, class_token.end, class_name,
-                      bases, templated_types, body, self.namespace_stack)
-
-  def handle_namespace(self):
-    # Support anonymous namespaces.
-    name = None
-    name_tokens, token = self.GetName()
-    if name_tokens:
-      name = ''.join([t.name for t in name_tokens])
-    self.namespace_stack.append(name)
-    assert token.token_type == tokenize.SYNTAX, token
-    # Create an internal token that denotes when the namespace is complete.
-    internal_token = tokenize.Token(_INTERNAL_TOKEN, _NAMESPACE_POP,
-                                    None, None)
-    internal_token.whence = token.whence
-    if token.name == '=':
-      # TODO(nnorwitz): handle aliasing namespaces.
-      name, next_token = self.GetName()
-      assert next_token.name == ';', next_token
-      self._AddBackToken(internal_token)
-    else:
-      assert token.name == '{', token
-      tokens = list(self.GetScope())
-      # Replace the trailing } with the internal namespace pop token.
-      tokens[-1] = internal_token
-      # Handle namespace with nothing in it.
-      self._AddBackTokens(tokens)
-    return None
-
-  def handle_using(self):
-    tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
-    assert tokens
-    return Using(tokens[0].start, tokens[0].end, tokens)
-
-  def handle_explicit(self):
-    assert self.in_class
-    # Nothing much to do.
-    # TODO(nnorwitz): maybe verify the method name == class name.
-    # This must be a ctor.
-    return self.GetMethod(FUNCTION_CTOR, None)
-
-  def handle_this(self):
-    pass  # Nothing to do.
-
-  def handle_operator(self):
-    # Pull off the next token(s?) and make that part of the method name.
-    pass
-
-  def handle_sizeof(self):
-    pass
-
-  def handle_case(self):
-    pass
-
-  def handle_switch(self):
-    pass
-
-  def handle_default(self):
-    token = self._GetNextToken()
-    assert token.token_type == tokenize.SYNTAX
-    assert token.name == ':'
-
-  def handle_if(self):
-    pass
-
-  def handle_else(self):
-    pass
-
-  def handle_return(self):
-    tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
-    if not tokens:
-      return Return(self.current_token.start, self.current_token.end, None)
-    return Return(tokens[0].start, tokens[0].end, tokens)
-
-  def handle_goto(self):
-    tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
-    assert len(tokens) == 1, str(tokens)
-    return Goto(tokens[0].start, tokens[0].end, tokens[0].name)
-
-  def handle_try(self):
-    pass  # Not needed yet.
-
-  def handle_catch(self):
-    pass  # Not needed yet.
-
-  def handle_throw(self):
-    pass  # Not needed yet.
-
-  def handle_while(self):
-    pass
-
-  def handle_do(self):
-    pass
-
-  def handle_for(self):
-    pass
-
-  def handle_break(self):
-    self._IgnoreUpTo(tokenize.SYNTAX, ';')
-
-  def handle_continue(self):
-    self._IgnoreUpTo(tokenize.SYNTAX, ';')
-
-
-def BuilderFromSource(source, filename):
-  """Utility method that returns an AstBuilder from source code.
-
-    Args:
-      source: 'C++ source code'
-      filename: 'file1'
-
-    Returns:
-      AstBuilder
-    """
-  return AstBuilder(tokenize.GetTokens(source), filename)
-
-
-def PrintIndentifiers(filename, should_print):
-  """Prints all identifiers for a C++ source file.
-
-    Args:
-      filename: 'file1'
-      should_print: predicate with signature: bool Function(token)
-    """
-  source = utils.ReadFile(filename, False)
-  if source is None:
-    sys.stderr.write('Unable to find: %s\n' % filename)
-    return
-
-  #print('Processing %s' % actual_filename)
-  builder = BuilderFromSource(source, filename)
-  try:
-    for node in builder.Generate():
-      if should_print(node):
-        print(node.name)
-  except KeyboardInterrupt:
-    return
-  except:
-    pass
-
-
-def PrintAllIndentifiers(filenames, should_print):
-  """Prints all identifiers for each C++ source file in filenames.
-
-    Args:
-      filenames: ['file1', 'file2', ...]
-      should_print: predicate with signature: bool Function(token)
-    """
-  for path in filenames:
-    PrintIndentifiers(path, should_print)
-
-
-def main(argv):
-  for filename in argv[1:]:
-    source = utils.ReadFile(filename)
-    if source is None:
-      continue
-
-    print('Processing %s' % filename)
-    builder = BuilderFromSource(source, filename)
-    try:
-      entire_ast = filter(None, builder.Generate())
-    except KeyboardInterrupt:
-      return
-    except:
-      # Already printed a warning, print the traceback and continue.
-      traceback.print_exc()
-    else:
-      if utils.DEBUG:
-        for ast in entire_ast:
-          print(ast)
-
-
-if __name__ == '__main__':
-  main(sys.argv)
diff --git a/googlemock/scripts/generator/cpp/gmock_class.py b/googlemock/scripts/generator/cpp/gmock_class.py
deleted file mode 100755 (executable)
index 3e21022..0000000
+++ /dev/null
@@ -1,247 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2008 Google Inc.  All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Generate Google Mock classes from base classes.
-
-This program will read in a C++ source file and output the Google Mock
-classes for the specified classes.  If no class is specified, all
-classes in the source file are emitted.
-
-Usage:
-  gmock_class.py header-file.h [ClassName]...
-
-Output is sent to stdout.
-"""
-
-import os
-import re
-import sys
-
-from cpp import ast
-from cpp import utils
-
-# Preserve compatibility with Python 2.3.
-try:
-  _dummy = set
-except NameError:
-  import sets
-
-  set = sets.Set
-
-_VERSION = (1, 0, 1)  # The version of this script.
-# How many spaces to indent.  Can set me with the INDENT environment variable.
-_INDENT = 2
-
-
-def _RenderType(ast_type):
-  """Renders the potentially recursively templated type into a string.
-
-  Args:
-    ast_type: The AST of the type.
-
-  Returns:
-    Rendered string of the type.
-  """
-  # Add modifiers like 'const'.
-  modifiers = ''
-  if ast_type.modifiers:
-    modifiers = ' '.join(ast_type.modifiers) + ' '
-  return_type = modifiers + ast_type.name
-  if ast_type.templated_types:
-    # Collect template args.
-    template_args = []
-    for arg in ast_type.templated_types:
-      rendered_arg = _RenderType(arg)
-      template_args.append(rendered_arg)
-    return_type += '<' + ', '.join(template_args) + '>'
-  if ast_type.pointer:
-    return_type += '*'
-  if ast_type.reference:
-    return_type += '&'
-  return return_type
-
-
-def _GenerateArg(source):
-  """Strips out comments, default arguments, and redundant spaces from a single argument.
-
-  Args:
-    source: A string for a single argument.
-
-  Returns:
-    Rendered string of the argument.
-  """
-  # Remove end of line comments before eliminating newlines.
-  arg = re.sub(r'//.*', '', source)
-
-  # Remove c-style comments.
-  arg = re.sub(r'/\*.*\*/', '', arg)
-
-  # Remove default arguments.
-  arg = re.sub(r'=.*', '', arg)
-
-  # Collapse spaces and newlines into a single space.
-  arg = re.sub(r'\s+', ' ', arg)
-  return arg.strip()
-
-
-def _EscapeForMacro(s):
-  """Escapes a string for use as an argument to a C++ macro."""
-  paren_count = 0
-  for c in s:
-    if c == '(':
-      paren_count += 1
-    elif c == ')':
-      paren_count -= 1
-    elif c == ',' and paren_count == 0:
-      return '(' + s + ')'
-  return s
-
-
-def _GenerateMethods(output_lines, source, class_node):
-  function_type = (
-      ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL | ast.FUNCTION_OVERRIDE)
-  ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR
-  indent = ' ' * _INDENT
-
-  for node in class_node.body:
-    # We only care about virtual functions.
-    if (isinstance(node, ast.Function) and node.modifiers & function_type and
-        not node.modifiers & ctor_or_dtor):
-      # Pick out all the elements we need from the original function.
-      modifiers = 'override'
-      if node.modifiers & ast.FUNCTION_CONST:
-        modifiers = 'const, ' + modifiers
-
-      return_type = 'void'
-      if node.return_type:
-        return_type = _EscapeForMacro(_RenderType(node.return_type))
-
-      args = []
-      for p in node.parameters:
-        arg = _GenerateArg(source[p.start:p.end])
-        if arg != 'void':
-          args.append(_EscapeForMacro(arg))
-
-      # Create the mock method definition.
-      output_lines.extend([
-          '%sMOCK_METHOD(%s, %s, (%s), (%s));' %
-          (indent, return_type, node.name, ', '.join(args), modifiers)
-      ])
-
-
-def _GenerateMocks(filename, source, ast_list, desired_class_names):
-  processed_class_names = set()
-  lines = []
-  for node in ast_list:
-    if (isinstance(node, ast.Class) and node.body and
-        # desired_class_names being None means that all classes are selected.
-        (not desired_class_names or node.name in desired_class_names)):
-      class_name = node.name
-      parent_name = class_name
-      processed_class_names.add(class_name)
-      class_node = node
-      # Add namespace before the class.
-      if class_node.namespace:
-        lines.extend(['namespace %s {' % n for n in class_node.namespace])  # }
-        lines.append('')
-
-      # Add template args for templated classes.
-      if class_node.templated_types:
-        # TODO(paulchang): Handle non-type template arguments (e.g.
-        # template<typename T, int N>).
-
-        # class_node.templated_types is an OrderedDict from strings to a tuples.
-        # The key is the name of the template, and the value is
-        # (type_name, default). Both type_name and default could be None.
-        template_args = class_node.templated_types.keys()
-        template_decls = ['typename ' + arg for arg in template_args]
-        lines.append('template <' + ', '.join(template_decls) + '>')
-        parent_name += '<' + ', '.join(template_args) + '>'
-
-      # Add the class prolog.
-      lines.append('class Mock%s : public %s {'  # }
-                   % (class_name, parent_name))
-      lines.append('%spublic:' % (' ' * (_INDENT // 2)))
-
-      # Add all the methods.
-      _GenerateMethods(lines, source, class_node)
-
-      # Close the class.
-      if lines:
-        # If there are no virtual methods, no need for a public label.
-        if len(lines) == 2:
-          del lines[-1]
-
-        # Only close the class if there really is a class.
-        lines.append('};')
-        lines.append('')  # Add an extra newline.
-
-      # Close the namespace.
-      if class_node.namespace:
-        for i in range(len(class_node.namespace) - 1, -1, -1):
-          lines.append('}  // namespace %s' % class_node.namespace[i])
-        lines.append('')  # Add an extra newline.
-
-  if desired_class_names:
-    missing_class_name_list = list(desired_class_names - processed_class_names)
-    if missing_class_name_list:
-      missing_class_name_list.sort()
-      sys.stderr.write('Class(es) not found in %s: %s\n' %
-                       (filename, ', '.join(missing_class_name_list)))
-  elif not processed_class_names:
-    sys.stderr.write('No class found in %s\n' % filename)
-
-  return lines
-
-
-def main(argv=sys.argv):
-  if len(argv) < 2:
-    sys.stderr.write('Google Mock Class Generator v%s\n\n' %
-                     '.'.join(map(str, _VERSION)))
-    sys.stderr.write(__doc__)
-    return 1
-
-  global _INDENT
-  try:
-    _INDENT = int(os.environ['INDENT'])
-  except KeyError:
-    pass
-  except:
-    sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT'))
-
-  filename = argv[1]
-  desired_class_names = None  # None means all classes in the source file.
-  if len(argv) >= 3:
-    desired_class_names = set(argv[2:])
-  source = utils.ReadFile(filename)
-  if source is None:
-    return 1
-
-  builder = ast.BuilderFromSource(source, filename)
-  try:
-    entire_ast = filter(None, builder.Generate())
-  except KeyboardInterrupt:
-    return
-  except:
-    # An error message was already printed since we couldn't parse.
-    sys.exit(1)
-  else:
-    lines = _GenerateMocks(filename, source, entire_ast, desired_class_names)
-    sys.stdout.write('\n'.join(lines))
-
-
-if __name__ == '__main__':
-  main(sys.argv)
diff --git a/googlemock/scripts/generator/cpp/gmock_class_test.py b/googlemock/scripts/generator/cpp/gmock_class_test.py
deleted file mode 100755 (executable)
index eff475f..0000000
+++ /dev/null
@@ -1,570 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2009 Neal Norwitz All Rights Reserved.
-# Portions Copyright 2009 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Tests for gmock.scripts.generator.cpp.gmock_class."""
-
-import os
-import sys
-import unittest
-
-# Allow the cpp imports below to work when run as a standalone script.
-sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
-
-from cpp import ast
-from cpp import gmock_class
-
-
-class TestCase(unittest.TestCase):
-  """Helper class that adds assert methods."""
-
-  @staticmethod
-  def StripLeadingWhitespace(lines):
-    """Strip leading whitespace in each line in 'lines'."""
-    return '\n'.join([s.lstrip() for s in lines.split('\n')])
-
-  def assertEqualIgnoreLeadingWhitespace(self, expected_lines, lines):
-    """Specialized assert that ignores the indent level."""
-    self.assertEqual(expected_lines, self.StripLeadingWhitespace(lines))
-
-
-class GenerateMethodsTest(TestCase):
-
-  @staticmethod
-  def GenerateMethodSource(cpp_source):
-    """Convert C++ source to Google Mock output source lines."""
-    method_source_lines = []
-    # <test> is a pseudo-filename, it is not read or written.
-    builder = ast.BuilderFromSource(cpp_source, '<test>')
-    ast_list = list(builder.Generate())
-    gmock_class._GenerateMethods(method_source_lines, cpp_source, ast_list[0])
-    return '\n'.join(method_source_lines)
-
-  def testSimpleMethod(self):
-    source = """
-class Foo {
- public:
-  virtual int Bar();
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(int, Bar, (), (override));',
-        self.GenerateMethodSource(source))
-
-  def testSimpleConstructorsAndDestructor(self):
-    source = """
-class Foo {
- public:
-  Foo();
-  Foo(int x);
-  Foo(const Foo& f);
-  Foo(Foo&& f);
-  ~Foo();
-  virtual int Bar() = 0;
-};
-"""
-    # The constructors and destructor should be ignored.
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(int, Bar, (), (override));',
-        self.GenerateMethodSource(source))
-
-  def testVirtualDestructor(self):
-    source = """
-class Foo {
- public:
-  virtual ~Foo();
-  virtual int Bar() = 0;
-};
-"""
-    # The destructor should be ignored.
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(int, Bar, (), (override));',
-        self.GenerateMethodSource(source))
-
-  def testExplicitlyDefaultedConstructorsAndDestructor(self):
-    source = """
-class Foo {
- public:
-  Foo() = default;
-  Foo(const Foo& f) = default;
-  Foo(Foo&& f) = default;
-  ~Foo() = default;
-  virtual int Bar() = 0;
-};
-"""
-    # The constructors and destructor should be ignored.
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(int, Bar, (), (override));',
-        self.GenerateMethodSource(source))
-
-  def testExplicitlyDeletedConstructorsAndDestructor(self):
-    source = """
-class Foo {
- public:
-  Foo() = delete;
-  Foo(const Foo& f) = delete;
-  Foo(Foo&& f) = delete;
-  ~Foo() = delete;
-  virtual int Bar() = 0;
-};
-"""
-    # The constructors and destructor should be ignored.
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(int, Bar, (), (override));',
-        self.GenerateMethodSource(source))
-
-  def testSimpleOverrideMethod(self):
-    source = """
-class Foo {
- public:
-  int Bar() override;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(int, Bar, (), (override));',
-        self.GenerateMethodSource(source))
-
-  def testSimpleConstMethod(self):
-    source = """
-class Foo {
- public:
-  virtual void Bar(bool flag) const;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(void, Bar, (bool flag), (const, override));',
-        self.GenerateMethodSource(source))
-
-  def testExplicitVoid(self):
-    source = """
-class Foo {
- public:
-  virtual int Bar(void);
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(int, Bar, (), (override));',
-        self.GenerateMethodSource(source))
-
-  def testStrangeNewlineInParameter(self):
-    source = """
-class Foo {
- public:
-  virtual void Bar(int
-a) = 0;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(void, Bar, (int a), (override));',
-        self.GenerateMethodSource(source))
-
-  def testDefaultParameters(self):
-    source = """
-class Foo {
- public:
-  virtual void Bar(int a, char c = 'x') = 0;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(void, Bar, (int a, char c), (override));',
-        self.GenerateMethodSource(source))
-
-  def testMultipleDefaultParameters(self):
-    source = """
-class Foo {
- public:
-  virtual void Bar(
-        int a = 42, 
-        char c = 'x', 
-        const int* const p = nullptr, 
-        const std::string& s = "42",
-        char tab[] = {'4','2'},
-        int const *& rp = aDefaultPointer) = 0;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(void, Bar, '
-        '(int a, char c, const int* const p, const std::string& s, char tab[], int const *& rp), '
-        '(override));', self.GenerateMethodSource(source))
-
-  def testMultipleSingleLineDefaultParameters(self):
-    source = """
-class Foo {
- public:
-  virtual void Bar(int a = 42, int b = 43, int c = 44) = 0;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(void, Bar, (int a, int b, int c), (override));',
-        self.GenerateMethodSource(source))
-
-  def testConstDefaultParameter(self):
-    source = """
-class Test {
- public:
-  virtual bool Bar(const int test_arg = 42) = 0;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(bool, Bar, (const int test_arg), (override));',
-        self.GenerateMethodSource(source))
-
-  def testConstRefDefaultParameter(self):
-    source = """
-class Test {
- public:
-  virtual bool Bar(const std::string& test_arg = "42" ) = 0;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(bool, Bar, (const std::string& test_arg), (override));',
-        self.GenerateMethodSource(source))
-
-  def testRemovesCommentsWhenDefaultsArePresent(self):
-    source = """
-class Foo {
- public:
-  virtual void Bar(int a = 42 /* a comment */,
-                   char /* other comment */ c= 'x') = 0;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(void, Bar, (int a, char c), (override));',
-        self.GenerateMethodSource(source))
-
-  def testDoubleSlashCommentsInParameterListAreRemoved(self):
-    source = """
-class Foo {
- public:
-  virtual void Bar(int a,  // inline comments should be elided.
-                   int b   // inline comments should be elided.
-                   ) const = 0;
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(void, Bar, (int a, int b), (const, override));',
-        self.GenerateMethodSource(source))
-
-  def testCStyleCommentsInParameterListAreNotRemoved(self):
-    # NOTE(nnorwitz): I'm not sure if it's the best behavior to keep these
-    # comments.  Also note that C style comments after the last parameter
-    # are still elided.
-    source = """
-class Foo {
- public:
-  virtual const string& Bar(int /* keeper */, int b);
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(const string&, Bar, (int, int b), (override));',
-        self.GenerateMethodSource(source))
-
-  def testArgsOfTemplateTypes(self):
-    source = """
-class Foo {
- public:
-  virtual int Bar(const vector<int>& v, map<int, string>* output);
-};"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(int, Bar, (const vector<int>& v, (map<int, string>* output)), (override));',
-        self.GenerateMethodSource(source))
-
-  def testReturnTypeWithOneTemplateArg(self):
-    source = """
-class Foo {
- public:
-  virtual vector<int>* Bar(int n);
-};"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(vector<int>*, Bar, (int n), (override));',
-        self.GenerateMethodSource(source))
-
-  def testReturnTypeWithManyTemplateArgs(self):
-    source = """
-class Foo {
- public:
-  virtual map<int, string> Bar();
-};"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD((map<int, string>), Bar, (), (override));',
-        self.GenerateMethodSource(source))
-
-  def testSimpleMethodInTemplatedClass(self):
-    source = """
-template<class T>
-class Foo {
- public:
-  virtual int Bar();
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(int, Bar, (), (override));',
-        self.GenerateMethodSource(source))
-
-  def testPointerArgWithoutNames(self):
-    source = """
-class Foo {
-  virtual int Bar(C*);
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(int, Bar, (C*), (override));',
-        self.GenerateMethodSource(source))
-
-  def testReferenceArgWithoutNames(self):
-    source = """
-class Foo {
-  virtual int Bar(C&);
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(int, Bar, (C&), (override));',
-        self.GenerateMethodSource(source))
-
-  def testArrayArgWithoutNames(self):
-    source = """
-class Foo {
-  virtual int Bar(C[]);
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(
-        'MOCK_METHOD(int, Bar, (C[]), (override));',
-        self.GenerateMethodSource(source))
-
-
-class GenerateMocksTest(TestCase):
-
-  @staticmethod
-  def GenerateMocks(cpp_source):
-    """Convert C++ source to complete Google Mock output source."""
-    # <test> is a pseudo-filename, it is not read or written.
-    filename = '<test>'
-    builder = ast.BuilderFromSource(cpp_source, filename)
-    ast_list = list(builder.Generate())
-    lines = gmock_class._GenerateMocks(filename, cpp_source, ast_list, None)
-    return '\n'.join(lines)
-
-  def testNamespaces(self):
-    source = """
-namespace Foo {
-namespace Bar { class Forward; }
-namespace Baz::Qux {
-
-class Test {
- public:
-  virtual void Foo();
-};
-
-}  // namespace Baz::Qux
-}  // namespace Foo
-"""
-    expected = """\
-namespace Foo {
-namespace Baz::Qux {
-
-class MockTest : public Test {
-public:
-MOCK_METHOD(void, Foo, (), (override));
-};
-
-}  // namespace Baz::Qux
-}  // namespace Foo
-"""
-    self.assertEqualIgnoreLeadingWhitespace(expected,
-                                            self.GenerateMocks(source))
-
-  def testClassWithStorageSpecifierMacro(self):
-    source = """
-class STORAGE_SPECIFIER Test {
- public:
-  virtual void Foo();
-};
-"""
-    expected = """\
-class MockTest : public Test {
-public:
-MOCK_METHOD(void, Foo, (), (override));
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(expected,
-                                            self.GenerateMocks(source))
-
-  def testTemplatedForwardDeclaration(self):
-    source = """
-template <class T> class Forward;  // Forward declaration should be ignored.
-class Test {
- public:
-  virtual void Foo();
-};
-"""
-    expected = """\
-class MockTest : public Test {
-public:
-MOCK_METHOD(void, Foo, (), (override));
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(expected,
-                                            self.GenerateMocks(source))
-
-  def testTemplatedClass(self):
-    source = """
-template <typename S, typename T>
-class Test {
- public:
-  virtual void Foo();
-};
-"""
-    expected = """\
-template <typename S, typename T>
-class MockTest : public Test<S, T> {
-public:
-MOCK_METHOD(void, Foo, (), (override));
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(expected,
-                                            self.GenerateMocks(source))
-
-  def testTemplateInATemplateTypedef(self):
-    source = """
-class Test {
- public:
-  typedef std::vector<std::list<int>> FooType;
-  virtual void Bar(const FooType& test_arg);
-};
-"""
-    expected = """\
-class MockTest : public Test {
-public:
-MOCK_METHOD(void, Bar, (const FooType& test_arg), (override));
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(expected,
-                                            self.GenerateMocks(source))
-
-  def testTemplatedClassWithTemplatedArguments(self):
-    source = """
-template <typename S, typename T, typename U, typename V, typename W>
-class Test {
- public:
-  virtual U Foo(T some_arg);
-};
-"""
-    expected = """\
-template <typename S, typename T, typename U, typename V, typename W>
-class MockTest : public Test<S, T, U, V, W> {
-public:
-MOCK_METHOD(U, Foo, (T some_arg), (override));
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(expected,
-                                            self.GenerateMocks(source))
-
-  def testTemplateInATemplateTypedefWithComma(self):
-    source = """
-class Test {
- public:
-  typedef std::function<void(
-      const vector<std::list<int>>&, int> FooType;
-  virtual void Bar(const FooType& test_arg);
-};
-"""
-    expected = """\
-class MockTest : public Test {
-public:
-MOCK_METHOD(void, Bar, (const FooType& test_arg), (override));
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(expected,
-                                            self.GenerateMocks(source))
-
-  def testParenthesizedCommaInArg(self):
-    source = """
-class Test {
- public:
-   virtual void Bar(std::function<void(int, int)> f);
-};
-"""
-    expected = """\
-class MockTest : public Test {
-public:
-MOCK_METHOD(void, Bar, (std::function<void(int, int)> f), (override));
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(expected,
-                                            self.GenerateMocks(source))
-
-  def testEnumType(self):
-    source = """
-class Test {
- public:
-  enum Bar {
-    BAZ, QUX, QUUX, QUUUX
-  };
-  virtual void Foo();
-};
-"""
-    expected = """\
-class MockTest : public Test {
-public:
-MOCK_METHOD(void, Foo, (), (override));
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(expected,
-                                            self.GenerateMocks(source))
-
-  def testEnumClassType(self):
-    source = """
-class Test {
- public:
-  enum class Bar {
-    BAZ, QUX, QUUX, QUUUX
-  };
-  virtual void Foo();
-};
-"""
-    expected = """\
-class MockTest : public Test {
-public:
-MOCK_METHOD(void, Foo, (), (override));
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(expected,
-                                            self.GenerateMocks(source))
-
-  def testStdFunction(self):
-    source = """
-class Test {
- public:
-  Test(std::function<int(std::string)> foo) : foo_(foo) {}
-
-  virtual std::function<int(std::string)> foo();
-
- private:
-  std::function<int(std::string)> foo_;
-};
-"""
-    expected = """\
-class MockTest : public Test {
-public:
-MOCK_METHOD(std::function<int (std::string)>, foo, (), (override));
-};
-"""
-    self.assertEqualIgnoreLeadingWhitespace(expected,
-                                            self.GenerateMocks(source))
-
-
-if __name__ == '__main__':
-  unittest.main()
diff --git a/googlemock/scripts/generator/cpp/keywords.py b/googlemock/scripts/generator/cpp/keywords.py
deleted file mode 100755 (executable)
index e428271..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2007 Neal Norwitz
-# Portions Copyright 2007 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""C++ keywords and helper utilities for determining keywords."""
-
-try:
-    # Python 3.x
-    import builtins
-except ImportError:
-    # Python 2.x
-    import __builtin__ as builtins
-
-
-if not hasattr(builtins, 'set'):
-    # Nominal support for Python 2.3.
-    from sets import Set as set
-
-
-TYPES = set('bool char int long short double float void wchar_t unsigned signed'.split())
-TYPE_MODIFIERS = set('auto register const inline extern static virtual volatile mutable'.split())
-ACCESS = set('public protected private friend'.split())
-
-CASTS = set('static_cast const_cast dynamic_cast reinterpret_cast'.split())
-
-OTHERS = set('true false asm class namespace using explicit this operator sizeof'.split())
-OTHER_TYPES = set('new delete typedef struct union enum typeid typename template'.split())
-
-CONTROL = set('case switch default if else return goto'.split())
-EXCEPTION = set('try catch throw'.split())
-LOOP = set('while do for break continue'.split())
-
-ALL = TYPES | TYPE_MODIFIERS | ACCESS | CASTS | OTHERS | OTHER_TYPES | CONTROL | EXCEPTION | LOOP
-
-
-def IsKeyword(token):
-    return token in ALL
-
-def IsBuiltinType(token):
-    if token in ('virtual', 'inline'):
-        # These only apply to methods, they can't be types by themselves.
-        return False
-    return token in TYPES or token in TYPE_MODIFIERS
diff --git a/googlemock/scripts/generator/cpp/tokenize.py b/googlemock/scripts/generator/cpp/tokenize.py
deleted file mode 100755 (executable)
index a75edcb..0000000
+++ /dev/null
@@ -1,284 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2007 Neal Norwitz
-# Portions Copyright 2007 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Tokenize C++ source code."""
-
-try:
-    # Python 3.x
-    import builtins
-except ImportError:
-    # Python 2.x
-    import __builtin__ as builtins
-
-
-import sys
-
-from cpp import utils
-
-
-if not hasattr(builtins, 'set'):
-    # Nominal support for Python 2.3.
-    from sets import Set as set
-
-
-# Add $ as a valid identifier char since so much code uses it.
-_letters = 'abcdefghijklmnopqrstuvwxyz'
-VALID_IDENTIFIER_CHARS = set(_letters + _letters.upper() + '_0123456789$')
-HEX_DIGITS = set('0123456789abcdefABCDEF')
-INT_OR_FLOAT_DIGITS = set('01234567890eE-+')
-
-
-# C++0x string preffixes.
-_STR_PREFIXES = set(('R', 'u8', 'u8R', 'u', 'uR', 'U', 'UR', 'L', 'LR'))
-
-
-# Token types.
-UNKNOWN = 'UNKNOWN'
-SYNTAX = 'SYNTAX'
-CONSTANT = 'CONSTANT'
-NAME = 'NAME'
-PREPROCESSOR = 'PREPROCESSOR'
-
-# Where the token originated from.  This can be used for backtracking.
-# It is always set to WHENCE_STREAM in this code.
-WHENCE_STREAM, WHENCE_QUEUE = range(2)
-
-
-class Token(object):
-    """Data container to represent a C++ token.
-
-    Tokens can be identifiers, syntax char(s), constants, or
-    pre-processor directives.
-
-    start contains the index of the first char of the token in the source
-    end contains the index of the last char of the token in the source
-    """
-
-    def __init__(self, token_type, name, start, end):
-        self.token_type = token_type
-        self.name = name
-        self.start = start
-        self.end = end
-        self.whence = WHENCE_STREAM
-
-    def __str__(self):
-        if not utils.DEBUG:
-            return 'Token(%r)' % self.name
-        return 'Token(%r, %s, %s)' % (self.name, self.start, self.end)
-
-    __repr__ = __str__
-
-
-def _GetString(source, start, i):
-    i = source.find('"', i+1)
-    while source[i-1] == '\\':
-        # Count the trailing backslashes.
-        backslash_count = 1
-        j = i - 2
-        while source[j] == '\\':
-            backslash_count += 1
-            j -= 1
-        # When trailing backslashes are even, they escape each other.
-        if (backslash_count % 2) == 0:
-            break
-        i = source.find('"', i+1)
-    return i + 1
-
-
-def _GetChar(source, start, i):
-    # NOTE(nnorwitz): may not be quite correct, should be good enough.
-    i = source.find("'", i+1)
-    while source[i-1] == '\\':
-        # Need to special case '\\'.
-        if (i - 2) > start and source[i-2] == '\\':
-            break
-        i = source.find("'", i+1)
-    # Try to handle unterminated single quotes (in a #if 0 block).
-    if i < 0:
-        i = start
-    return i + 1
-
-
-def GetTokens(source):
-    """Returns a sequence of Tokens.
-
-    Args:
-      source: string of C++ source code.
-
-    Yields:
-      Token that represents the next token in the source.
-    """
-    # Cache various valid character sets for speed.
-    valid_identifier_chars = VALID_IDENTIFIER_CHARS
-    hex_digits = HEX_DIGITS
-    int_or_float_digits = INT_OR_FLOAT_DIGITS
-    int_or_float_digits2 = int_or_float_digits | set('.')
-
-    # Only ignore errors while in a #if 0 block.
-    ignore_errors = False
-    count_ifs = 0
-
-    i = 0
-    end = len(source)
-    while i < end:
-        # Skip whitespace.
-        while i < end and source[i].isspace():
-            i += 1
-        if i >= end:
-            return
-
-        token_type = UNKNOWN
-        start = i
-        c = source[i]
-        if c.isalpha() or c == '_':              # Find a string token.
-            token_type = NAME
-            while source[i] in valid_identifier_chars:
-                i += 1
-            # String and character constants can look like a name if
-            # they are something like L"".
-            if (source[i] == "'" and (i - start) == 1 and
-                source[start:i] in 'uUL'):
-                # u, U, and L are valid C++0x character preffixes.
-                token_type = CONSTANT
-                i = _GetChar(source, start, i)
-            elif source[i] == "'" and source[start:i] in _STR_PREFIXES:
-                token_type = CONSTANT
-                i = _GetString(source, start, i)
-        elif c == '/' and source[i+1] == '/':    # Find // comments.
-            i = source.find('\n', i)
-            if i == -1:  # Handle EOF.
-                i = end
-            continue
-        elif c == '/' and source[i+1] == '*':    # Find /* comments. */
-            i = source.find('*/', i) + 2
-            continue
-        elif c in ':+-<>&|*=':                   # : or :: (plus other chars).
-            token_type = SYNTAX
-            i += 1
-            new_ch = source[i]
-            if new_ch == c and c != '>':         # Treat ">>" as two tokens.
-                i += 1
-            elif c == '-' and new_ch == '>':
-                i += 1
-            elif new_ch == '=':
-                i += 1
-        elif c in '()[]{}~!?^%;/.,':             # Handle single char tokens.
-            token_type = SYNTAX
-            i += 1
-            if c == '.' and source[i].isdigit():
-                token_type = CONSTANT
-                i += 1
-                while source[i] in int_or_float_digits:
-                    i += 1
-                # Handle float suffixes.
-                for suffix in ('l', 'f'):
-                    if suffix == source[i:i+1].lower():
-                        i += 1
-                        break
-        elif c.isdigit():                        # Find integer.
-            token_type = CONSTANT
-            if c == '0' and source[i+1] in 'xX':
-                # Handle hex digits.
-                i += 2
-                while source[i] in hex_digits:
-                    i += 1
-            else:
-                while source[i] in int_or_float_digits2:
-                    i += 1
-            # Handle integer (and float) suffixes.
-            for suffix in ('ull', 'll', 'ul', 'l', 'f', 'u'):
-                size = len(suffix)
-                if suffix == source[i:i+size].lower():
-                    i += size
-                    break
-        elif c == '"':                           # Find string.
-            token_type = CONSTANT
-            i = _GetString(source, start, i)
-        elif c == "'":                           # Find char.
-            token_type = CONSTANT
-            i = _GetChar(source, start, i)
-        elif c == '#':                           # Find pre-processor command.
-            token_type = PREPROCESSOR
-            got_if = source[i:i+3] == '#if' and source[i+3:i+4].isspace()
-            if got_if:
-                count_ifs += 1
-            elif source[i:i+6] == '#endif':
-                count_ifs -= 1
-                if count_ifs == 0:
-                    ignore_errors = False
-
-            # TODO(nnorwitz): handle preprocessor statements (\ continuations).
-            while 1:
-                i1 = source.find('\n', i)
-                i2 = source.find('//', i)
-                i3 = source.find('/*', i)
-                i4 = source.find('"', i)
-                # NOTE(nnorwitz): doesn't handle comments in #define macros.
-                # Get the first important symbol (newline, comment, EOF/end).
-                i = min([x for x in (i1, i2, i3, i4, end) if x != -1])
-
-                # Handle #include "dir//foo.h" properly.
-                if source[i] == '"':
-                    i = source.find('"', i+1) + 1
-                    assert i > 0
-                    continue
-                # Keep going if end of the line and the line ends with \.
-                if not (i == i1 and source[i-1] == '\\'):
-                    if got_if:
-                        condition = source[start+4:i].lstrip()
-                        if (condition.startswith('0') or
-                            condition.startswith('(0)')):
-                            ignore_errors = True
-                    break
-                i += 1
-        elif c == '\\':                          # Handle \ in code.
-            # This is different from the pre-processor \ handling.
-            i += 1
-            continue
-        elif ignore_errors:
-            # The tokenizer seems to be in pretty good shape.  This
-            # raise is conditionally disabled so that bogus code
-            # in an #if 0 block can be handled.  Since we will ignore
-            # it anyways, this is probably fine.  So disable the
-            # exception and  return the bogus char.
-            i += 1
-        else:
-            sys.stderr.write('Got invalid token in %s @ %d token:%s: %r\n' %
-                             ('?', i, c, source[i-10:i+10]))
-            raise RuntimeError('unexpected token')
-
-        if i <= 0:
-            print('Invalid index, exiting now.')
-            return
-        yield Token(token_type, source[start:i], start, i)
-
-
-if __name__ == '__main__':
-    def main(argv):
-        """Driver mostly for testing purposes."""
-        for filename in argv[1:]:
-            source = utils.ReadFile(filename)
-            if source is None:
-                continue
-
-            for token in GetTokens(source):
-                print('%-12s: %s' % (token.token_type, token.name))
-                # print('\r%6.2f%%' % (100.0 * index / token.end),)
-            sys.stdout.write('\n')
-
-
-    main(sys.argv)
diff --git a/googlemock/scripts/generator/cpp/utils.py b/googlemock/scripts/generator/cpp/utils.py
deleted file mode 100755 (executable)
index 6f5fc09..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2007 Neal Norwitz
-# Portions Copyright 2007 Google Inc.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Generic utilities for C++ parsing."""
-
-import sys
-
-# Set to True to see the start/end token indices.
-DEBUG = True
-
-
-def ReadFile(filename, print_error=True):
-    """Returns the contents of a file."""
-    try:
-        fp = open(filename)
-        try:
-            return fp.read()
-        finally:
-            fp.close()
-    except IOError:
-        if print_error:
-            print('Error reading %s: %s' % (filename, sys.exc_info()[1]))
-        return None
diff --git a/googlemock/scripts/generator/gmock_gen.py b/googlemock/scripts/generator/gmock_gen.py
deleted file mode 100755 (executable)
index 9d528a5..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2008 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Driver for starting up Google Mock class generator."""
-
-
-import os
-import sys
-
-if __name__ == '__main__':
-  # Add the directory of this script to the path so we can import gmock_class.
-  sys.path.append(os.path.dirname(__file__))
-
-  from cpp import gmock_class
-  # Fix the docstring in case they require the usage.
-  gmock_class.__doc__ = gmock_class.__doc__.replace('gmock_class.py', __file__)
-  gmock_class.main()
index 7463f4383233c315e128dc577a3c74cec23c8b34..92cde3484abf6bb52d1527cf8b1d4fa45ea2f4d7 100644 (file)
@@ -27,7 +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.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file implements cardinalities.
 #include "gmock/gmock-cardinalities.h"
 
 #include <limits.h>
+
 #include <ostream>  // NOLINT
 #include <sstream>
 #include <string>
+
 #include "gmock/internal/gmock-internal-utils.h"
 #include "gtest/gtest.h"
 
@@ -49,8 +50,7 @@ namespace {
 class BetweenCardinalityImpl : public CardinalityInterface {
  public:
   BetweenCardinalityImpl(int min, int max)
-      : min_(min >= 0 ? min : 0),
-        max_(max >= min_ ? max : min_) {
+      : min_(min >= 0 ? min : 0), max_(max >= min_ ? max : min_) {
     std::stringstream ss;
     if (min < 0) {
       ss << "The invocation lower bound must be >= 0, "
@@ -62,8 +62,7 @@ class BetweenCardinalityImpl : public CardinalityInterface {
       internal::Expect(false, __FILE__, __LINE__, ss.str());
     } else if (min > max) {
       ss << "The invocation upper bound (" << max
-         << ") must be >= the invocation lower bound (" << min
-         << ").";
+         << ") must be >= the invocation lower bound (" << min << ").";
       internal::Expect(false, __FILE__, __LINE__, ss.str());
     }
   }
@@ -87,7 +86,8 @@ class BetweenCardinalityImpl : public CardinalityInterface {
   const int min_;
   const int max_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl);
+  BetweenCardinalityImpl(const BetweenCardinalityImpl&) = delete;
+  BetweenCardinalityImpl& operator=(const BetweenCardinalityImpl&) = delete;
 };
 
 // Formats "n times" in a human-friendly way.
index e5b547981d14d47fa49132d49cd3e950ae0c30fd..0a74841f35bfdaaded84b5ff1c2072813167aa0b 100644 (file)
@@ -27,7 +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.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file defines some utilities useful for implementing Google
 #include "gmock/internal/gmock-internal-utils.h"
 
 #include <ctype.h>
+
+#include <array>
+#include <cctype>
+#include <cstdint>
+#include <cstring>
 #include <ostream>  // NOLINT
 #include <string>
+#include <vector>
+
 #include "gmock/gmock.h"
 #include "gmock/internal/gmock-port.h"
 #include "gtest/gtest.h"
@@ -48,21 +54,22 @@ namespace internal {
 
 // Joins a vector of strings as if they are fields of a tuple; returns
 // the joined string.
-GTEST_API_ std::string JoinAsTuple(const Strings& fields) {
-  switch (fields.size()) {
-    case 0:
-      return "";
-    case 1:
-      return fields[0];
-    default:
-      std::string result = "(" + fields[0];
-      for (size_t i = 1; i < fields.size(); i++) {
-        result += ", ";
-        result += fields[i];
-      }
-      result += ")";
-      return result;
+GTEST_API_ std::string JoinAsKeyValueTuple(
+    const std::vector<const char*>& names, const Strings& values) {
+  GTEST_CHECK_(names.size() == values.size());
+  if (values.empty()) {
+    return "";
   }
+  const auto build_one = [&](const size_t i) {
+    return std::string(names[i]) + ": " + values[i];
+  };
+  std::string result = "(" + build_one(0);
+  for (size_t i = 1; i < values.size(); i++) {
+    result += ", ";
+    result += build_one(i);
+  }
+  result += ")";
+  return result;
 }
 
 // Converts an identifier name to a space-separated list of lower-case
@@ -76,12 +83,11 @@ GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
     // We don't care about the current locale as the input is
     // guaranteed to be a valid C++ identifier name.
     const bool starts_new_word = IsUpper(*p) ||
-        (!IsAlpha(prev_char) && IsLower(*p)) ||
-        (!IsDigit(prev_char) && IsDigit(*p));
+                                 (!IsAlpha(prev_char) && IsLower(*p)) ||
+                                 (!IsDigit(prev_char) && IsDigit(*p));
 
     if (IsAlNum(*p)) {
-      if (starts_new_word && result != "")
-        result += ' ';
+      if (starts_new_word && result != "") result += ' ';
       result += ToLower(*p);
     }
   }
@@ -95,12 +101,9 @@ class GoogleTestFailureReporter : public FailureReporterInterface {
  public:
   void ReportFailure(FailureType type, const char* file, int line,
                      const std::string& message) override {
-    AssertHelper(type == kFatal ?
-                 TestPartResult::kFatalFailure :
-                 TestPartResult::kNonFatalFailure,
-                 file,
-                 line,
-                 message.c_str()) = Message();
+    AssertHelper(type == kFatal ? TestPartResult::kFatalFailure
+                                : TestPartResult::kNonFatalFailure,
+                 file, line, message.c_str()) = Message();
     if (type == kFatal) {
       posix::Abort();
     }
@@ -126,10 +129,10 @@ static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
 // Returns true if and only if a log with the given severity is visible
 // according to the --gmock_verbose flag.
 GTEST_API_ bool LogIsVisible(LogSeverity severity) {
-  if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
+  if (GMOCK_FLAG_GET(verbose) == kInfoVerbosity) {
     // Always show the log if --gmock_verbose=info.
     return true;
-  } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
+  } else if (GMOCK_FLAG_GET(verbose) == kErrorVerbosity) {
     // Always hide it if --gmock_verbose=error.
     return false;
   } else {
@@ -148,8 +151,7 @@ GTEST_API_ bool LogIsVisible(LogSeverity severity) {
 // conservative.
 GTEST_API_ void Log(LogSeverity severity, const std::string& message,
                     int stack_frames_to_skip) {
-  if (!LogIsVisible(severity))
-    return;
+  if (!LogIsVisible(severity)) return;
 
   // Ensures that logs from different threads don't interleave.
   MutexLock l(&g_log_mutex);
@@ -178,8 +180,8 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message,
       std::cout << "\n";
     }
     std::cout << "Stack trace:\n"
-         << ::testing::internal::GetCurrentOsStackTraceExceptTop(
-             ::testing::UnitTest::GetInstance(), actual_to_skip);
+              << ::testing::internal::GetCurrentOsStackTraceExceptTop(
+                     ::testing::UnitTest::GetInstance(), actual_to_skip);
   }
   std::cout << ::std::flush;
 }
@@ -196,5 +198,53 @@ GTEST_API_ void IllegalDoDefault(const char* file, int line) {
       "the variable in various places.");
 }
 
+constexpr char UnBase64Impl(char c, const char* const base64, char carry) {
+  return *base64 == 0   ? static_cast<char>(65)
+         : *base64 == c ? carry
+                        : UnBase64Impl(c, base64 + 1, carry + 1);
+}
+
+template <size_t... I>
+constexpr std::array<char, 256> UnBase64Impl(IndexSequence<I...>,
+                                             const char* const base64) {
+  return {{UnBase64Impl(static_cast<char>(I), base64, 0)...}};
+}
+
+constexpr std::array<char, 256> UnBase64(const char* const base64) {
+  return UnBase64Impl(MakeIndexSequence<256>{}, base64);
+}
+
+static constexpr char kBase64[] =
+    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+static constexpr std::array<char, 256> kUnBase64 = UnBase64(kBase64);
+
+bool Base64Unescape(const std::string& encoded, std::string* decoded) {
+  decoded->clear();
+  size_t encoded_len = encoded.size();
+  decoded->reserve(3 * (encoded_len / 4) + (encoded_len % 4));
+  int bit_pos = 0;
+  char dst = 0;
+  for (int src : encoded) {
+    if (std::isspace(src) || src == '=') {
+      continue;
+    }
+    char src_bin = kUnBase64[static_cast<size_t>(src)];
+    if (src_bin >= 64) {
+      decoded->clear();
+      return false;
+    }
+    if (bit_pos == 0) {
+      dst |= static_cast<char>(src_bin << 2);
+      bit_pos = 6;
+    } else {
+      dst |= static_cast<char>(src_bin >> (bit_pos - 2));
+      decoded->push_back(dst);
+      dst = static_cast<char>(src_bin << (10 - bit_pos));
+      bit_pos = (bit_pos + 6) % 8;
+    }
+  }
+  return true;
+}
+
 }  // namespace internal
 }  // namespace testing
index dded437addbaabb7cc7f1972f6ebd1402fdfe1bc..a8d04a6da0c06cab97b0b0d71d26791c8e9baa86 100644 (file)
@@ -27,7 +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.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file implements Matcher<const string&>, Matcher<string>, and
 #include "gmock/gmock-matchers.h"
 
 #include <string.h>
+
 #include <iostream>
 #include <sstream>
 #include <string>
+#include <vector>
 
 namespace testing {
 namespace internal {
@@ -48,11 +49,13 @@ namespace internal {
 // 'negation' is false; otherwise returns the description of the
 // negation of the matcher.  'param_values' contains a list of strings
 // that are the print-out of the matcher's parameters.
-GTEST_API_ std::string FormatMatcherDescription(bool negation,
-                                                const char* matcher_name,
-                                                const Strings& param_values) {
+GTEST_API_ std::string FormatMatcherDescription(
+    bool negation, const char* matcher_name,
+    const std::vector<const char*>& param_names, const Strings& param_values) {
   std::string result = ConvertIdentifierNameToWords(matcher_name);
-  if (param_values.size() >= 1) result += " " + JoinAsTuple(param_values);
+  if (param_values.size() >= 1) {
+    result += " " + JoinAsKeyValueTuple(param_names, param_values);
+  }
   return negation ? "not (" + result + ")" : result;
 }
 
index c7266a3704b0e54425a28ce20de235c6ef6de709..658ad3fa229eca92ce5907ef44ad9fe836c6fde7 100644 (file)
@@ -27,7 +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.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file implements the spec builder syntax (ON_CALL and
@@ -42,6 +41,7 @@
 #include <memory>
 #include <set>
 #include <string>
+#include <unordered_map>
 #include <vector>
 
 #include "gmock/gmock.h"
 #include "gtest/internal/gtest-port.h"
 
 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
-# include <unistd.h>  // NOLINT
+#include <unistd.h>  // NOLINT
 #endif
 
 // Silence C4800 (C4800: 'int *const ': forcing value
 // to bool 'true' or 'false') for MSVC 15
 #ifdef _MSC_VER
 #if _MSC_VER == 1900
-#  pragma warning(push)
-#  pragma warning(disable:4800)
+#pragma warning(push)
+#pragma warning(disable : 4800)
 #endif
 #endif
 
@@ -195,11 +195,12 @@ void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
 
   // Describes the state of the expectation (e.g. is it satisfied?
   // is it active?).
-  *os << " - " << (IsOverSaturated() ? "over-saturated" :
-                   IsSaturated() ? "saturated" :
-                   IsSatisfied() ? "satisfied" : "unsatisfied")
-      << " and "
-      << (is_retired() ? "retired" : "active");
+  *os << " - "
+      << (IsOverSaturated() ? "over-saturated"
+          : IsSaturated()   ? "saturated"
+          : IsSatisfied()   ? "satisfied"
+                            : "unsatisfied")
+      << " and " << (is_retired() ? "retired" : "active");
 }
 
 // Checks the action count (i.e. the number of WillOnce() and
@@ -242,13 +243,12 @@ void ExpectationBase::CheckActionCountIfNotDone() const
 
     ::std::stringstream ss;
     DescribeLocationTo(&ss);
-    ss << "Too " << (too_many ? "many" : "few")
-       << " actions specified in " << source_text() << "...\n"
+    ss << "Too " << (too_many ? "many" : "few") << " actions specified in "
+       << source_text() << "...\n"
        << "Expected to be ";
     cardinality().DescribeTo(&ss);
-    ss << ", but has " << (too_many ? "" : "only ")
-       << action_count << " WillOnce()"
-       << (action_count == 1 ? "" : "s");
+    ss << ", but has " << (too_many ? "" : "only ") << action_count
+       << " WillOnce()" << (action_count == 1 ? "" : "s");
     if (repeated_action_specified_) {
       ss << " and a WillRepeatedly()";
     }
@@ -264,10 +264,10 @@ void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
                        ".Times() cannot appear "
                        "more than once in an EXPECT_CALL().");
   } else {
-    ExpectSpecProperty(last_clause_ < kTimes,
-                       ".Times() cannot appear after "
-                       ".InSequence(), .WillOnce(), .WillRepeatedly(), "
-                       "or .RetiresOnSaturation().");
+    ExpectSpecProperty(
+        last_clause_ < kTimes,
+        ".Times() may only appear *before* .InSequence(), .WillOnce(), "
+        ".WillRepeatedly(), or .RetiresOnSaturation(), not after.");
   }
   last_clause_ = kTimes;
 
@@ -283,7 +283,7 @@ GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
 void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
   // Include a stack trace only if --gmock_verbose=info is specified.
   const int stack_frames_to_skip =
-      GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1;
+      GMOCK_FLAG_GET(verbose) == kInfoVerbosity ? 3 : -1;
   switch (reaction) {
     case kAllow:
       Log(kInfo, msg, stack_frames_to_skip);
@@ -370,143 +370,12 @@ const char* UntypedFunctionMockerBase::Name() const
   return name;
 }
 
-// Calculates the result of invoking this mock function with the given
-// arguments, prints it, and returns it.  The caller is responsible
-// for deleting the result.
-UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
-    void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
-  // See the definition of untyped_expectations_ for why access to it
-  // is unprotected here.
-  if (untyped_expectations_.size() == 0) {
-    // No expectation is set on this mock method - we have an
-    // uninteresting call.
-
-    // We must get Google Mock's reaction on uninteresting calls
-    // made on this mock object BEFORE performing the action,
-    // because the action may DELETE the mock object and make the
-    // following expression meaningless.
-    const CallReaction reaction =
-        Mock::GetReactionOnUninterestingCalls(MockObject());
-
-    // True if and only if we need to print this call's arguments and return
-    // value.  This definition must be kept in sync with
-    // the behavior of ReportUninterestingCall().
-    const bool need_to_report_uninteresting_call =
-        // If the user allows this uninteresting call, we print it
-        // only when they want informational messages.
-        reaction == kAllow ? LogIsVisible(kInfo) :
-                           // If the user wants this to be a warning, we print
-                           // it only when they want to see warnings.
-            reaction == kWarn
-                ? LogIsVisible(kWarning)
-                :
-                // Otherwise, the user wants this to be an error, and we
-                // should always print detailed information in the error.
-                true;
-
-    if (!need_to_report_uninteresting_call) {
-      // Perform the action without printing the call information.
-      return this->UntypedPerformDefaultAction(
-          untyped_args, "Function call: " + std::string(Name()));
-    }
-
-    // Warns about the uninteresting call.
-    ::std::stringstream ss;
-    this->UntypedDescribeUninterestingCall(untyped_args, &ss);
-
-    // Calculates the function result.
-    UntypedActionResultHolderBase* const result =
-        this->UntypedPerformDefaultAction(untyped_args, ss.str());
-
-    // Prints the function result.
-    if (result != nullptr) result->PrintAsActionResult(&ss);
-
-    ReportUninterestingCall(reaction, ss.str());
-    return result;
-  }
-
-  bool is_excessive = false;
-  ::std::stringstream ss;
-  ::std::stringstream why;
-  ::std::stringstream loc;
-  const void* untyped_action = nullptr;
-
-  // The UntypedFindMatchingExpectation() function acquires and
-  // releases g_gmock_mutex.
-
-  const ExpectationBase* const untyped_expectation =
-      this->UntypedFindMatchingExpectation(untyped_args, &untyped_action,
-                                           &is_excessive, &ss, &why);
-  const bool found = untyped_expectation != nullptr;
-
-  // True if and only if we need to print the call's arguments
-  // and return value.
-  // This definition must be kept in sync with the uses of Expect()
-  // and Log() in this function.
-  const bool need_to_report_call =
-      !found || is_excessive || LogIsVisible(kInfo);
-  if (!need_to_report_call) {
-    // Perform the action without printing the call information.
-    return untyped_action == nullptr
-               ? this->UntypedPerformDefaultAction(untyped_args, "")
-               : this->UntypedPerformAction(untyped_action, untyped_args);
-  }
-
-  ss << "    Function call: " << Name();
-  this->UntypedPrintArgs(untyped_args, &ss);
-
-  // In case the action deletes a piece of the expectation, we
-  // generate the message beforehand.
-  if (found && !is_excessive) {
-    untyped_expectation->DescribeLocationTo(&loc);
-  }
-
-  UntypedActionResultHolderBase* result = nullptr;
-
-  auto perform_action = [&] {
-    return untyped_action == nullptr
-               ? this->UntypedPerformDefaultAction(untyped_args, ss.str())
-               : this->UntypedPerformAction(untyped_action, untyped_args);
-  };
-  auto handle_failures = [&] {
-    ss << "\n" << why.str();
-
-    if (!found) {
-      // No expectation matches this call - reports a failure.
-      Expect(false, nullptr, -1, ss.str());
-    } else if (is_excessive) {
-      // We had an upper-bound violation and the failure message is in ss.
-      Expect(false, untyped_expectation->file(), untyped_expectation->line(),
-             ss.str());
-    } else {
-      // We had an expected call and the matching expectation is
-      // described in ss.
-      Log(kInfo, loc.str() + ss.str(), 2);
-    }
-  };
-#if GTEST_HAS_EXCEPTIONS
-  try {
-    result = perform_action();
-  } catch (...) {
-    handle_failures();
-    throw;
-  }
-#else
-  result = perform_action();
-#endif
-
-  if (result != nullptr) result->PrintAsActionResult(&ss);
-  handle_failures();
-  return result;
-}
-
 // Returns an Expectation object that references and co-owns exp,
 // which must be an expectation on this mock function.
 Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
   // See the definition of untyped_expectations_ for why access to it
   // is unprotected here.
-  for (UntypedExpectations::const_iterator it =
-           untyped_expectations_.begin();
+  for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();
        it != untyped_expectations_.end(); ++it) {
     if (it->get() == exp) {
       return Expectation(*it);
@@ -526,8 +395,7 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
   g_gmock_mutex.AssertHeld();
   bool expectations_met = true;
-  for (UntypedExpectations::const_iterator it =
-           untyped_expectations_.begin();
+  for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();
        it != untyped_expectations_.end(); ++it) {
     ExpectationBase* const untyped_expectation = it->get();
     if (untyped_expectation->IsOverSaturated()) {
@@ -538,15 +406,15 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
     } else if (!untyped_expectation->IsSatisfied()) {
       expectations_met = false;
       ::std::stringstream ss;
-      ss  << "Actual function call count doesn't match "
-          << untyped_expectation->source_text() << "...\n";
+      ss << "Actual function call count doesn't match "
+         << untyped_expectation->source_text() << "...\n";
       // No need to show the source file location of the expectation
       // in the description, as the Expect() call that follows already
       // takes care of it.
       untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
       untyped_expectation->DescribeCallCountTo(&ss);
-      Expect(false, untyped_expectation->file(),
-             untyped_expectation->line(), ss.str());
+      Expect(false, untyped_expectation->file(), untyped_expectation->line(),
+             ss.str());
     }
   }
 
@@ -613,8 +481,7 @@ class MockObjectRegistry {
   // object alive.  Therefore we report any living object as test
   // failure, unless the user explicitly asked us to ignore it.
   ~MockObjectRegistry() {
-    if (!GMOCK_FLAG(catch_leaked_mocks))
-      return;
+    if (!GMOCK_FLAG_GET(catch_leaked_mocks)) return;
 
     int leaked_count = 0;
     for (StateMap::const_iterator it = states_.begin(); it != states_.end();
@@ -634,7 +501,7 @@ class MockObjectRegistry {
                   << state.first_used_test << ")";
       }
       std::cout << " should be deleted but never is. Its address is @"
-           << it->first << ".";
+                << it->first << ".";
       leaked_count++;
     }
     if (leaked_count > 0) {
@@ -668,57 +535,63 @@ MockObjectRegistry g_mock_object_registry;
 
 // Maps a mock object to the reaction Google Mock should have when an
 // uninteresting method is called.  Protected by g_gmock_mutex.
-std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
+std::unordered_map<uintptr_t, internal::CallReaction>&
+UninterestingCallReactionMap() {
+  static auto* map = new std::unordered_map<uintptr_t, internal::CallReaction>;
+  return *map;
+}
 
 // Sets the reaction Google Mock should have when an uninteresting
 // method of the given mock object is called.
-void SetReactionOnUninterestingCalls(const void* mock_obj,
+void SetReactionOnUninterestingCalls(uintptr_t mock_obj,
                                      internal::CallReaction reaction)
     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
   internal::MutexLock l(&internal::g_gmock_mutex);
-  g_uninteresting_call_reaction[mock_obj] = reaction;
+  UninterestingCallReactionMap()[mock_obj] = reaction;
 }
 
 }  // namespace
 
 // Tells Google Mock to allow uninteresting calls on the given mock
 // object.
-void Mock::AllowUninterestingCalls(const void* mock_obj)
+void Mock::AllowUninterestingCalls(uintptr_t mock_obj)
     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
   SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
 }
 
 // Tells Google Mock to warn the user about uninteresting calls on the
 // given mock object.
-void Mock::WarnUninterestingCalls(const void* mock_obj)
+void Mock::WarnUninterestingCalls(uintptr_t mock_obj)
     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
   SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
 }
 
 // Tells Google Mock to fail uninteresting calls on the given mock
 // object.
-void Mock::FailUninterestingCalls(const void* mock_obj)
+void Mock::FailUninterestingCalls(uintptr_t mock_obj)
     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
   SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
 }
 
 // Tells Google Mock the given mock object is being destroyed and its
 // entry in the call-reaction table should be removed.
-void Mock::UnregisterCallReaction(const void* mock_obj)
+void Mock::UnregisterCallReaction(uintptr_t mock_obj)
     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
   internal::MutexLock l(&internal::g_gmock_mutex);
-  g_uninteresting_call_reaction.erase(mock_obj);
+  UninterestingCallReactionMap().erase(static_cast<uintptr_t>(mock_obj));
 }
 
 // Returns the reaction Google Mock will have on uninteresting calls
 // made on the given mock object.
 internal::CallReaction Mock::GetReactionOnUninterestingCalls(
-    const void* mock_obj)
-        GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
+    const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
   internal::MutexLock l(&internal::g_gmock_mutex);
-  return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
-      internal::intToCallReaction(GMOCK_FLAG(default_mock_behavior)) :
-      g_uninteresting_call_reaction[mock_obj];
+  return (UninterestingCallReactionMap().count(
+              reinterpret_cast<uintptr_t>(mock_obj)) == 0)
+             ? internal::intToCallReaction(
+                   GMOCK_FLAG_GET(default_mock_behavior))
+             : UninterestingCallReactionMap()[reinterpret_cast<uintptr_t>(
+                   mock_obj)];
 }
 
 // Tells Google Mock to ignore mock_obj when checking for leaked mock
@@ -873,8 +746,8 @@ Expectation::~Expectation() {}
 void Sequence::AddExpectation(const Expectation& expectation) const {
   if (*last_expectation_ != expectation) {
     if (last_expectation_->expectation_base() != nullptr) {
-      expectation.expectation_base()->immediate_prerequisites_
-          += *last_expectation_;
+      expectation.expectation_base()->immediate_prerequisites_ +=
+          *last_expectation_;
     }
     *last_expectation_ = expectation;
   }
@@ -903,6 +776,6 @@ InSequence::~InSequence() {
 
 #ifdef _MSC_VER
 #if _MSC_VER == 1900
-#  pragma warning(pop)
+#pragma warning(pop)
 #endif
 #endif
index 7bcdb0ba2dfca27676a81dda7791ace699516e31..5025656a02a30a7258d90613ecf3e4bffd46f887 100644 (file)
 // (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 "gmock/gmock.h"
-#include "gmock/internal/gmock-port.h"
 
-namespace testing {
+#include "gmock/internal/gmock-port.h"
 
 GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
                    "true if and only if Google Mock should report leaked "
                    "mock objects as failures.");
 
-GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,
+GMOCK_DEFINE_string_(verbose, testing::internal::kWarningVerbosity,
                      "Controls how verbose Google Mock's output is."
                      "  Valid values:\n"
                      "  info    - prints all messages.\n"
@@ -51,6 +49,7 @@ GMOCK_DEFINE_int32_(default_mock_behavior, 1,
                     "  1 - by default, mocks act as NaggyMocks.\n"
                     "  2 - by default, mocks act as StrictMocks.");
 
+namespace testing {
 namespace internal {
 
 // Parses a string as a command line flag.  The string should have the
@@ -59,18 +58,18 @@ namespace internal {
 //
 // Returns the value of the flag, or NULL if the parsing failed.
 static const char* ParseGoogleMockFlagValue(const char* str,
-                                            const char* flag,
+                                            const char* flag_name,
                                             bool def_optional) {
   // str and flag must not be NULL.
-  if (str == nullptr || flag == nullptr) return nullptr;
+  if (str == nullptr || flag_name == nullptr) return nullptr;
 
   // The flag must start with "--gmock_".
-  const std::string flag_str = std::string("--gmock_") + flag;
-  const size_t flag_len = flag_str.length();
-  if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
+  const std::string flag_name_str = std::string("--gmock_") + flag_name;
+  const size_t flag_name_len = flag_name_str.length();
+  if (strncmp(str, flag_name_str.c_str(), flag_name_len) != 0) return nullptr;
 
   // Skips the flag name.
-  const char* flag_end = str + flag_len;
+  const char* flag_end = str + flag_name_len;
 
   // When def_optional is true, it's OK to not have a "=value" part.
   if (def_optional && (flag_end[0] == '\0')) {
@@ -91,10 +90,10 @@ static const char* ParseGoogleMockFlagValue(const char* str,
 //
 // On success, stores the value of the flag in *value, and returns
 // true.  On failure, returns false without changing *value.
-static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
-                                    bool* value) {
+static bool ParseGoogleMockFlag(const char* str, const char* flag_name,
+                                bool* value) {
   // Gets the value of the flag as a string.
-  const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
+  const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, true);
 
   // Aborts if the parsing failed.
   if (value_str == nullptr) return false;
@@ -110,10 +109,10 @@ static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
 // On success, stores the value of the flag in *value, and returns
 // true.  On failure, returns false without changing *value.
 template <typename String>
-static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
-                                      String* value) {
+static bool ParseGoogleMockFlag(const char* str, const char* flag_name,
+                                String* value) {
   // Gets the value of the flag as a string.
-  const char* const value_str = ParseGoogleMockFlagValue(str, flag, false);
+  const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, false);
 
   // Aborts if the parsing failed.
   if (value_str == nullptr) return false;
@@ -123,17 +122,17 @@ static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
   return true;
 }
 
-static bool ParseGoogleMockIntFlag(const char* str, const char* flag,
-                                   int32_t* value) {
+static bool ParseGoogleMockFlag(const char* str, const char* flag_name,
+                                int32_t* value) {
   // Gets the value of the flag as a string.
-  const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
+  const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, true);
 
   // Aborts if the parsing failed.
   if (value_str == nullptr) return false;
 
   // Sets *value to the value of the flag.
-  return ParseInt32(Message() << "The value of flag --" << flag,
-                    value_str, value);
+  return ParseInt32(Message() << "The value of flag --" << flag_name, value_str,
+                    value);
 }
 
 // The internal implementation of InitGoogleMock().
@@ -152,11 +151,22 @@ void InitGoogleMockImpl(int* argc, CharType** argv) {
     const char* const arg = arg_string.c_str();
 
     // Do we see a Google Mock flag?
-    if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks",
-                                &GMOCK_FLAG(catch_leaked_mocks)) ||
-        ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose)) ||
-        ParseGoogleMockIntFlag(arg, "default_mock_behavior",
-                               &GMOCK_FLAG(default_mock_behavior))) {
+    bool found_gmock_flag = false;
+
+#define GMOCK_INTERNAL_PARSE_FLAG(flag_name)            \
+  if (!found_gmock_flag) {                              \
+    auto value = GMOCK_FLAG_GET(flag_name);             \
+    if (ParseGoogleMockFlag(arg, #flag_name, &value)) { \
+      GMOCK_FLAG_SET(flag_name, value);                 \
+      found_gmock_flag = true;                          \
+    }                                                   \
+  }
+
+    GMOCK_INTERNAL_PARSE_FLAG(catch_leaked_mocks)
+    GMOCK_INTERNAL_PARSE_FLAG(verbose)
+    GMOCK_INTERNAL_PARSE_FLAG(default_mock_behavior)
+
+    if (found_gmock_flag) {
       // Yes.  Shift the remainder of the argv list left by one.  Note
       // that argv has (*argc + 1) elements, the last one always being
       // NULL.  The following loop moves the trailing NULL element as
index 18c500f6639d211d7e1c6de9c7c9ed6f9053214c..b411c5ecb97a1f6605d61298e83077b54e6af6ba 100644 (file)
@@ -27,8 +27,8 @@
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-
 #include <iostream>
+
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
@@ -56,7 +56,7 @@ void loop() { RUN_ALL_TESTS(); }
 // https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library
 // // NOLINT
 #if GTEST_OS_WINDOWS_MOBILE
-# include <tchar.h>  // NOLINT
+#include <tchar.h>  // NOLINT
 
 GTEST_API_ int _tmain(int argc, TCHAR** argv) {
 #else
index efb7306b22627f9c0fe14b121f9dc60e2500cca0..d4297c80fe8d182bd5675a26701bd97497d82dd5 100644 (file)
@@ -30,7 +30,6 @@
 #
 #   Bazel Build for Google C++ Testing Framework(Google Test)-googlemock
 
-load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test")
 load("@rules_python//python:defs.bzl", "py_library", "py_test")
 
 licenses(["notice"])
@@ -39,8 +38,9 @@ licenses(["notice"])
 cc_test(
     name = "gmock_all_test",
     size = "small",
-    srcs = glob(include = ["gmock-*.cc"]),
+    srcs = glob(include = ["gmock-*.cc"]) + ["gmock-matchers_test.h"],
     linkopts = select({
+        "//:qnx": [],
         "//:windows": [],
         "//conditions:default": ["-pthread"],
     }),
index e1ca7fe2ddb8adc4f4dd60a8964386089439c0b7..215495ed2a06a2e0ea15aafc4d9922990c01a9bd 100644 (file)
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file tests the built-in actions.
 
-// Silence C4100 (unreferenced formal parameter) for MSVC
+// Silence C4100 (unreferenced formal parameter) and C4503 (decorated name
+// length exceeded) for MSVC.
 #ifdef _MSC_VER
-#  pragma warning(push)
-#  pragma warning(disable:4100)
+#pragma warning(push)
+#pragma warning(disable : 4100)
+#pragma warning(disable : 4503)
 #if _MSC_VER == 1900
 // and silence C4800 (C4800: 'int *const ': forcing value
 // to bool 'true' or 'false') for MSVC 15
-#  pragma warning(disable:4800)
+#pragma warning(disable : 4800)
 #endif
 #endif
 
 #include "gmock/gmock-actions.h"
+
 #include <algorithm>
+#include <functional>
 #include <iterator>
 #include <memory>
 #include <string>
 #include <type_traits>
+#include <vector>
+
 #include "gmock/gmock.h"
 #include "gmock/internal/gmock-port.h"
-#include "gtest/gtest.h"
 #include "gtest/gtest-spi.h"
+#include "gtest/gtest.h"
 
+namespace testing {
 namespace {
 
-using ::testing::_;
-using ::testing::Action;
-using ::testing::ActionInterface;
-using ::testing::Assign;
-using ::testing::ByMove;
-using ::testing::ByRef;
-using ::testing::DefaultValue;
-using ::testing::DoAll;
-using ::testing::DoDefault;
-using ::testing::IgnoreResult;
-using ::testing::Invoke;
-using ::testing::InvokeWithoutArgs;
-using ::testing::MakePolymorphicAction;
-using ::testing::PolymorphicAction;
-using ::testing::Return;
-using ::testing::ReturnNew;
-using ::testing::ReturnNull;
-using ::testing::ReturnRef;
-using ::testing::ReturnRefOfCopy;
-using ::testing::ReturnRoundRobin;
-using ::testing::SetArgPointee;
-using ::testing::SetArgumentPointee;
-using ::testing::Unused;
-using ::testing::WithArgs;
 using ::testing::internal::BuiltInDefaultValue;
 
-#if !GTEST_OS_WINDOWS_MOBILE
-using ::testing::SetErrnoAndReturn;
-#endif
+TEST(TypeTraits, Negation) {
+  // Direct use with std types.
+  static_assert(std::is_base_of<std::false_type,
+                                internal::negation<std::true_type>>::value,
+                "");
+
+  static_assert(std::is_base_of<std::true_type,
+                                internal::negation<std::false_type>>::value,
+                "");
+
+  // With other types that fit the requirement of a value member that is
+  // convertible to bool.
+  static_assert(std::is_base_of<
+                    std::true_type,
+                    internal::negation<std::integral_constant<int, 0>>>::value,
+                "");
+
+  static_assert(std::is_base_of<
+                    std::false_type,
+                    internal::negation<std::integral_constant<int, 1>>>::value,
+                "");
+
+  static_assert(std::is_base_of<
+                    std::false_type,
+                    internal::negation<std::integral_constant<int, -1>>>::value,
+                "");
+}
+
+// Weird false/true types that aren't actually bool constants (but should still
+// be legal according to [meta.logical] because `bool(T::value)` is valid), are
+// distinct from std::false_type and std::true_type, and are distinct from other
+// instantiations of the same template.
+//
+// These let us check finicky details mandated by the standard like
+// "std::conjunction should evaluate to a type that inherits from the first
+// false-y input".
+template <int>
+struct MyFalse : std::integral_constant<int, 0> {};
+
+template <int>
+struct MyTrue : std::integral_constant<int, -1> {};
+
+TEST(TypeTraits, Conjunction) {
+  // Base case: always true.
+  static_assert(std::is_base_of<std::true_type, internal::conjunction<>>::value,
+                "");
+
+  // One predicate: inherits from that predicate, regardless of value.
+  static_assert(
+      std::is_base_of<MyFalse<0>, internal::conjunction<MyFalse<0>>>::value,
+      "");
+
+  static_assert(
+      std::is_base_of<MyTrue<0>, internal::conjunction<MyTrue<0>>>::value, "");
+
+  // Multiple predicates, with at least one false: inherits from that one.
+  static_assert(
+      std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,
+                                                        MyTrue<2>>>::value,
+      "");
+
+  static_assert(
+      std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,
+                                                        MyFalse<2>>>::value,
+      "");
+
+  // Short circuiting: in the case above, additional predicates need not even
+  // define a value member.
+  struct Empty {};
+  static_assert(
+      std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,
+                                                        Empty>>::value,
+      "");
+
+  // All predicates true: inherits from the last.
+  static_assert(
+      std::is_base_of<MyTrue<2>, internal::conjunction<MyTrue<0>, MyTrue<1>,
+                                                       MyTrue<2>>>::value,
+      "");
+}
+
+TEST(TypeTraits, Disjunction) {
+  // Base case: always false.
+  static_assert(
+      std::is_base_of<std::false_type, internal::disjunction<>>::value, "");
+
+  // One predicate: inherits from that predicate, regardless of value.
+  static_assert(
+      std::is_base_of<MyFalse<0>, internal::disjunction<MyFalse<0>>>::value,
+      "");
+
+  static_assert(
+      std::is_base_of<MyTrue<0>, internal::disjunction<MyTrue<0>>>::value, "");
+
+  // Multiple predicates, with at least one true: inherits from that one.
+  static_assert(
+      std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,
+                                                       MyFalse<2>>>::value,
+      "");
+
+  static_assert(
+      std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,
+                                                       MyTrue<2>>>::value,
+      "");
+
+  // Short circuiting: in the case above, additional predicates need not even
+  // define a value member.
+  struct Empty {};
+  static_assert(
+      std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,
+                                                       Empty>>::value,
+      "");
+
+  // All predicates false: inherits from the last.
+  static_assert(
+      std::is_base_of<MyFalse<2>, internal::disjunction<MyFalse<0>, MyFalse<1>,
+                                                        MyFalse<2>>>::value,
+      "");
+}
+
+TEST(TypeTraits, IsInvocableRV) {
+  struct C {
+    int operator()() const { return 0; }
+    void operator()(int) & {}
+    std::string operator()(int) && { return ""; };
+  };
+
+  // The first overload is callable for const and non-const rvalues and lvalues.
+  // It can be used to obtain an int, cv void, or anything int is convertible
+  // to.
+  static_assert(internal::is_callable_r<int, C>::value, "");
+  static_assert(internal::is_callable_r<int, C&>::value, "");
+  static_assert(internal::is_callable_r<int, const C>::value, "");
+  static_assert(internal::is_callable_r<int, const C&>::value, "");
+
+  static_assert(internal::is_callable_r<void, C>::value, "");
+  static_assert(internal::is_callable_r<const volatile void, C>::value, "");
+  static_assert(internal::is_callable_r<char, C>::value, "");
+
+  // It's possible to provide an int. If it's given to an lvalue, the result is
+  // void. Otherwise it is std::string (which is also treated as allowed for a
+  // void result type).
+  static_assert(internal::is_callable_r<void, C&, int>::value, "");
+  static_assert(!internal::is_callable_r<int, C&, int>::value, "");
+  static_assert(!internal::is_callable_r<std::string, C&, int>::value, "");
+  static_assert(!internal::is_callable_r<void, const C&, int>::value, "");
+
+  static_assert(internal::is_callable_r<std::string, C, int>::value, "");
+  static_assert(internal::is_callable_r<void, C, int>::value, "");
+  static_assert(!internal::is_callable_r<int, C, int>::value, "");
+
+  // It's not possible to provide other arguments.
+  static_assert(!internal::is_callable_r<void, C, std::string>::value, "");
+  static_assert(!internal::is_callable_r<void, C, int, int>::value, "");
+
+  // In C++17 and above, where it's guaranteed that functions can return
+  // non-moveable objects, everything should work fine for non-moveable rsult
+  // types too.
+#if defined(__cplusplus) && __cplusplus >= 201703L
+  {
+    struct NonMoveable {
+      NonMoveable() = default;
+      NonMoveable(NonMoveable&&) = delete;
+    };
+
+    static_assert(!std::is_move_constructible_v<NonMoveable>);
+
+    struct Callable {
+      NonMoveable operator()() { return NonMoveable(); }
+    };
+
+    static_assert(internal::is_callable_r<NonMoveable, Callable>::value);
+    static_assert(internal::is_callable_r<void, Callable>::value);
+    static_assert(
+        internal::is_callable_r<const volatile void, Callable>::value);
+
+    static_assert(!internal::is_callable_r<int, Callable>::value);
+    static_assert(!internal::is_callable_r<NonMoveable, Callable, int>::value);
+  }
+#endif  // C++17 and above
+
+  // Nothing should choke when we try to call other arguments besides directly
+  // callable objects, but they should not show up as callable.
+  static_assert(!internal::is_callable_r<void, int>::value, "");
+  static_assert(!internal::is_callable_r<void, void (C::*)()>::value, "");
+  static_assert(!internal::is_callable_r<void, void (C::*)(), C*>::value, "");
+}
 
 // Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
 TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
@@ -114,17 +280,17 @@ TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
 #endif
 #endif
   EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get());  // NOLINT
-  EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get());  // NOLINT
-  EXPECT_EQ(0, BuiltInDefaultValue<short>::Get());  // NOLINT
+  EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get());     // NOLINT
+  EXPECT_EQ(0, BuiltInDefaultValue<short>::Get());            // NOLINT
   EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());
   EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());
   EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());
-  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get());  // NOLINT
-  EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get());  // NOLINT
-  EXPECT_EQ(0, BuiltInDefaultValue<long>::Get());  // NOLINT
+  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get());       // NOLINT
+  EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get());          // NOLINT
+  EXPECT_EQ(0, BuiltInDefaultValue<long>::Get());                 // NOLINT
   EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long long>::Get());  // NOLINT
-  EXPECT_EQ(0, BuiltInDefaultValue<signed long long>::Get());  // NOLINT
-  EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get());  // NOLINT
+  EXPECT_EQ(0, BuiltInDefaultValue<signed long long>::Get());     // NOLINT
+  EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get());            // NOLINT
   EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
   EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
 }
@@ -139,17 +305,17 @@ TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {
   EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
 #endif
   EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists());  // NOLINT
-  EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists());  // NOLINT
-  EXPECT_TRUE(BuiltInDefaultValue<short>::Exists());  // NOLINT
+  EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists());    // NOLINT
+  EXPECT_TRUE(BuiltInDefaultValue<short>::Exists());           // NOLINT
   EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());
   EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());
   EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());
-  EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists());  // NOLINT
-  EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists());  // NOLINT
-  EXPECT_TRUE(BuiltInDefaultValue<long>::Exists());  // NOLINT
+  EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists());       // NOLINT
+  EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists());         // NOLINT
+  EXPECT_TRUE(BuiltInDefaultValue<long>::Exists());                // NOLINT
   EXPECT_TRUE(BuiltInDefaultValue<unsigned long long>::Exists());  // NOLINT
-  EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists());  // NOLINT
-  EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists());  // NOLINT
+  EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists());    // NOLINT
+  EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists());           // NOLINT
   EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());
   EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());
 }
@@ -167,13 +333,13 @@ TEST(BuiltInDefaultValueTest, BoolExists) {
 // Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
 // string type.
 TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
-  EXPECT_EQ("", BuiltInDefaultValue< ::std::string>::Get());
+  EXPECT_EQ("", BuiltInDefaultValue<::std::string>::Get());
 }
 
 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
 // string type.
 TEST(BuiltInDefaultValueTest, ExistsForString) {
-  EXPECT_TRUE(BuiltInDefaultValue< ::std::string>::Exists());
+  EXPECT_TRUE(BuiltInDefaultValue<::std::string>::Exists());
 }
 
 // Tests that BuiltInDefaultValue<const T>::Get() returns the same
@@ -208,7 +374,6 @@ class MyNonDefaultConstructible {
   int value_;
 };
 
-
 TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
   EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
 }
@@ -217,25 +382,19 @@ TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
   EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
 }
 
-
 TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
   EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
 }
 
 // Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
-  EXPECT_DEATH_IF_SUPPORTED({
-    BuiltInDefaultValue<int&>::Get();
-  }, "");
-  EXPECT_DEATH_IF_SUPPORTED({
-    BuiltInDefaultValue<const char&>::Get();
-  }, "");
+  EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<int&>::Get(); }, "");
+  EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<const char&>::Get(); }, "");
 }
 
 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
-  EXPECT_DEATH_IF_SUPPORTED({
-    BuiltInDefaultValue<MyNonDefaultConstructible>::Get();
-  }, "");
+  EXPECT_DEATH_IF_SUPPORTED(
+      { BuiltInDefaultValue<MyNonDefaultConstructible>::Get(); }, "");
 }
 
 // Tests that DefaultValue<T>::IsSet() is false initially.
@@ -281,26 +440,22 @@ TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
 
   EXPECT_EQ(0, DefaultValue<int>::Get());
 
-  EXPECT_DEATH_IF_SUPPORTED({
-    DefaultValue<MyNonDefaultConstructible>::Get();
-  }, "");
+  EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },
+                            "");
 }
 
 TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
   EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
   EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr);
-  DefaultValue<std::unique_ptr<int>>::SetFactory([] {
-    return std::unique_ptr<int>(new int(42));
-  });
+  DefaultValue<std::unique_ptr<int>>::SetFactory(
+      [] { return std::unique_ptr<int>(new int(42)); });
   EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
   std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
   EXPECT_EQ(42, *i);
 }
 
 // Tests that DefaultValue<void>::Get() returns void.
-TEST(DefaultValueTest, GetWorksForVoid) {
-  return DefaultValue<void>::Get();
-}
+TEST(DefaultValueTest, GetWorksForVoid) { return DefaultValue<void>::Get(); }
 
 // Tests using DefaultValue with a reference type.
 
@@ -348,12 +503,9 @@ TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
   EXPECT_FALSE(DefaultValue<int&>::IsSet());
   EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
 
-  EXPECT_DEATH_IF_SUPPORTED({
-    DefaultValue<int&>::Get();
-  }, "");
-  EXPECT_DEATH_IF_SUPPORTED({
-    DefaultValue<MyNonDefaultConstructible>::Get();
-  }, "");
+  EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, "");
+  EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },
+                            "");
 }
 
 // Tests that ActionInterface can be implemented by defining the
@@ -384,7 +536,7 @@ TEST(ActionInterfaceTest, MakeAction) {
   EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));
 }
 
-// Tests that Action<F> can be contructed from a pointer to
+// Tests that Action<F> can be constructed from a pointer to
 // ActionInterface<F>.
 TEST(ActionTest, CanBeConstructedFromActionInterface) {
   Action<MyGlobalFunction> action(new MyActionImpl);
@@ -433,7 +585,7 @@ class IsNotZero : public ActionInterface<bool(int)> {  // NOLINT
 };
 
 TEST(ActionTest, CanBeConvertedToOtherActionType) {
-  const Action<bool(int)> a1(new IsNotZero);  // NOLINT
+  const Action<bool(int)> a1(new IsNotZero);           // NOLINT
   const Action<int(char)> a2 = Action<int(char)>(a1);  // NOLINT
   EXPECT_EQ(1, a2.Perform(std::make_tuple('a')));
   EXPECT_EQ(0, a2.Perform(std::make_tuple('\0')));
@@ -525,24 +677,134 @@ TEST(ReturnTest, AcceptsStringLiteral) {
   EXPECT_EQ("world", a2.Perform(std::make_tuple()));
 }
 
-// Test struct which wraps a vector of integers. Used in
-// 'SupportsWrapperReturnType' test.
-struct IntegerVectorWrapper {
-  std::vector<int> * v;
-  IntegerVectorWrapper(std::vector<int>& _v) : v(&_v) {}  // NOLINT
-};
+// Return(x) should work fine when the mock function's return type is a
+// reference-like wrapper for decltype(x), as when x is a std::string and the
+// mock function returns std::string_view.
+TEST(ReturnTest, SupportsReferenceLikeReturnType) {
+  // A reference wrapper for std::vector<int>, implicitly convertible from it.
+  struct Result {
+    const std::vector<int>* v;
+    Result(const std::vector<int>& v) : v(&v) {}  // NOLINT
+  };
+
+  // Set up an action for a mock function that returns the reference wrapper
+  // type, initializing it with an actual vector.
+  //
+  // The returned wrapper should be initialized with a copy of that vector
+  // that's embedded within the action itself (which should stay alive as long
+  // as the mock object is alive), rather than e.g. a reference to the temporary
+  // we feed to Return. This should work fine both for WillOnce and
+  // WillRepeatedly.
+  MockFunction<Result()> mock;
+  EXPECT_CALL(mock, Call)
+      .WillOnce(Return(std::vector<int>{17, 19, 23}))
+      .WillRepeatedly(Return(std::vector<int>{29, 31, 37}));
 
-// Tests that Return() works when return type is a wrapper type.
-TEST(ReturnTest, SupportsWrapperReturnType) {
-  // Initialize vector of integers.
-  std::vector<int> v;
-  for (int i = 0; i < 5; ++i) v.push_back(i);
+  EXPECT_THAT(mock.AsStdFunction()(),
+              Field(&Result::v, Pointee(ElementsAre(17, 19, 23))));
 
-  // Return() called with 'v' as argument. The Action will return the same data
-  // as 'v' (copy) but it will be wrapped in an IntegerVectorWrapper.
-  Action<IntegerVectorWrapper()> a = Return(v);
-  const std::vector<int>& result = *(a.Perform(std::make_tuple()).v);
-  EXPECT_THAT(result, ::testing::ElementsAre(0, 1, 2, 3, 4));
+  EXPECT_THAT(mock.AsStdFunction()(),
+              Field(&Result::v, Pointee(ElementsAre(29, 31, 37))));
+}
+
+TEST(ReturnTest, PrefersConversionOperator) {
+  // Define types In and Out such that:
+  //
+  //  *  In is implicitly convertible to Out.
+  //  *  Out also has an explicit constructor from In.
+  //
+  struct In;
+  struct Out {
+    int x;
+
+    explicit Out(const int x) : x(x) {}
+    explicit Out(const In&) : x(0) {}
+  };
+
+  struct In {
+    operator Out() const { return Out{19}; }  // NOLINT
+  };
+
+  // Assumption check: the C++ language rules are such that a function that
+  // returns Out which uses In a return statement will use the implicit
+  // conversion path rather than the explicit constructor.
+  EXPECT_THAT([]() -> Out { return In(); }(), Field(&Out::x, 19));
+
+  // Return should work the same way: if the mock function's return type is Out
+  // and we feed Return an In value, then the Out should be created through the
+  // implicit conversion path rather than the explicit constructor.
+  MockFunction<Out()> mock;
+  EXPECT_CALL(mock, Call).WillOnce(Return(In()));
+  EXPECT_THAT(mock.AsStdFunction()(), Field(&Out::x, 19));
+}
+
+// It should be possible to use Return(R) with a mock function result type U
+// that is convertible from const R& but *not* R (such as
+// std::reference_wrapper). This should work for both WillOnce and
+// WillRepeatedly.
+TEST(ReturnTest, ConversionRequiresConstLvalueReference) {
+  using R = int;
+  using U = std::reference_wrapper<const int>;
+
+  static_assert(std::is_convertible<const R&, U>::value, "");
+  static_assert(!std::is_convertible<R, U>::value, "");
+
+  MockFunction<U()> mock;
+  EXPECT_CALL(mock, Call).WillOnce(Return(17)).WillRepeatedly(Return(19));
+
+  EXPECT_EQ(17, mock.AsStdFunction()());
+  EXPECT_EQ(19, mock.AsStdFunction()());
+}
+
+// Return(x) should not be usable with a mock function result type that's
+// implicitly convertible from decltype(x) but requires a non-const lvalue
+// reference to the input. It doesn't make sense for the conversion operator to
+// modify the input.
+TEST(ReturnTest, ConversionRequiresMutableLvalueReference) {
+  // Set up a type that is implicitly convertible from std::string&, but not
+  // std::string&& or `const std::string&`.
+  //
+  // Avoid asserting about conversion from std::string on MSVC, which seems to
+  // implement std::is_convertible incorrectly in this case.
+  struct S {
+    S(std::string&) {}  // NOLINT
+  };
+
+  static_assert(std::is_convertible<std::string&, S>::value, "");
+#ifndef _MSC_VER
+  static_assert(!std::is_convertible<std::string&&, S>::value, "");
+#endif
+  static_assert(!std::is_convertible<const std::string&, S>::value, "");
+
+  // It shouldn't be possible to use the result of Return(std::string) in a
+  // context where an S is needed.
+  //
+  // Here too we disable the assertion for MSVC, since its incorrect
+  // implementation of is_convertible causes our SFINAE to be wrong.
+  using RA = decltype(Return(std::string()));
+
+  static_assert(!std::is_convertible<RA, Action<S()>>::value, "");
+#ifndef _MSC_VER
+  static_assert(!std::is_convertible<RA, OnceAction<S()>>::value, "");
+#endif
+}
+
+TEST(ReturnTest, MoveOnlyResultType) {
+  // Return should support move-only result types when used with WillOnce.
+  {
+    MockFunction<std::unique_ptr<int>()> mock;
+    EXPECT_CALL(mock, Call)
+        // NOLINTNEXTLINE
+        .WillOnce(Return(std::unique_ptr<int>(new int(17))));
+
+    EXPECT_THAT(mock.AsStdFunction()(), Pointee(17));
+  }
+
+  // The result of Return should not be convertible to Action (so it can't be
+  // used with WillRepeatedly).
+  static_assert(!std::is_convertible<decltype(Return(std::unique_ptr<int>())),
+                                     Action<std::unique_ptr<int>()>>::value,
+                "");
 }
 
 // Tests that Return(v) is covaraint.
@@ -596,19 +858,6 @@ TEST(ReturnTest, ConvertsArgumentWhenConverted) {
                           << "when performed.";
 }
 
-class DestinationType {};
-
-class SourceType {
- public:
-  // Note: a non-const typecast operator.
-  operator DestinationType() { return DestinationType(); }
-};
-
-TEST(ReturnTest, CanConvertArgumentUsingNonConstTypeCastOperator) {
-  SourceType s;
-  Action<DestinationType()> action(Return(s));
-}
-
 // Tests that ReturnNull() returns NULL in a pointer-returning function.
 TEST(ReturnNullTest, WorksInPointerReturningFunction) {
   const Action<int*()> a1 = ReturnNull();
@@ -648,7 +897,9 @@ TEST(ReturnRefTest, IsCovariant) {
 }
 
 template <typename T, typename = decltype(ReturnRef(std::declval<T&&>()))>
-bool CanCallReturnRef(T&&) { return true; }
+bool CanCallReturnRef(T&&) {
+  return true;
+}
 bool CanCallReturnRef(Unused) { return false; }
 
 // Tests that ReturnRef(v) is working with non-temporaries (T&)
@@ -668,7 +919,7 @@ TEST(ReturnRefTest, WorksForNonTemporary) {
 
 // Tests that ReturnRef(v) is not working with temporaries (T&&)
 TEST(ReturnRefTest, DoesNotWorkForTemporary) {
-  auto scalar_value = []()  -> int { return 123; };
+  auto scalar_value = []() -> int { return 123; };
   EXPECT_FALSE(CanCallReturnRef(scalar_value()));
 
   auto non_scalar_value = []() -> std::string { return "ABC"; };
@@ -747,15 +998,15 @@ class MockClass {
                int(const std::unique_ptr<int>&, std::unique_ptr<int>));
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass);
+  MockClass(const MockClass&) = delete;
+  MockClass& operator=(const MockClass&) = delete;
 };
 
 // Tests that DoDefault() returns the built-in default value for the
 // return type by default.
 TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
   MockClass mock;
-  EXPECT_CALL(mock, IntFunc(_))
-      .WillOnce(DoDefault());
+  EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
   EXPECT_EQ(0, mock.IntFunc(true));
 }
 
@@ -763,14 +1014,11 @@ TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
 // the process when there is no built-in default value for the return type.
 TEST(DoDefaultDeathTest, DiesForUnknowType) {
   MockClass mock;
-  EXPECT_CALL(mock, Foo())
-      .WillRepeatedly(DoDefault());
+  EXPECT_CALL(mock, Foo()).WillRepeatedly(DoDefault());
 #if GTEST_HAS_EXCEPTIONS
   EXPECT_ANY_THROW(mock.Foo());
 #else
-  EXPECT_DEATH_IF_SUPPORTED({
-    mock.Foo();
-  }, "");
+  EXPECT_DEATH_IF_SUPPORTED({ mock.Foo(); }, "");
 #endif
 }
 
@@ -782,16 +1030,13 @@ void VoidFunc(bool /* flag */) {}
 TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
   MockClass mock;
   EXPECT_CALL(mock, IntFunc(_))
-      .WillRepeatedly(DoAll(Invoke(VoidFunc),
-                            DoDefault()));
+      .WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault()));
 
   // Ideally we should verify the error message as well.  Sadly,
   // EXPECT_DEATH() can only capture stderr, while Google Mock's
   // errors are printed on stdout.  Therefore we have to settle for
   // not verifying the message.
-  EXPECT_DEATH_IF_SUPPORTED({
-    mock.IntFunc(true);
-  }, "");
+  EXPECT_DEATH_IF_SUPPORTED({ mock.IntFunc(true); }, "");
 }
 
 // Tests that DoDefault() returns the default value set by
@@ -799,8 +1044,7 @@ TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
 TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
   DefaultValue<int>::Set(1);
   MockClass mock;
-  EXPECT_CALL(mock, IntFunc(_))
-      .WillOnce(DoDefault());
+  EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
   EXPECT_EQ(1, mock.IntFunc(false));
   DefaultValue<int>::Clear();
 }
@@ -808,20 +1052,19 @@ TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
 // Tests that DoDefault() does the action specified by ON_CALL().
 TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
   MockClass mock;
-  ON_CALL(mock, IntFunc(_))
-      .WillByDefault(Return(2));
-  EXPECT_CALL(mock, IntFunc(_))
-      .WillOnce(DoDefault());
+  ON_CALL(mock, IntFunc(_)).WillByDefault(Return(2));
+  EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
   EXPECT_EQ(2, mock.IntFunc(false));
 }
 
 // Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
 TEST(DoDefaultTest, CannotBeUsedInOnCall) {
   MockClass mock;
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    ON_CALL(mock, IntFunc(_))
-      .WillByDefault(DoDefault());
-  }, "DoDefault() cannot be used in ON_CALL()");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        ON_CALL(mock, IntFunc(_)).WillByDefault(DoDefault());
+      },
+      "DoDefault() cannot be used in ON_CALL()");
 }
 
 // Tests that SetArgPointee<N>(v) sets the variable pointed to by
@@ -868,7 +1111,7 @@ TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
   a.Perform(std::make_tuple(&ptr));
   EXPECT_STREQ(L"world", ptr);
 
-# if GTEST_HAS_STD_WSTRING
+#if GTEST_HAS_STD_WSTRING
 
   typedef void MyStringFunction(std::wstring*);
   Action<MyStringFunction> a2 = SetArgPointee<0>(L"world");
@@ -876,7 +1119,7 @@ TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
   a2.Perform(std::make_tuple(&str));
   EXPECT_EQ(L"world", str);
 
-# endif
+#endif
 }
 
 // Tests that SetArgPointee<N>() accepts a char pointer.
@@ -907,7 +1150,7 @@ TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
   a.Perform(std::make_tuple(true, &ptr));
   EXPECT_EQ(hi, ptr);
 
-# if GTEST_HAS_STD_WSTRING
+#if GTEST_HAS_STD_WSTRING
 
   typedef void MyStringFunction(bool, std::wstring*);
   wchar_t world_array[] = L"world";
@@ -916,7 +1159,7 @@ TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
   std::wstring str;
   a2.Perform(std::make_tuple(true, &str));
   EXPECT_EQ(world_array, str);
-# endif
+#endif
 }
 
 // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
@@ -1079,6 +1322,159 @@ TEST(AssignTest, CompatibleTypes) {
   EXPECT_DOUBLE_EQ(5, x);
 }
 
+// DoAll should support &&-qualified actions when used with WillOnce.
+TEST(DoAll, SupportsRefQualifiedActions) {
+  struct InitialAction {
+    void operator()(const int arg) && { EXPECT_EQ(17, arg); }
+  };
+
+  struct FinalAction {
+    int operator()() && { return 19; }
+  };
+
+  MockFunction<int(int)> mock;
+  EXPECT_CALL(mock, Call).WillOnce(DoAll(InitialAction{}, FinalAction{}));
+  EXPECT_EQ(19, mock.AsStdFunction()(17));
+}
+
+// DoAll should never provide rvalue references to the initial actions. If the
+// mock action itself accepts an rvalue reference or a non-scalar object by
+// value then the final action should receive an rvalue reference, but initial
+// actions should receive only lvalue references.
+TEST(DoAll, ProvidesLvalueReferencesToInitialActions) {
+  struct Obj {};
+
+  // Mock action accepts by value: the initial action should be fed a const
+  // lvalue reference, and the final action an rvalue reference.
+  {
+    struct InitialAction {
+      void operator()(Obj&) const { FAIL() << "Unexpected call"; }
+      void operator()(const Obj&) const {}
+      void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
+      void operator()(const Obj&&) const { FAIL() << "Unexpected call"; }
+    };
+
+    MockFunction<void(Obj)> mock;
+    EXPECT_CALL(mock, Call)
+        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}))
+        .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));
+
+    mock.AsStdFunction()(Obj{});
+    mock.AsStdFunction()(Obj{});
+  }
+
+  // Mock action accepts by const lvalue reference: both actions should receive
+  // a const lvalue reference.
+  {
+    struct InitialAction {
+      void operator()(Obj&) const { FAIL() << "Unexpected call"; }
+      void operator()(const Obj&) const {}
+      void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
+      void operator()(const Obj&&) const { FAIL() << "Unexpected call"; }
+    };
+
+    MockFunction<void(const Obj&)> mock;
+    EXPECT_CALL(mock, Call)
+        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {}))
+        .WillRepeatedly(
+            DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {}));
+
+    mock.AsStdFunction()(Obj{});
+    mock.AsStdFunction()(Obj{});
+  }
+
+  // Mock action accepts by non-const lvalue reference: both actions should get
+  // a non-const lvalue reference if they want them.
+  {
+    struct InitialAction {
+      void operator()(Obj&) const {}
+      void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
+    };
+
+    MockFunction<void(Obj&)> mock;
+    EXPECT_CALL(mock, Call)
+        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}))
+        .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}));
+
+    Obj obj;
+    mock.AsStdFunction()(obj);
+    mock.AsStdFunction()(obj);
+  }
+
+  // Mock action accepts by rvalue reference: the initial actions should receive
+  // a non-const lvalue reference if it wants it, and the final action an rvalue
+  // reference.
+  {
+    struct InitialAction {
+      void operator()(Obj&) const {}
+      void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
+    };
+
+    MockFunction<void(Obj &&)> mock;
+    EXPECT_CALL(mock, Call)
+        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}))
+        .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));
+
+    mock.AsStdFunction()(Obj{});
+    mock.AsStdFunction()(Obj{});
+  }
+
+  // &&-qualified initial actions should also be allowed with WillOnce.
+  {
+    struct InitialAction {
+      void operator()(Obj&) && {}
+    };
+
+    MockFunction<void(Obj&)> mock;
+    EXPECT_CALL(mock, Call)
+        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}));
+
+    Obj obj;
+    mock.AsStdFunction()(obj);
+  }
+
+  {
+    struct InitialAction {
+      void operator()(Obj&) && {}
+    };
+
+    MockFunction<void(Obj &&)> mock;
+    EXPECT_CALL(mock, Call)
+        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));
+
+    mock.AsStdFunction()(Obj{});
+  }
+}
+
+// DoAll should support being used with type-erased Action objects, both through
+// WillOnce and WillRepeatedly.
+TEST(DoAll, SupportsTypeErasedActions) {
+  // With only type-erased actions.
+  const Action<void()> initial_action = [] {};
+  const Action<int()> final_action = [] { return 17; };
+
+  MockFunction<int()> mock;
+  EXPECT_CALL(mock, Call)
+      .WillOnce(DoAll(initial_action, initial_action, final_action))
+      .WillRepeatedly(DoAll(initial_action, initial_action, final_action));
+
+  EXPECT_EQ(17, mock.AsStdFunction()());
+
+  // With &&-qualified and move-only final action.
+  {
+    struct FinalAction {
+      FinalAction() = default;
+      FinalAction(FinalAction&&) = default;
+
+      int operator()() && { return 17; }
+    };
+
+    EXPECT_CALL(mock, Call)
+        .WillOnce(DoAll(initial_action, initial_action, FinalAction{}));
+
+    EXPECT_EQ(17, mock.AsStdFunction()());
+  }
+}
 
 // Tests using WithArgs and with an action that takes 1 argument.
 TEST(WithArgsTest, OneArg) {
@@ -1175,8 +1571,29 @@ TEST(WithArgsTest, ReturnReference) {
 
 TEST(WithArgsTest, InnerActionWithConversion) {
   Action<Derived*()> inner = [] { return nullptr; };
-  Action<Base*(double)> a = testing::WithoutArgs(inner);
-  EXPECT_EQ(nullptr, a.Perform(std::make_tuple(1.1)));
+
+  MockFunction<Base*(double)> mock;
+  EXPECT_CALL(mock, Call)
+      .WillOnce(WithoutArgs(inner))
+      .WillRepeatedly(WithoutArgs(inner));
+
+  EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1));
+  EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1));
+}
+
+// It should be possible to use an &&-qualified inner action as long as the
+// whole shebang is used as an rvalue with WillOnce.
+TEST(WithArgsTest, RefQualifiedInnerAction) {
+  struct SomeAction {
+    int operator()(const int arg) && {
+      EXPECT_EQ(17, arg);
+      return 19;
+    }
+  };
+
+  MockFunction<int(int, int)> mock;
+  EXPECT_CALL(mock, Call).WillOnce(WithArg<1>(SomeAction{}));
+  EXPECT_EQ(19, mock.AsStdFunction()(0, 17));
 }
 
 #if !GTEST_OS_WINDOWS_MOBILE
@@ -1235,7 +1652,7 @@ TEST(ByRefTest, IsCopyable) {
 TEST(ByRefTest, ConstValue) {
   const int n = 0;
   // int& ref = ByRef(n);  // This shouldn't compile - we have a
-                           // negative compilation test to catch it.
+  // negative compilation test to catch it.
   const int& const_ref = ByRef(n);
   EXPECT_EQ(&n, &const_ref);
 }
@@ -1260,7 +1677,7 @@ TEST(ByRefTest, ExplicitType) {
   EXPECT_EQ(&n, &r1);
 
   // ByRef<char>(n);  // This shouldn't compile - we have a negative
-                      // compilation test to catch it.
+  // compilation test to catch it.
 
   Derived d;
   Derived& r2 = ByRef<Derived>(d);
@@ -1375,9 +1792,10 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
   MockClass mock;
   std::unique_ptr<int> i(new int(19));
   EXPECT_CALL(mock_function, Call());
-  EXPECT_CALL(mock, MakeUnique()).WillOnce(DoAll(
-      InvokeWithoutArgs(&mock_function, &testing::MockFunction<void()>::Call),
-      Return(ByMove(std::move(i)))));
+  EXPECT_CALL(mock, MakeUnique())
+      .WillOnce(DoAll(InvokeWithoutArgs(&mock_function,
+                                        &testing::MockFunction<void()>::Call),
+                      Return(ByMove(std::move(i)))));
 
   std::unique_ptr<int> result1 = mock.MakeUnique();
   EXPECT_EQ(19, *result1);
@@ -1387,9 +1805,8 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
   MockClass mock;
 
   // Check default value
-  DefaultValue<std::unique_ptr<int>>::SetFactory([] {
-    return std::unique_ptr<int>(new int(42));
-  });
+  DefaultValue<std::unique_ptr<int>>::SetFactory(
+      [] { return std::unique_ptr<int>(new int(42)); });
   EXPECT_EQ(42, *mock.MakeUnique());
 
   EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
@@ -1449,6 +1866,178 @@ TEST(MockMethodTest, CanTakeMoveOnlyValue) {
   EXPECT_EQ(42, *saved);
 }
 
+// It should be possible to use callables with an &&-qualified call operator
+// with WillOnce, since they will be called only once. This allows actions to
+// contain and manipulate move-only types.
+TEST(MockMethodTest, ActionHasRvalueRefQualifiedCallOperator) {
+  struct Return17 {
+    int operator()() && { return 17; }
+  };
+
+  // Action is directly compatible with mocked function type.
+  {
+    MockFunction<int()> mock;
+    EXPECT_CALL(mock, Call).WillOnce(Return17());
+
+    EXPECT_EQ(17, mock.AsStdFunction()());
+  }
+
+  // Action doesn't want mocked function arguments.
+  {
+    MockFunction<int(int)> mock;
+    EXPECT_CALL(mock, Call).WillOnce(Return17());
+
+    EXPECT_EQ(17, mock.AsStdFunction()(0));
+  }
+}
+
+// Edge case: if an action has both a const-qualified and an &&-qualified call
+// operator, there should be no "ambiguous call" errors. The &&-qualified
+// operator should be used by WillOnce (since it doesn't need to retain the
+// action beyond one call), and the const-qualified one by WillRepeatedly.
+TEST(MockMethodTest, ActionHasMultipleCallOperators) {
+  struct ReturnInt {
+    int operator()() && { return 17; }
+    int operator()() const& { return 19; }
+  };
+
+  // Directly compatible with mocked function type.
+  {
+    MockFunction<int()> mock;
+    EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());
+
+    EXPECT_EQ(17, mock.AsStdFunction()());
+    EXPECT_EQ(19, mock.AsStdFunction()());
+    EXPECT_EQ(19, mock.AsStdFunction()());
+  }
+
+  // Ignores function arguments.
+  {
+    MockFunction<int(int)> mock;
+    EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());
+
+    EXPECT_EQ(17, mock.AsStdFunction()(0));
+    EXPECT_EQ(19, mock.AsStdFunction()(0));
+    EXPECT_EQ(19, mock.AsStdFunction()(0));
+  }
+}
+
+// WillOnce should have no problem coping with a move-only action, whether it is
+// &&-qualified or not.
+TEST(MockMethodTest, MoveOnlyAction) {
+  // &&-qualified
+  {
+    struct Return17 {
+      Return17() = default;
+      Return17(Return17&&) = default;
+
+      Return17(const Return17&) = delete;
+      Return17 operator=(const Return17&) = delete;
+
+      int operator()() && { return 17; }
+    };
+
+    MockFunction<int()> mock;
+    EXPECT_CALL(mock, Call).WillOnce(Return17());
+    EXPECT_EQ(17, mock.AsStdFunction()());
+  }
+
+  // Not &&-qualified
+  {
+    struct Return17 {
+      Return17() = default;
+      Return17(Return17&&) = default;
+
+      Return17(const Return17&) = delete;
+      Return17 operator=(const Return17&) = delete;
+
+      int operator()() const { return 17; }
+    };
+
+    MockFunction<int()> mock;
+    EXPECT_CALL(mock, Call).WillOnce(Return17());
+    EXPECT_EQ(17, mock.AsStdFunction()());
+  }
+}
+
+// It should be possible to use an action that returns a value with a mock
+// function that doesn't, both through WillOnce and WillRepeatedly.
+TEST(MockMethodTest, ActionReturnsIgnoredValue) {
+  struct ReturnInt {
+    int operator()() const { return 0; }
+  };
+
+  MockFunction<void()> mock;
+  EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());
+
+  mock.AsStdFunction()();
+  mock.AsStdFunction()();
+}
+
+// Despite the fanciness around move-only actions and so on, it should still be
+// possible to hand an lvalue reference to a copyable action to WillOnce.
+TEST(MockMethodTest, WillOnceCanAcceptLvalueReference) {
+  MockFunction<int()> mock;
+
+  const auto action = [] { return 17; };
+  EXPECT_CALL(mock, Call).WillOnce(action);
+
+  EXPECT_EQ(17, mock.AsStdFunction()());
+}
+
+// A callable that doesn't use SFINAE to restrict its call operator's overload
+// set, but is still picky about which arguments it will accept.
+struct StaticAssertSingleArgument {
+  template <typename... Args>
+  static constexpr bool CheckArgs() {
+    static_assert(sizeof...(Args) == 1, "");
+    return true;
+  }
+
+  template <typename... Args, bool = CheckArgs<Args...>()>
+  int operator()(Args...) const {
+    return 17;
+  }
+};
+
+// WillOnce and WillRepeatedly should both work fine with naïve implementations
+// of actions that don't use SFINAE to limit the overload set for their call
+// operator. If they are compatible with the actual mocked signature, we
+// shouldn't probe them with no arguments and trip a static_assert.
+TEST(MockMethodTest, ActionSwallowsAllArguments) {
+  MockFunction<int(int)> mock;
+  EXPECT_CALL(mock, Call)
+      .WillOnce(StaticAssertSingleArgument{})
+      .WillRepeatedly(StaticAssertSingleArgument{});
+
+  EXPECT_EQ(17, mock.AsStdFunction()(0));
+  EXPECT_EQ(17, mock.AsStdFunction()(0));
+}
+
+struct ActionWithTemplatedConversionOperators {
+  template <typename... Args>
+  operator OnceAction<int(Args...)>() && {  // NOLINT
+    return [] { return 17; };
+  }
+
+  template <typename... Args>
+  operator Action<int(Args...)>() const {  // NOLINT
+    return [] { return 19; };
+  }
+};
+
+// It should be fine to hand both WillOnce and WillRepeatedly a function that
+// defines templated conversion operators to OnceAction and Action. WillOnce
+// should prefer the OnceAction version.
+TEST(MockMethodTest, ActionHasTemplatedConversionOperators) {
+  MockFunction<int()> mock;
+  EXPECT_CALL(mock, Call)
+      .WillOnce(ActionWithTemplatedConversionOperators{})
+      .WillRepeatedly(ActionWithTemplatedConversionOperators{});
+
+  EXPECT_EQ(17, mock.AsStdFunction()());
+  EXPECT_EQ(19, mock.AsStdFunction()());
+}
 
 // Tests for std::function based action.
 
@@ -1463,7 +2052,9 @@ int Deref(std::unique_ptr<int> ptr) { return *ptr; }
 
 struct Double {
   template <typename T>
-  T operator()(T t) { return 2 * t; }
+  T operator()(T t) {
+    return 2 * t;
+  }
 };
 
 std::unique_ptr<int> UniqueInt(int i) {
@@ -1532,8 +2123,9 @@ TEST(FunctorActionTest, TypeConversion) {
 
 TEST(FunctorActionTest, UnusedArguments) {
   // Verify that users can ignore uninteresting arguments.
-  Action<int(int, double y, double z)> a =
-      [](int i, Unused, Unused) { return 2 * i; };
+  Action<int(int, double y, double z)> a = [](int i, Unused, Unused) {
+    return 2 * i;
+  };
   std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44);
   EXPECT_EQ(6, a.Perform(dummy));
 }
@@ -1552,9 +2144,7 @@ TEST(MoveOnlyArgumentsTest, ReturningActions) {
   EXPECT_EQ(x, 3);
 }
 
-ACTION(ReturnArity) {
-  return std::tuple_size<args_type>::value;
-}
+ACTION(ReturnArity) { return std::tuple_size<args_type>::value; }
 
 TEST(ActionMacro, LargeArity) {
   EXPECT_EQ(
@@ -1573,11 +2163,5 @@ TEST(ActionMacro, LargeArity) {
                                    14, 15, 16, 17, 18, 19)));
 }
 
-}  // Unnamed namespace
-
-#ifdef _MSC_VER
-#if _MSC_VER == 1900
-#  pragma warning(pop)
-#endif
-#endif
-
+}  // namespace
+}  // namespace testing
index ca97cae249246ba74853720ae4a50e0b28abf638..cdd99563538745945c8d69daba4f63b0e0bcdcef 100644 (file)
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file tests the built-in cardinalities.
 
 #include "gmock/gmock.h"
-#include "gtest/gtest.h"
 #include "gtest/gtest-spi.h"
+#include "gtest/gtest.h"
 
 namespace {
 
@@ -55,13 +54,12 @@ class MockFoo {
   MOCK_METHOD0(Bar, int());  // NOLINT
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
+  MockFoo(const MockFoo&) = delete;
+  MockFoo& operator=(const MockFoo&) = delete;
 };
 
 // Tests that Cardinality objects can be default constructed.
-TEST(CardinalityTest, IsDefaultConstructable) {
-  Cardinality c;
-}
+TEST(CardinalityTest, IsDefaultConstructable) { Cardinality c; }
 
 // Tests that Cardinality objects are copyable.
 TEST(CardinalityTest, IsCopyable) {
@@ -119,8 +117,7 @@ TEST(AnyNumber, Works) {
 
   stringstream ss;
   c.DescribeTo(&ss);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called any number of times",
-                      ss.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "called any number of times", ss.str());
 }
 
 TEST(AnyNumberTest, HasCorrectBounds) {
@@ -132,9 +129,11 @@ TEST(AnyNumberTest, HasCorrectBounds) {
 // Tests AtLeast(n).
 
 TEST(AtLeastTest, OnNegativeNumber) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    AtLeast(-1);
-  }, "The invocation lower bound must be >= 0");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        AtLeast(-1);
+      },
+      "The invocation lower bound must be >= 0");
 }
 
 TEST(AtLeastTest, OnZero) {
@@ -147,8 +146,7 @@ TEST(AtLeastTest, OnZero) {
 
   stringstream ss;
   c.DescribeTo(&ss);
-  EXPECT_PRED_FORMAT2(IsSubstring, "any number of times",
-                      ss.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "any number of times", ss.str());
 }
 
 TEST(AtLeastTest, OnPositiveNumber) {
@@ -164,18 +162,15 @@ TEST(AtLeastTest, OnPositiveNumber) {
 
   stringstream ss1;
   AtLeast(1).DescribeTo(&ss1);
-  EXPECT_PRED_FORMAT2(IsSubstring, "at least once",
-                      ss1.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "at least once", ss1.str());
 
   stringstream ss2;
   c.DescribeTo(&ss2);
-  EXPECT_PRED_FORMAT2(IsSubstring, "at least twice",
-                      ss2.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "at least twice", ss2.str());
 
   stringstream ss3;
   AtLeast(3).DescribeTo(&ss3);
-  EXPECT_PRED_FORMAT2(IsSubstring, "at least 3 times",
-                      ss3.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "at least 3 times", ss3.str());
 }
 
 TEST(AtLeastTest, HasCorrectBounds) {
@@ -187,9 +182,11 @@ TEST(AtLeastTest, HasCorrectBounds) {
 // Tests AtMost(n).
 
 TEST(AtMostTest, OnNegativeNumber) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    AtMost(-1);
-  }, "The invocation upper bound must be >= 0");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        AtMost(-1);
+      },
+      "The invocation upper bound must be >= 0");
 }
 
 TEST(AtMostTest, OnZero) {
@@ -202,8 +199,7 @@ TEST(AtMostTest, OnZero) {
 
   stringstream ss;
   c.DescribeTo(&ss);
-  EXPECT_PRED_FORMAT2(IsSubstring, "never called",
-                      ss.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str());
 }
 
 TEST(AtMostTest, OnPositiveNumber) {
@@ -219,18 +215,15 @@ TEST(AtMostTest, OnPositiveNumber) {
 
   stringstream ss1;
   AtMost(1).DescribeTo(&ss1);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called at most once",
-                      ss1.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "called at most once", ss1.str());
 
   stringstream ss2;
   c.DescribeTo(&ss2);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice",
-                      ss2.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", ss2.str());
 
   stringstream ss3;
   AtMost(3).DescribeTo(&ss3);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called at most 3 times",
-                      ss3.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "called at most 3 times", ss3.str());
 }
 
 TEST(AtMostTest, HasCorrectBounds) {
@@ -242,22 +235,28 @@ TEST(AtMostTest, HasCorrectBounds) {
 // Tests Between(m, n).
 
 TEST(BetweenTest, OnNegativeStart) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    Between(-1, 2);
-  }, "The invocation lower bound must be >= 0, but is actually -1");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        Between(-1, 2);
+      },
+      "The invocation lower bound must be >= 0, but is actually -1");
 }
 
 TEST(BetweenTest, OnNegativeEnd) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    Between(1, -2);
-  }, "The invocation upper bound must be >= 0, but is actually -2");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        Between(1, -2);
+      },
+      "The invocation upper bound must be >= 0, but is actually -2");
 }
 
 TEST(BetweenTest, OnStartBiggerThanEnd) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    Between(2, 1);
-  }, "The invocation upper bound (1) must be >= "
-     "the invocation lower bound (2)");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        Between(2, 1);
+      },
+      "The invocation upper bound (1) must be >= "
+      "the invocation lower bound (2)");
 }
 
 TEST(BetweenTest, OnZeroStartAndZeroEnd) {
@@ -271,8 +270,7 @@ TEST(BetweenTest, OnZeroStartAndZeroEnd) {
 
   stringstream ss;
   c.DescribeTo(&ss);
-  EXPECT_PRED_FORMAT2(IsSubstring, "never called",
-                      ss.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str());
 }
 
 TEST(BetweenTest, OnZeroStartAndNonZeroEnd) {
@@ -289,8 +287,7 @@ TEST(BetweenTest, OnZeroStartAndNonZeroEnd) {
 
   stringstream ss;
   c.DescribeTo(&ss);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice",
-                      ss.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", ss.str());
 }
 
 TEST(BetweenTest, OnSameStartAndEnd) {
@@ -307,8 +304,7 @@ TEST(BetweenTest, OnSameStartAndEnd) {
 
   stringstream ss;
   c.DescribeTo(&ss);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times",
-                      ss.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", ss.str());
 }
 
 TEST(BetweenTest, OnDifferentStartAndEnd) {
@@ -328,8 +324,7 @@ TEST(BetweenTest, OnDifferentStartAndEnd) {
 
   stringstream ss;
   c.DescribeTo(&ss);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called between 3 and 5 times",
-                      ss.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "called between 3 and 5 times", ss.str());
 }
 
 TEST(BetweenTest, HasCorrectBounds) {
@@ -341,9 +336,11 @@ TEST(BetweenTest, HasCorrectBounds) {
 // Tests Exactly(n).
 
 TEST(ExactlyTest, OnNegativeNumber) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    Exactly(-1);
-  }, "The invocation lower bound must be >= 0");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        Exactly(-1);
+      },
+      "The invocation lower bound must be >= 0");
 }
 
 TEST(ExactlyTest, OnZero) {
@@ -356,8 +353,7 @@ TEST(ExactlyTest, OnZero) {
 
   stringstream ss;
   c.DescribeTo(&ss);
-  EXPECT_PRED_FORMAT2(IsSubstring, "never called",
-                      ss.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str());
 }
 
 TEST(ExactlyTest, OnPositiveNumber) {
@@ -370,18 +366,15 @@ TEST(ExactlyTest, OnPositiveNumber) {
 
   stringstream ss1;
   Exactly(1).DescribeTo(&ss1);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called once",
-                      ss1.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "called once", ss1.str());
 
   stringstream ss2;
   c.DescribeTo(&ss2);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called twice",
-                      ss2.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "called twice", ss2.str());
 
   stringstream ss3;
   Exactly(3).DescribeTo(&ss3);
-  EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times",
-                      ss3.str());
+  EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", ss3.str());
 }
 
 TEST(ExactlyTest, HasCorrectBounds) {
index cf76fa99f286fe4eeb85d1d2181c04f4074b7417..286115fef0024bbfe2f76e4cf82e975797542a37 100644 (file)
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
+// Silence C4503 (decorated name length exceeded) for MSVC.
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4503)
+#endif
 
 // Google Mock - a framework for writing C++ mock classes.
 //
@@ -37,7 +42,7 @@
 // MSDN says the header file to be included for STDMETHOD is BaseTyps.h but
 // we are getting compiler errors if we use basetyps.h, hence including
 // objbase.h for definition of STDMETHOD.
-# include <objbase.h>
+#include <objbase.h>
 #endif  // GTEST_OS_WINDOWS
 
 #include <functional>
@@ -65,7 +70,7 @@ using testing::Return;
 using testing::ReturnRef;
 using testing::TypedEq;
 
-template<typename T>
+template <typename T>
 class TemplatedCopyable {
  public:
   TemplatedCopyable() {}
@@ -82,7 +87,7 @@ class FooInterface {
 
   virtual int Nullary() = 0;
   virtual bool Unary(int x) = 0;
-  virtual long Binary(short x, int y) = 0;  // NOLINT
+  virtual long Binary(short x, int y) = 0;                     // NOLINT
   virtual int Decimal(bool b, char c, short d, int e, long f,  // NOLINT
                       float g, double h, unsigned i, char* j,
                       const std::string& k) = 0;
@@ -133,8 +138,8 @@ class FooInterface {
 // signature. This was fixed in Visual Studio 2008. However, the compiler
 // still emits a warning that alerts about this change in behavior.
 #ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable : 4373)
+#pragma warning(push)
+#pragma warning(disable : 4373)
 #endif
 class MockFoo : public FooInterface {
  public:
@@ -203,7 +208,8 @@ class MockFoo : public FooInterface {
   MOCK_METHOD(int, RefQualifiedOverloaded, (), (ref(&&), override));
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
+  MockFoo(const MockFoo&) = delete;
+  MockFoo& operator=(const MockFoo&) = delete;
 };
 
 class LegacyMockFoo : public FooInterface {
@@ -275,11 +281,12 @@ class LegacyMockFoo : public FooInterface {
   int RefQualifiedOverloaded() && override { return 0; }
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockFoo);
+  LegacyMockFoo(const LegacyMockFoo&) = delete;
+  LegacyMockFoo& operator=(const LegacyMockFoo&) = delete;
 };
 
 #ifdef _MSC_VER
-# pragma warning(pop)
+#pragma warning(pop)
 #endif
 
 template <class T>
@@ -493,7 +500,8 @@ class MockB {
   MOCK_METHOD(void, DoB, ());
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
+  MockB(const MockB&) = delete;
+  MockB& operator=(const MockB&) = delete;
 };
 
 class LegacyMockB {
@@ -503,7 +511,8 @@ class LegacyMockB {
   MOCK_METHOD0(DoB, void());
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockB);
+  LegacyMockB(const LegacyMockB&) = delete;
+  LegacyMockB& operator=(const LegacyMockB&) = delete;
 };
 
 template <typename T>
@@ -558,7 +567,8 @@ class MockStack : public StackInterface<T> {
   MOCK_METHOD((std::map<int, int>), ReturnTypeWithComma, (int), (const));
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack);
+  MockStack(const MockStack&) = delete;
+  MockStack& operator=(const MockStack&) = delete;
 };
 
 template <typename T>
@@ -576,7 +586,8 @@ class LegacyMockStack : public StackInterface<T> {
   MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map<int, int>(int));  // NOLINT
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockStack);
+  LegacyMockStack(const LegacyMockStack&) = delete;
+  LegacyMockStack& operator=(const LegacyMockStack&) = delete;
 };
 
 template <typename T>
@@ -595,10 +606,8 @@ TYPED_TEST(TemplateMockTest, Works) {
       .WillOnce(Return(0));
   EXPECT_CALL(mock, Push(_));
   int n = 5;
-  EXPECT_CALL(mock, GetTop())
-      .WillOnce(ReturnRef(n));
-  EXPECT_CALL(mock, Pop())
-      .Times(AnyNumber());
+  EXPECT_CALL(mock, GetTop()).WillOnce(ReturnRef(n));
+  EXPECT_CALL(mock, Pop()).Times(AnyNumber());
 
   EXPECT_EQ(0, mock.GetSize());
   mock.Push(5);
@@ -612,10 +621,8 @@ TYPED_TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) {
   TypeParam mock;
 
   const std::map<int, int> a_map;
-  EXPECT_CALL(mock, ReturnTypeWithComma())
-      .WillOnce(Return(a_map));
-  EXPECT_CALL(mock, ReturnTypeWithComma(1))
-      .WillOnce(Return(a_map));
+  EXPECT_CALL(mock, ReturnTypeWithComma()).WillOnce(Return(a_map));
+  EXPECT_CALL(mock, ReturnTypeWithComma(1)).WillOnce(Return(a_map));
 
   EXPECT_EQ(a_map, mock.ReturnTypeWithComma());
   EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1));
@@ -650,7 +657,8 @@ class MockStackWithCallType : public StackInterfaceWithCallType<T> {
               (Calltype(STDMETHODCALLTYPE), override, const));
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStackWithCallType);
+  MockStackWithCallType(const MockStackWithCallType&) = delete;
+  MockStackWithCallType& operator=(const MockStackWithCallType&) = delete;
 };
 
 template <typename T>
@@ -664,7 +672,9 @@ class LegacyMockStackWithCallType : public StackInterfaceWithCallType<T> {
   MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTop, const T&());
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockStackWithCallType);
+  LegacyMockStackWithCallType(const LegacyMockStackWithCallType&) = delete;
+  LegacyMockStackWithCallType& operator=(const LegacyMockStackWithCallType&) =
+      delete;
 };
 
 template <typename T>
@@ -685,10 +695,8 @@ TYPED_TEST(TemplateMockTestWithCallType, Works) {
       .WillOnce(Return(0));
   EXPECT_CALL(mock, Push(_));
   int n = 5;
-  EXPECT_CALL(mock, GetTop())
-      .WillOnce(ReturnRef(n));
-  EXPECT_CALL(mock, Pop())
-      .Times(AnyNumber());
+  EXPECT_CALL(mock, GetTop()).WillOnce(ReturnRef(n));
+  EXPECT_CALL(mock, Pop()).Times(AnyNumber());
 
   EXPECT_EQ(0, mock.GetSize());
   mock.Push(5);
@@ -716,7 +724,9 @@ class MockOverloadedOnArgNumber {
   MY_MOCK_METHODS1_;
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber);
+  MockOverloadedOnArgNumber(const MockOverloadedOnArgNumber&) = delete;
+  MockOverloadedOnArgNumber& operator=(const MockOverloadedOnArgNumber&) =
+      delete;
 };
 
 class LegacyMockOverloadedOnArgNumber {
@@ -726,7 +736,10 @@ class LegacyMockOverloadedOnArgNumber {
   LEGACY_MY_MOCK_METHODS1_;
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockOverloadedOnArgNumber);
+  LegacyMockOverloadedOnArgNumber(const LegacyMockOverloadedOnArgNumber&) =
+      delete;
+  LegacyMockOverloadedOnArgNumber& operator=(
+      const LegacyMockOverloadedOnArgNumber&) = delete;
 };
 
 template <typename T>
@@ -747,9 +760,9 @@ TYPED_TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
   EXPECT_TRUE(mock.Overloaded(true, 1));
 }
 
-#define MY_MOCK_METHODS2_ \
-    MOCK_CONST_METHOD1(Overloaded, int(int n)); \
-    MOCK_METHOD1(Overloaded, int(int n))
+#define MY_MOCK_METHODS2_                     \
+  MOCK_CONST_METHOD1(Overloaded, int(int n)); \
+  MOCK_METHOD1(Overloaded, int(int n))
 
 class MockOverloadedOnConstness {
  public:
@@ -758,7 +771,9 @@ class MockOverloadedOnConstness {
   MY_MOCK_METHODS2_;
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnConstness);
+  MockOverloadedOnConstness(const MockOverloadedOnConstness&) = delete;
+  MockOverloadedOnConstness& operator=(const MockOverloadedOnConstness&) =
+      delete;
 };
 
 TEST(MockMethodOverloadedMockMethodTest, CanOverloadOnConstnessInMacroBody) {
@@ -779,9 +794,7 @@ TEST(MockMethodMockFunctionTest, WorksForVoidNullary) {
 
 TEST(MockMethodMockFunctionTest, WorksForNonVoidNullary) {
   MockFunction<int()> foo;
-  EXPECT_CALL(foo, Call())
-      .WillOnce(Return(1))
-      .WillOnce(Return(2));
+  EXPECT_CALL(foo, Call()).WillOnce(Return(1)).WillOnce(Return(2));
   EXPECT_EQ(1, foo.Call());
   EXPECT_EQ(2, foo.Call());
 }
@@ -794,19 +807,17 @@ TEST(MockMethodMockFunctionTest, WorksForVoidUnary) {
 
 TEST(MockMethodMockFunctionTest, WorksForNonVoidBinary) {
   MockFunction<int(bool, int)> foo;
-  EXPECT_CALL(foo, Call(false, 42))
-      .WillOnce(Return(1))
-      .WillOnce(Return(2));
-  EXPECT_CALL(foo, Call(true, Ge(100)))
-      .WillOnce(Return(3));
+  EXPECT_CALL(foo, Call(false, 42)).WillOnce(Return(1)).WillOnce(Return(2));
+  EXPECT_CALL(foo, Call(true, Ge(100))).WillOnce(Return(3));
   EXPECT_EQ(1, foo.Call(false, 42));
   EXPECT_EQ(2, foo.Call(false, 42));
   EXPECT_EQ(3, foo.Call(true, 120));
 }
 
 TEST(MockMethodMockFunctionTest, WorksFor10Arguments) {
-  MockFunction<int(bool a0, char a1, int a2, int a3, int a4,
-                   int a5, int a6, char a7, int a8, bool a9)> foo;
+  MockFunction<int(bool a0, char a1, int a2, int a3, int a4, int a5, int a6,
+                   char a7, int a8, bool a9)>
+      foo;
   EXPECT_CALL(foo, Call(_, 'a', _, _, _, _, _, _, _, _))
       .WillOnce(Return(1))
       .WillOnce(Return(2));
@@ -816,9 +827,7 @@ TEST(MockMethodMockFunctionTest, WorksFor10Arguments) {
 
 TEST(MockMethodMockFunctionTest, AsStdFunction) {
   MockFunction<int(int)> foo;
-  auto call = [](const std::function<int(int)> &f, int i) {
-    return f(i);
-  };
+  auto call = [](const std::function<int(int)>& f, int i) { return f(i); };
   EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1));
   EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2));
   EXPECT_EQ(-1, call(foo.AsStdFunction(), 1));
@@ -836,10 +845,8 @@ TEST(MockMethodMockFunctionTest, AsStdFunctionReturnsReference) {
 }
 
 TEST(MockMethodMockFunctionTest, AsStdFunctionWithReferenceParameter) {
-  MockFunction<int(int &)> foo;
-  auto call = [](const std::function<int(int& )> &f, int &i) {
-    return f(i);
-  };
+  MockFunction<int(int&)> foo;
+  auto call = [](const std::function<int(int&)>& f, int& i) { return f(i); };
   int i = 42;
   EXPECT_CALL(foo, Call(i)).WillOnce(Return(-1));
   EXPECT_EQ(-1, call(foo.AsStdFunction(), i));
@@ -888,8 +895,7 @@ TYPED_TEST(
 }
 
 template <typename F>
-struct AlternateCallable {
-};
+struct AlternateCallable {};
 
 TYPED_TEST(MockMethodMockFunctionSignatureTest,
            IsMockFunctionTemplateArgumentDeducedForAlternateCallable) {
@@ -898,16 +904,14 @@ TYPED_TEST(MockMethodMockFunctionSignatureTest,
   EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo));
 }
 
-TYPED_TEST(
-    MockMethodMockFunctionSignatureTest,
-    IsMockFunctionCallMethodSignatureTheSameForAlternateCallable) {
+TYPED_TEST(MockMethodMockFunctionSignatureTest,
+           IsMockFunctionCallMethodSignatureTheSameForAlternateCallable) {
   using ForRawSignature = decltype(&MockFunction<TypeParam>::Call);
   using ForStdFunction =
       decltype(&MockFunction<std::function<TypeParam>>::Call);
   EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value));
 }
 
-
 struct MockMethodSizes0 {
   MOCK_METHOD(void, func, ());
 };
@@ -925,22 +929,21 @@ struct MockMethodSizes4 {
 };
 
 struct LegacyMockMethodSizes0 {
-    MOCK_METHOD0(func, void());
+  MOCK_METHOD0(func, void());
 };
 struct LegacyMockMethodSizes1 {
-    MOCK_METHOD1(func, void(int));
+  MOCK_METHOD1(func, void(int));
 };
 struct LegacyMockMethodSizes2 {
-    MOCK_METHOD2(func, void(int, int));
+  MOCK_METHOD2(func, void(int, int));
 };
 struct LegacyMockMethodSizes3 {
-    MOCK_METHOD3(func, void(int, int, int));
+  MOCK_METHOD3(func, void(int, int, int));
 };
 struct LegacyMockMethodSizes4 {
-    MOCK_METHOD4(func, void(int, int, int, int));
+  MOCK_METHOD4(func, void(int, int, int, int));
 };
 
-
 TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) {
   EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1));
   EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2));
index 0d15e8f482c7c7900ca81115fa8d312b75639f53..932bece5afed52af7e85d5d100a35f4d589955d0 100644 (file)
@@ -27,7 +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.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file tests the internal utilities.
@@ -58,7 +57,7 @@
 #undef GTEST_IMPLEMENTATION_
 
 #if GTEST_OS_CYGWIN
-# include <sys/types.h>  // For ssize_t. NOLINT
+#include <sys/types.h>  // For ssize_t. NOLINT
 #endif
 
 namespace proto2 {
@@ -70,24 +69,23 @@ namespace internal {
 
 namespace {
 
-TEST(JoinAsTupleTest, JoinsEmptyTuple) {
-  EXPECT_EQ("", JoinAsTuple(Strings()));
+TEST(JoinAsKeyValueTupleTest, JoinsEmptyTuple) {
+  EXPECT_EQ("", JoinAsKeyValueTuple({}, Strings()));
 }
 
-TEST(JoinAsTupleTest, JoinsOneTuple) {
-  const char* fields[] = {"1"};
-  EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
+TEST(JoinAsKeyValueTupleTest, JoinsOneTuple) {
+  EXPECT_EQ("(a: 1)", JoinAsKeyValueTuple({"a"}, {"1"}));
 }
 
-TEST(JoinAsTupleTest, JoinsTwoTuple) {
-  const char* fields[] = {"1", "a"};
-  EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
+TEST(JoinAsKeyValueTupleTest, JoinsTwoTuple) {
+  EXPECT_EQ("(a: 1, b: 2)", JoinAsKeyValueTuple({"a", "b"}, {"1", "2"}));
 }
 
-TEST(JoinAsTupleTest, JoinsTenTuple) {
-  const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
-  EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
-            JoinAsTuple(Strings(fields, fields + 10)));
+TEST(JoinAsKeyValueTupleTest, JoinsTenTuple) {
+  EXPECT_EQ(
+      "(a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10)",
+      JoinAsKeyValueTuple({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"},
+                          {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}));
 }
 
 TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsNoWord) {
@@ -140,6 +138,12 @@ TEST(GetRawPointerTest, WorksForRawPointers) {
   EXPECT_EQ(&n, GetRawPointer(&n));
 }
 
+TEST(GetRawPointerTest, WorksForStdReferenceWrapper) {
+  int n = 1;
+  EXPECT_EQ(&n, GetRawPointer(std::ref(n)));
+  EXPECT_EQ(&n, GetRawPointer(std::cref(n)));
+}
+
 // Tests KindOf<T>.
 
 class Base {};
@@ -150,19 +154,19 @@ TEST(KindOfTest, Bool) {
 }
 
 TEST(KindOfTest, Integer) {
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long long));  // NOLINT
+  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char));                // NOLINT
+  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char));         // NOLINT
+  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char));       // NOLINT
+  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short));               // NOLINT
+  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short));      // NOLINT
+  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int));                 // NOLINT
+  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int));        // NOLINT
+  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long));                // NOLINT
+  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long));       // NOLINT
+  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long long));           // NOLINT
   EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long long));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t));  // NOLINT
-  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t));  // NOLINT
+  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t));             // NOLINT
+  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t));              // NOLINT
 #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN
   // ssize_t is not defined on Windows and possibly some other OSes.
   EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t));  // NOLINT
@@ -170,15 +174,15 @@ TEST(KindOfTest, Integer) {
 }
 
 TEST(KindOfTest, FloatingPoint) {
-  EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float));  // NOLINT
-  EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double));  // NOLINT
+  EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float));        // NOLINT
+  EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double));       // NOLINT
   EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(long double));  // NOLINT
 }
 
 TEST(KindOfTest, Other) {
-  EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*));  // NOLINT
+  EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*));   // NOLINT
   EXPECT_EQ(kOther, GMOCK_KIND_OF_(char**));  // NOLINT
-  EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base));  // NOLINT
+  EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base));    // NOLINT
 }
 
 // Tests LosslessArithmeticConvertible<T, U>.
@@ -209,26 +213,26 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) {
   EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value));
 
   // Unsigned => larger unsigned is fine.
-  EXPECT_TRUE((LosslessArithmeticConvertible<
-               unsigned short, uint64_t>::value));  // NOLINT
+  EXPECT_TRUE((LosslessArithmeticConvertible<unsigned short,
+                                             uint64_t>::value));  // NOLINT
 
   // Signed => unsigned is not fine.
-  EXPECT_FALSE((LosslessArithmeticConvertible<
-                short, uint64_t>::value));  // NOLINT
-  EXPECT_FALSE((LosslessArithmeticConvertible<
-      signed char, unsigned int>::value));  // NOLINT
+  EXPECT_FALSE(
+      (LosslessArithmeticConvertible<short, uint64_t>::value));  // NOLINT
+  EXPECT_FALSE((LosslessArithmeticConvertible<signed char,
+                                              unsigned int>::value));  // NOLINT
 
   // Same size and same signedness: fine too.
-  EXPECT_TRUE((LosslessArithmeticConvertible<
-               unsigned char, unsigned char>::value));
+  EXPECT_TRUE(
+      (LosslessArithmeticConvertible<unsigned char, unsigned char>::value));
   EXPECT_TRUE((LosslessArithmeticConvertible<int, int>::value));
   EXPECT_TRUE((LosslessArithmeticConvertible<wchar_t, wchar_t>::value));
-  EXPECT_TRUE((LosslessArithmeticConvertible<
-               unsigned long, unsigned long>::value));  // NOLINT
+  EXPECT_TRUE((LosslessArithmeticConvertible<unsigned long,
+                                             unsigned long>::value));  // NOLINT
 
   // Same size, different signedness: not fine.
-  EXPECT_FALSE((LosslessArithmeticConvertible<
-                unsigned char, signed char>::value));
+  EXPECT_FALSE(
+      (LosslessArithmeticConvertible<unsigned char, signed char>::value));
   EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value));
   EXPECT_FALSE((LosslessArithmeticConvertible<uint64_t, int64_t>::value));
 
@@ -243,8 +247,8 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) {
   // the format of the latter is implementation-defined.
   EXPECT_FALSE((LosslessArithmeticConvertible<char, float>::value));
   EXPECT_FALSE((LosslessArithmeticConvertible<int, double>::value));
-  EXPECT_FALSE((LosslessArithmeticConvertible<
-                short, long double>::value));  // NOLINT
+  EXPECT_FALSE(
+      (LosslessArithmeticConvertible<short, long double>::value));  // NOLINT
 }
 
 TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) {
@@ -272,7 +276,7 @@ TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) {
   EXPECT_FALSE((LosslessArithmeticConvertible<double, float>::value));
   GTEST_INTENTIONAL_CONST_COND_PUSH_()
   if (sizeof(double) == sizeof(long double)) {  // NOLINT
-  GTEST_INTENTIONAL_CONST_COND_POP_()
+    GTEST_INTENTIONAL_CONST_COND_POP_()
     // In some implementations (e.g. MSVC), double and long double
     // have the same size.
     EXPECT_TRUE((LosslessArithmeticConvertible<long double, double>::value));
@@ -291,7 +295,7 @@ TEST(TupleMatchesTest, WorksForSize0) {
 }
 
 TEST(TupleMatchesTest, WorksForSize1) {
-  std::tuple<Matcher<int> > matchers(Eq(1));
+  std::tuple<Matcher<int>> matchers(Eq(1));
   std::tuple<int> values1(1), values2(2);
 
   EXPECT_TRUE(TupleMatches(matchers, values1));
@@ -299,7 +303,7 @@ TEST(TupleMatchesTest, WorksForSize1) {
 }
 
 TEST(TupleMatchesTest, WorksForSize2) {
-  std::tuple<Matcher<int>, Matcher<char> > matchers(Eq(1), Eq('a'));
+  std::tuple<Matcher<int>, Matcher<char>> matchers(Eq(1), Eq('a'));
   std::tuple<int, char> values1(1, 'a'), values2(1, 'b'), values3(2, 'a'),
       values4(2, 'b');
 
@@ -312,7 +316,7 @@ TEST(TupleMatchesTest, WorksForSize2) {
 TEST(TupleMatchesTest, WorksForSize5) {
   std::tuple<Matcher<int>, Matcher<char>, Matcher<bool>,
              Matcher<long>,  // NOLINT
-             Matcher<std::string> >
+             Matcher<std::string>>
       matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi"));
   std::tuple<int, char, bool, long, std::string>  // NOLINT
       values1(1, 'a', true, 2L, "hi"), values2(1, 'a', true, 2L, "hello"),
@@ -331,13 +335,10 @@ TEST(AssertTest, SucceedsOnTrue) {
 
 // Tests that Assert(false, ...) generates a fatal failure.
 TEST(AssertTest, FailsFatallyOnFalse) {
-  EXPECT_DEATH_IF_SUPPORTED({
-    Assert(false, __FILE__, __LINE__, "This should fail.");
-  }, "");
+  EXPECT_DEATH_IF_SUPPORTED(
+      { Assert(false, __FILE__, __LINE__, "This should fail."); }, "");
 
-  EXPECT_DEATH_IF_SUPPORTED({
-    Assert(false, __FILE__, __LINE__);
-  }, "");
+  EXPECT_DEATH_IF_SUPPORTED({ Assert(false, __FILE__, __LINE__); }, "");
 }
 
 // Tests that Expect(true, ...) succeeds.
@@ -348,40 +349,44 @@ TEST(ExpectTest, SucceedsOnTrue) {
 
 // Tests that Expect(false, ...) generates a non-fatal failure.
 TEST(ExpectTest, FailsNonfatallyOnFalse) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    Expect(false, __FILE__, __LINE__, "This should fail.");
-  }, "This should fail");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        Expect(false, __FILE__, __LINE__, "This should fail.");
+      },
+      "This should fail");
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    Expect(false, __FILE__, __LINE__);
-  }, "Expectation failed");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        Expect(false, __FILE__, __LINE__);
+      },
+      "Expectation failed");
 }
 
 // Tests LogIsVisible().
 
 class LogIsVisibleTest : public ::testing::Test {
  protected:
-  void SetUp() override { original_verbose_ = GMOCK_FLAG(verbose); }
+  void SetUp() override { original_verbose_ = GMOCK_FLAG_GET(verbose); }
 
-  void TearDown() override { GMOCK_FLAG(verbose) = original_verbose_; }
+  void TearDown() override { GMOCK_FLAG_SET(verbose, original_verbose_); }
 
   std::string original_verbose_;
 };
 
 TEST_F(LogIsVisibleTest, AlwaysReturnsTrueIfVerbosityIsInfo) {
-  GMOCK_FLAG(verbose) = kInfoVerbosity;
+  GMOCK_FLAG_SET(verbose, kInfoVerbosity);
   EXPECT_TRUE(LogIsVisible(kInfo));
   EXPECT_TRUE(LogIsVisible(kWarning));
 }
 
 TEST_F(LogIsVisibleTest, AlwaysReturnsFalseIfVerbosityIsError) {
-  GMOCK_FLAG(verbose) = kErrorVerbosity;
+  GMOCK_FLAG_SET(verbose, kErrorVerbosity);
   EXPECT_FALSE(LogIsVisible(kInfo));
   EXPECT_FALSE(LogIsVisible(kWarning));
 }
 
 TEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) {
-  GMOCK_FLAG(verbose) = kWarningVerbosity;
+  GMOCK_FLAG_SET(verbose, kWarningVerbosity);
   EXPECT_FALSE(LogIsVisible(kInfo));
   EXPECT_TRUE(LogIsVisible(kWarning));
 }
@@ -394,31 +399,31 @@ TEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) {
 // and log severity.
 void TestLogWithSeverity(const std::string& verbosity, LogSeverity severity,
                          bool should_print) {
-  const std::string old_flag = GMOCK_FLAG(verbose);
-  GMOCK_FLAG(verbose) = verbosity;
+  const std::string old_flag = GMOCK_FLAG_GET(verbose);
+  GMOCK_FLAG_SET(verbose, verbosity);
   CaptureStdout();
   Log(severity, "Test log.\n", 0);
   if (should_print) {
-    EXPECT_THAT(GetCapturedStdout().c_str(),
-                ContainsRegex(
-                    severity == kWarning ?
-                    "^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n" :
-                    "^\nTest log\\.\nStack trace:\n"));
+    EXPECT_THAT(
+        GetCapturedStdout().c_str(),
+        ContainsRegex(severity == kWarning
+                          ? "^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n"
+                          : "^\nTest log\\.\nStack trace:\n"));
   } else {
     EXPECT_STREQ("", GetCapturedStdout().c_str());
   }
-  GMOCK_FLAG(verbose) = old_flag;
+  GMOCK_FLAG_SET(verbose, old_flag);
 }
 
 // Tests that when the stack_frames_to_skip parameter is negative,
 // Log() doesn't include the stack trace in the output.
 TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) {
-  const std::string saved_flag = GMOCK_FLAG(verbose);
-  GMOCK_FLAG(verbose) = kInfoVerbosity;
+  const std::string saved_flag = GMOCK_FLAG_GET(verbose);
+  GMOCK_FLAG_SET(verbose, kInfoVerbosity);
   CaptureStdout();
   Log(kInfo, "Test log.\n", -1);
   EXPECT_STREQ("\nTest log.\n", GetCapturedStdout().c_str());
-  GMOCK_FLAG(verbose) = saved_flag;
+  GMOCK_FLAG_SET(verbose, saved_flag);
 }
 
 struct MockStackTraceGetter : testing::internal::OsStackTraceGetterInterface {
@@ -440,7 +445,8 @@ TEST(LogTest, NoSkippingStackFrameInOptMode) {
   const std::string log = GetCapturedStdout();
 
   std::string expected_trace =
-      (testing::Message() << GTEST_FLAG(stack_trace_depth) << "::").GetString();
+      (testing::Message() << GTEST_FLAG_GET(stack_trace_depth) << "::")
+          .GetString();
   std::string expected_message =
       "\nGMOCK WARNING:\n"
       "Test log.\n"
@@ -449,13 +455,13 @@ TEST(LogTest, NoSkippingStackFrameInOptMode) {
   EXPECT_THAT(log, HasSubstr(expected_message));
   int skip_count = atoi(log.substr(expected_message.size()).c_str());
 
-# if defined(NDEBUG)
+#if defined(NDEBUG)
   // In opt mode, no stack frame should be skipped.
   const int expected_skip_count = 0;
-# else
+#else
   // In dbg mode, the stack frames should be skipped.
   const int expected_skip_count = 100;
-# endif
+#endif
 
   // Note that each inner implementation layer will +1 the number to remove
   // itself from the trace. This means that the value is a little higher than
@@ -497,12 +503,12 @@ TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) {
 
 // Verifies that Log() behaves correctly for the given verbosity level
 // and log severity.
-std::string GrabOutput(void(*logger)(), const char* verbosity) {
-  const std::string saved_flag = GMOCK_FLAG(verbose);
-  GMOCK_FLAG(verbose) = verbosity;
+std::string GrabOutput(void (*logger)(), const char* verbosity) {
+  const std::string saved_flag = GMOCK_FLAG_GET(verbose);
+  GMOCK_FLAG_SET(verbose, verbosity);
   CaptureStdout();
   logger();
-  GMOCK_FLAG(verbose) = saved_flag;
+  GMOCK_FLAG_SET(verbose, saved_flag);
   return GetCapturedStdout();
 }
 
@@ -532,7 +538,7 @@ TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsWarning) {
 
 // Verifies that EXPECT_CALL doesn't log
 // if the --gmock_verbose flag is set to "error".
-TEST(ExpectCallTest,  DoesNotLogWhenVerbosityIsError) {
+TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) {
   EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kErrorVerbosity).c_str());
 }
 
@@ -576,9 +582,9 @@ TEST(OnCallTest, LogsAnythingArgument) {
 
 TEST(StlContainerViewTest, WorksForStlContainer) {
   StaticAssertTypeEq<std::vector<int>,
-      StlContainerView<std::vector<int> >::type>();
+                     StlContainerView<std::vector<int>>::type>();
   StaticAssertTypeEq<const std::vector<double>&,
-      StlContainerView<std::vector<double> >::const_reference>();
+                     StlContainerView<std::vector<double>>::const_reference>();
 
   typedef std::vector<char> Chars;
   Chars v1;
@@ -591,17 +597,16 @@ TEST(StlContainerViewTest, WorksForStlContainer) {
 }
 
 TEST(StlContainerViewTest, WorksForStaticNativeArray) {
-  StaticAssertTypeEq<NativeArray<int>,
-      StlContainerView<int[3]>::type>();
+  StaticAssertTypeEq<NativeArray<int>, StlContainerView<int[3]>::type>();
   StaticAssertTypeEq<NativeArray<double>,
-      StlContainerView<const double[4]>::type>();
+                     StlContainerView<const double[4]>::type>();
   StaticAssertTypeEq<NativeArray<char[3]>,
-      StlContainerView<const char[2][3]>::type>();
+                     StlContainerView<const char[2][3]>::type>();
 
   StaticAssertTypeEq<const NativeArray<int>,
-      StlContainerView<int[2]>::const_reference>();
+                     StlContainerView<int[2]>::const_reference>();
 
-  int a1[3] = { 0, 1, 2 };
+  int a1[3] = {0, 1, 2};
   NativeArray<int> a2 = StlContainerView<int[3]>::ConstReference(a1);
   EXPECT_EQ(3U, a2.size());
   EXPECT_EQ(a1, a2.begin());
@@ -619,24 +624,24 @@ TEST(StlContainerViewTest, WorksForStaticNativeArray) {
 
 TEST(StlContainerViewTest, WorksForDynamicNativeArray) {
   StaticAssertTypeEq<NativeArray<int>,
-                     StlContainerView<std::tuple<const int*, size_t> >::type>();
+                     StlContainerView<std::tuple<const int*, size_t>>::type>();
   StaticAssertTypeEq<
       NativeArray<double>,
-      StlContainerView<std::tuple<std::shared_ptr<double>, int> >::type>();
+      StlContainerView<std::tuple<std::shared_ptr<double>, int>>::type>();
 
   StaticAssertTypeEq<
       const NativeArray<int>,
-      StlContainerView<std::tuple<const int*, int> >::const_reference>();
+      StlContainerView<std::tuple<const int*, int>>::const_reference>();
 
-  int a1[3] = { 0, 1, 2 };
+  int a1[3] = {0, 1, 2};
   const int* const p1 = a1;
   NativeArray<int> a2 =
-      StlContainerView<std::tuple<const int*, int> >::ConstReference(
+      StlContainerView<std::tuple<const int*, int>>::ConstReference(
           std::make_tuple(p1, 3));
   EXPECT_EQ(3U, a2.size());
   EXPECT_EQ(a1, a2.begin());
 
-  const NativeArray<int> a3 = StlContainerView<std::tuple<int*, size_t> >::Copy(
+  const NativeArray<int> a3 = StlContainerView<std::tuple<int*, size_t>>::Copy(
       std::make_tuple(static_cast<int*>(a1), 3));
   ASSERT_EQ(3U, a3.size());
   EXPECT_EQ(0, a3.begin()[0]);
@@ -715,6 +720,46 @@ TEST(FunctionTest, LongArgumentList) {
                    F::MakeResultIgnoredValue>::value));
 }
 
+TEST(Base64Unescape, InvalidString) {
+  std::string unescaped;
+  EXPECT_FALSE(Base64Unescape("(invalid)", &unescaped));
+}
+
+TEST(Base64Unescape, ShortString) {
+  std::string unescaped;
+  EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQh", &unescaped));
+  EXPECT_EQ("Hello world!", unescaped);
+}
+
+TEST(Base64Unescape, ShortStringWithPadding) {
+  std::string unescaped;
+  EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQ=", &unescaped));
+  EXPECT_EQ("Hello world", unescaped);
+}
+
+TEST(Base64Unescape, ShortStringWithoutPadding) {
+  std::string unescaped;
+  EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQ", &unescaped));
+  EXPECT_EQ("Hello world", unescaped);
+}
+
+TEST(Base64Unescape, LongStringWithWhiteSpaces) {
+  std::string escaped =
+      R"(TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
+  IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg
+  dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu
+  dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo
+  ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=)";
+  std::string expected =
+      "Man is distinguished, not only by his reason, but by this singular "
+      "passion from other animals, which is a lust of the mind, that by a "
+      "perseverance of delight in the continued and indefatigable generation "
+      "of knowledge, exceeds the short vehemence of any carnal pleasure.";
+  std::string unescaped;
+  EXPECT_TRUE(Base64Unescape(escaped, &unescaped));
+  EXPECT_EQ(expected, unescaped);
+}
+
 }  // namespace
 }  // namespace internal
 }  // namespace testing
diff --git a/googlemock/test/gmock-matchers-arithmetic_test.cc b/googlemock/test/gmock-matchers-arithmetic_test.cc
new file mode 100644 (file)
index 0000000..a4c1def
--- /dev/null
@@ -0,0 +1,1517 @@
+// Copyright 2007, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Google Mock - a framework for writing C++ mock classes.
+//
+// This file tests some commonly used argument matchers.
+
+// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
+// possible loss of data and C4100, unreferenced local parameter
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4244)
+#pragma warning(disable : 4100)
+#endif
+
+#include "test/gmock-matchers_test.h"
+
+namespace testing {
+namespace gmock_matchers_test {
+namespace {
+
+typedef ::std::tuple<long, int> Tuple2;  // NOLINT
+
+// Tests that Eq() matches a 2-tuple where the first field == the
+// second field.
+TEST(Eq2Test, MatchesEqualArguments) {
+  Matcher<const Tuple2&> m = Eq();
+  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
+  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
+}
+
+// Tests that Eq() describes itself properly.
+TEST(Eq2Test, CanDescribeSelf) {
+  Matcher<const Tuple2&> m = Eq();
+  EXPECT_EQ("are an equal pair", Describe(m));
+}
+
+// Tests that Ge() matches a 2-tuple where the first field >= the
+// second field.
+TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
+  Matcher<const Tuple2&> m = Ge();
+  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
+  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
+  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
+}
+
+// Tests that Ge() describes itself properly.
+TEST(Ge2Test, CanDescribeSelf) {
+  Matcher<const Tuple2&> m = Ge();
+  EXPECT_EQ("are a pair where the first >= the second", Describe(m));
+}
+
+// Tests that Gt() matches a 2-tuple where the first field > the
+// second field.
+TEST(Gt2Test, MatchesGreaterThanArguments) {
+  Matcher<const Tuple2&> m = Gt();
+  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
+  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
+  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
+}
+
+// Tests that Gt() describes itself properly.
+TEST(Gt2Test, CanDescribeSelf) {
+  Matcher<const Tuple2&> m = Gt();
+  EXPECT_EQ("are a pair where the first > the second", Describe(m));
+}
+
+// Tests that Le() matches a 2-tuple where the first field <= the
+// second field.
+TEST(Le2Test, MatchesLessThanOrEqualArguments) {
+  Matcher<const Tuple2&> m = Le();
+  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
+  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
+  EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
+}
+
+// Tests that Le() describes itself properly.
+TEST(Le2Test, CanDescribeSelf) {
+  Matcher<const Tuple2&> m = Le();
+  EXPECT_EQ("are a pair where the first <= the second", Describe(m));
+}
+
+// Tests that Lt() matches a 2-tuple where the first field < the
+// second field.
+TEST(Lt2Test, MatchesLessThanArguments) {
+  Matcher<const Tuple2&> m = Lt();
+  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
+  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
+  EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
+}
+
+// Tests that Lt() describes itself properly.
+TEST(Lt2Test, CanDescribeSelf) {
+  Matcher<const Tuple2&> m = Lt();
+  EXPECT_EQ("are a pair where the first < the second", Describe(m));
+}
+
+// Tests that Ne() matches a 2-tuple where the first field != the
+// second field.
+TEST(Ne2Test, MatchesUnequalArguments) {
+  Matcher<const Tuple2&> m = Ne();
+  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
+  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
+  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
+}
+
+// Tests that Ne() describes itself properly.
+TEST(Ne2Test, CanDescribeSelf) {
+  Matcher<const Tuple2&> m = Ne();
+  EXPECT_EQ("are an unequal pair", Describe(m));
+}
+
+TEST(PairMatchBaseTest, WorksWithMoveOnly) {
+  using Pointers = std::tuple<std::unique_ptr<int>, std::unique_ptr<int>>;
+  Matcher<Pointers> matcher = Eq();
+  Pointers pointers;
+  // Tested values don't matter; the point is that matcher does not copy the
+  // matched values.
+  EXPECT_TRUE(matcher.Matches(pointers));
+}
+
+// Tests that IsNan() matches a NaN, with float.
+TEST(IsNan, FloatMatchesNan) {
+  float quiet_nan = std::numeric_limits<float>::quiet_NaN();
+  float other_nan = std::nanf("1");
+  float real_value = 1.0f;
+
+  Matcher<float> m = IsNan();
+  EXPECT_TRUE(m.Matches(quiet_nan));
+  EXPECT_TRUE(m.Matches(other_nan));
+  EXPECT_FALSE(m.Matches(real_value));
+
+  Matcher<float&> m_ref = IsNan();
+  EXPECT_TRUE(m_ref.Matches(quiet_nan));
+  EXPECT_TRUE(m_ref.Matches(other_nan));
+  EXPECT_FALSE(m_ref.Matches(real_value));
+
+  Matcher<const float&> m_cref = IsNan();
+  EXPECT_TRUE(m_cref.Matches(quiet_nan));
+  EXPECT_TRUE(m_cref.Matches(other_nan));
+  EXPECT_FALSE(m_cref.Matches(real_value));
+}
+
+// Tests that IsNan() matches a NaN, with double.
+TEST(IsNan, DoubleMatchesNan) {
+  double quiet_nan = std::numeric_limits<double>::quiet_NaN();
+  double other_nan = std::nan("1");
+  double real_value = 1.0;
+
+  Matcher<double> m = IsNan();
+  EXPECT_TRUE(m.Matches(quiet_nan));
+  EXPECT_TRUE(m.Matches(other_nan));
+  EXPECT_FALSE(m.Matches(real_value));
+
+  Matcher<double&> m_ref = IsNan();
+  EXPECT_TRUE(m_ref.Matches(quiet_nan));
+  EXPECT_TRUE(m_ref.Matches(other_nan));
+  EXPECT_FALSE(m_ref.Matches(real_value));
+
+  Matcher<const double&> m_cref = IsNan();
+  EXPECT_TRUE(m_cref.Matches(quiet_nan));
+  EXPECT_TRUE(m_cref.Matches(other_nan));
+  EXPECT_FALSE(m_cref.Matches(real_value));
+}
+
+// Tests that IsNan() matches a NaN, with long double.
+TEST(IsNan, LongDoubleMatchesNan) {
+  long double quiet_nan = std::numeric_limits<long double>::quiet_NaN();
+  long double other_nan = std::nan("1");
+  long double real_value = 1.0;
+
+  Matcher<long double> m = IsNan();
+  EXPECT_TRUE(m.Matches(quiet_nan));
+  EXPECT_TRUE(m.Matches(other_nan));
+  EXPECT_FALSE(m.Matches(real_value));
+
+  Matcher<long double&> m_ref = IsNan();
+  EXPECT_TRUE(m_ref.Matches(quiet_nan));
+  EXPECT_TRUE(m_ref.Matches(other_nan));
+  EXPECT_FALSE(m_ref.Matches(real_value));
+
+  Matcher<const long double&> m_cref = IsNan();
+  EXPECT_TRUE(m_cref.Matches(quiet_nan));
+  EXPECT_TRUE(m_cref.Matches(other_nan));
+  EXPECT_FALSE(m_cref.Matches(real_value));
+}
+
+// Tests that IsNan() works with Not.
+TEST(IsNan, NotMatchesNan) {
+  Matcher<float> mf = Not(IsNan());
+  EXPECT_FALSE(mf.Matches(std::numeric_limits<float>::quiet_NaN()));
+  EXPECT_FALSE(mf.Matches(std::nanf("1")));
+  EXPECT_TRUE(mf.Matches(1.0));
+
+  Matcher<double> md = Not(IsNan());
+  EXPECT_FALSE(md.Matches(std::numeric_limits<double>::quiet_NaN()));
+  EXPECT_FALSE(md.Matches(std::nan("1")));
+  EXPECT_TRUE(md.Matches(1.0));
+
+  Matcher<long double> mld = Not(IsNan());
+  EXPECT_FALSE(mld.Matches(std::numeric_limits<long double>::quiet_NaN()));
+  EXPECT_FALSE(mld.Matches(std::nanl("1")));
+  EXPECT_TRUE(mld.Matches(1.0));
+}
+
+// Tests that IsNan() can describe itself.
+TEST(IsNan, CanDescribeSelf) {
+  Matcher<float> mf = IsNan();
+  EXPECT_EQ("is NaN", Describe(mf));
+
+  Matcher<double> md = IsNan();
+  EXPECT_EQ("is NaN", Describe(md));
+
+  Matcher<long double> mld = IsNan();
+  EXPECT_EQ("is NaN", Describe(mld));
+}
+
+// Tests that IsNan() can describe itself with Not.
+TEST(IsNan, CanDescribeSelfWithNot) {
+  Matcher<float> mf = Not(IsNan());
+  EXPECT_EQ("isn't NaN", Describe(mf));
+
+  Matcher<double> md = Not(IsNan());
+  EXPECT_EQ("isn't NaN", Describe(md));
+
+  Matcher<long double> mld = Not(IsNan());
+  EXPECT_EQ("isn't NaN", Describe(mld));
+}
+
+// Tests that FloatEq() matches a 2-tuple where
+// FloatEq(first field) matches the second field.
+TEST(FloatEq2Test, MatchesEqualArguments) {
+  typedef ::std::tuple<float, float> Tpl;
+  Matcher<const Tpl&> m = FloatEq();
+  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
+  EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f)));
+  EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
+}
+
+// Tests that FloatEq() describes itself properly.
+TEST(FloatEq2Test, CanDescribeSelf) {
+  Matcher<const ::std::tuple<float, float>&> m = FloatEq();
+  EXPECT_EQ("are an almost-equal pair", Describe(m));
+}
+
+// Tests that NanSensitiveFloatEq() matches a 2-tuple where
+// NanSensitiveFloatEq(first field) matches the second field.
+TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) {
+  typedef ::std::tuple<float, float> Tpl;
+  Matcher<const Tpl&> m = NanSensitiveFloatEq();
+  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
+  EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
+                            std::numeric_limits<float>::quiet_NaN())));
+  EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
+  EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
+  EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
+}
+
+// Tests that NanSensitiveFloatEq() describes itself properly.
+TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) {
+  Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatEq();
+  EXPECT_EQ("are an almost-equal pair", Describe(m));
+}
+
+// Tests that DoubleEq() matches a 2-tuple where
+// DoubleEq(first field) matches the second field.
+TEST(DoubleEq2Test, MatchesEqualArguments) {
+  typedef ::std::tuple<double, double> Tpl;
+  Matcher<const Tpl&> m = DoubleEq();
+  EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
+  EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1)));
+  EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0)));
+}
+
+// Tests that DoubleEq() describes itself properly.
+TEST(DoubleEq2Test, CanDescribeSelf) {
+  Matcher<const ::std::tuple<double, double>&> m = DoubleEq();
+  EXPECT_EQ("are an almost-equal pair", Describe(m));
+}
+
+// Tests that NanSensitiveDoubleEq() matches a 2-tuple where
+// NanSensitiveDoubleEq(first field) matches the second field.
+TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) {
+  typedef ::std::tuple<double, double> Tpl;
+  Matcher<const Tpl&> m = NanSensitiveDoubleEq();
+  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
+  EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
+                            std::numeric_limits<double>::quiet_NaN())));
+  EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
+  EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
+  EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
+}
+
+// Tests that DoubleEq() describes itself properly.
+TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) {
+  Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleEq();
+  EXPECT_EQ("are an almost-equal pair", Describe(m));
+}
+
+// Tests that FloatEq() matches a 2-tuple where
+// FloatNear(first field, max_abs_error) matches the second field.
+TEST(FloatNear2Test, MatchesEqualArguments) {
+  typedef ::std::tuple<float, float> Tpl;
+  Matcher<const Tpl&> m = FloatNear(0.5f);
+  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
+  EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f)));
+  EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f)));
+}
+
+// Tests that FloatNear() describes itself properly.
+TEST(FloatNear2Test, CanDescribeSelf) {
+  Matcher<const ::std::tuple<float, float>&> m = FloatNear(0.5f);
+  EXPECT_EQ("are an almost-equal pair", Describe(m));
+}
+
+// Tests that NanSensitiveFloatNear() matches a 2-tuple where
+// NanSensitiveFloatNear(first field) matches the second field.
+TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) {
+  typedef ::std::tuple<float, float> Tpl;
+  Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f);
+  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
+  EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
+  EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
+                            std::numeric_limits<float>::quiet_NaN())));
+  EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
+  EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
+  EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
+}
+
+// Tests that NanSensitiveFloatNear() describes itself properly.
+TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) {
+  Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatNear(0.5f);
+  EXPECT_EQ("are an almost-equal pair", Describe(m));
+}
+
+// Tests that FloatEq() matches a 2-tuple where
+// DoubleNear(first field, max_abs_error) matches the second field.
+TEST(DoubleNear2Test, MatchesEqualArguments) {
+  typedef ::std::tuple<double, double> Tpl;
+  Matcher<const Tpl&> m = DoubleNear(0.5);
+  EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
+  EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0)));
+  EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0)));
+}
+
+// Tests that DoubleNear() describes itself properly.
+TEST(DoubleNear2Test, CanDescribeSelf) {
+  Matcher<const ::std::tuple<double, double>&> m = DoubleNear(0.5);
+  EXPECT_EQ("are an almost-equal pair", Describe(m));
+}
+
+// Tests that NanSensitiveDoubleNear() matches a 2-tuple where
+// NanSensitiveDoubleNear(first field) matches the second field.
+TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) {
+  typedef ::std::tuple<double, double> Tpl;
+  Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f);
+  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
+  EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
+  EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
+                            std::numeric_limits<double>::quiet_NaN())));
+  EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
+  EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
+  EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
+}
+
+// Tests that NanSensitiveDoubleNear() describes itself properly.
+TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {
+  Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleNear(0.5f);
+  EXPECT_EQ("are an almost-equal pair", Describe(m));
+}
+
+// Tests that Not(m) matches any value that doesn't match m.
+TEST(NotTest, NegatesMatcher) {
+  Matcher<int> m;
+  m = Not(Eq(2));
+  EXPECT_TRUE(m.Matches(3));
+  EXPECT_FALSE(m.Matches(2));
+}
+
+// Tests that Not(m) describes itself properly.
+TEST(NotTest, CanDescribeSelf) {
+  Matcher<int> m = Not(Eq(5));
+  EXPECT_EQ("isn't equal to 5", Describe(m));
+}
+
+// Tests that monomorphic matchers are safely cast by the Not matcher.
+TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
+  // greater_than_5 is a monomorphic matcher.
+  Matcher<int> greater_than_5 = Gt(5);
+
+  Matcher<const int&> m = Not(greater_than_5);
+  Matcher<int&> m2 = Not(greater_than_5);
+  Matcher<int&> m3 = Not(m);
+}
+
+// Helper to allow easy testing of AllOf matchers with num parameters.
+void AllOfMatches(int num, const Matcher<int>& m) {
+  SCOPED_TRACE(Describe(m));
+  EXPECT_TRUE(m.Matches(0));
+  for (int i = 1; i <= num; ++i) {
+    EXPECT_FALSE(m.Matches(i));
+  }
+  EXPECT_TRUE(m.Matches(num + 1));
+}
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(AllOfTest);
+
+// Tests that AllOf(m1, ..., mn) matches any value that matches all of
+// the given matchers.
+TEST(AllOfTest, MatchesWhenAllMatch) {
+  Matcher<int> m;
+  m = AllOf(Le(2), Ge(1));
+  EXPECT_TRUE(m.Matches(1));
+  EXPECT_TRUE(m.Matches(2));
+  EXPECT_FALSE(m.Matches(0));
+  EXPECT_FALSE(m.Matches(3));
+
+  m = AllOf(Gt(0), Ne(1), Ne(2));
+  EXPECT_TRUE(m.Matches(3));
+  EXPECT_FALSE(m.Matches(2));
+  EXPECT_FALSE(m.Matches(1));
+  EXPECT_FALSE(m.Matches(0));
+
+  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
+  EXPECT_TRUE(m.Matches(4));
+  EXPECT_FALSE(m.Matches(3));
+  EXPECT_FALSE(m.Matches(2));
+  EXPECT_FALSE(m.Matches(1));
+  EXPECT_FALSE(m.Matches(0));
+
+  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
+  EXPECT_TRUE(m.Matches(0));
+  EXPECT_TRUE(m.Matches(1));
+  EXPECT_FALSE(m.Matches(3));
+
+  // The following tests for varying number of sub-matchers. Due to the way
+  // the sub-matchers are handled it is enough to test every sub-matcher once
+  // with sub-matchers using the same matcher type. Varying matcher types are
+  // checked for above.
+  AllOfMatches(2, AllOf(Ne(1), Ne(2)));
+  AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
+  AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
+  AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
+  AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
+  AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
+  AllOfMatches(8,
+               AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8)));
+  AllOfMatches(
+      9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9)));
+  AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
+                         Ne(9), Ne(10)));
+  AllOfMatches(
+      50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
+                Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17),
+                Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25),
+                Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33),
+                Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41),
+                Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
+                Ne(50)));
+}
+
+// Tests that AllOf(m1, ..., mn) describes itself properly.
+TEST(AllOfTest, CanDescribeSelf) {
+  Matcher<int> m;
+  m = AllOf(Le(2), Ge(1));
+  EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
+
+  m = AllOf(Gt(0), Ne(1), Ne(2));
+  std::string expected_descr1 =
+      "(is > 0) and (isn't equal to 1) and (isn't equal to 2)";
+  EXPECT_EQ(expected_descr1, Describe(m));
+
+  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
+  std::string expected_descr2 =
+      "(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal "
+      "to 3)";
+  EXPECT_EQ(expected_descr2, Describe(m));
+
+  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
+  std::string expected_descr3 =
+      "(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) "
+      "and (isn't equal to 7)";
+  EXPECT_EQ(expected_descr3, Describe(m));
+}
+
+// Tests that AllOf(m1, ..., mn) describes its negation properly.
+TEST(AllOfTest, CanDescribeNegation) {
+  Matcher<int> m;
+  m = AllOf(Le(2), Ge(1));
+  std::string expected_descr4 = "(isn't <= 2) or (isn't >= 1)";
+  EXPECT_EQ(expected_descr4, DescribeNegation(m));
+
+  m = AllOf(Gt(0), Ne(1), Ne(2));
+  std::string expected_descr5 =
+      "(isn't > 0) or (is equal to 1) or (is equal to 2)";
+  EXPECT_EQ(expected_descr5, DescribeNegation(m));
+
+  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
+  std::string expected_descr6 =
+      "(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)";
+  EXPECT_EQ(expected_descr6, DescribeNegation(m));
+
+  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
+  std::string expected_desr7 =
+      "(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or "
+      "(is equal to 7)";
+  EXPECT_EQ(expected_desr7, DescribeNegation(m));
+
+  m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
+            Ne(10), Ne(11));
+  AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
+  EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)"));
+  AllOfMatches(11, m);
+}
+
+// Tests that monomorphic matchers are safely cast by the AllOf matcher.
+TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
+  // greater_than_5 and less_than_10 are monomorphic matchers.
+  Matcher<int> greater_than_5 = Gt(5);
+  Matcher<int> less_than_10 = Lt(10);
+
+  Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
+  Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
+  Matcher<int&> m3 = AllOf(greater_than_5, m2);
+
+  // Tests that BothOf works when composing itself.
+  Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
+  Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
+}
+
+TEST_P(AllOfTestP, ExplainsResult) {
+  Matcher<int> m;
+
+  // Successful match.  Both matchers need to explain.  The second
+  // matcher doesn't give an explanation, so only the first matcher's
+  // explanation is printed.
+  m = AllOf(GreaterThan(10), Lt(30));
+  EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
+
+  // Successful match.  Both matchers need to explain.
+  m = AllOf(GreaterThan(10), GreaterThan(20));
+  EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
+            Explain(m, 30));
+
+  // Successful match.  All matchers need to explain.  The second
+  // matcher doesn't given an explanation.
+  m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
+  EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
+            Explain(m, 25));
+
+  // Successful match.  All matchers need to explain.
+  m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
+  EXPECT_EQ(
+      "which is 30 more than 10, and which is 20 more than 20, "
+      "and which is 10 more than 30",
+      Explain(m, 40));
+
+  // Failed match.  The first matcher, which failed, needs to
+  // explain.
+  m = AllOf(GreaterThan(10), GreaterThan(20));
+  EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
+
+  // Failed match.  The second matcher, which failed, needs to
+  // explain.  Since it doesn't given an explanation, nothing is
+  // printed.
+  m = AllOf(GreaterThan(10), Lt(30));
+  EXPECT_EQ("", Explain(m, 40));
+
+  // Failed match.  The second matcher, which failed, needs to
+  // explain.
+  m = AllOf(GreaterThan(10), GreaterThan(20));
+  EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
+}
+
+// Helper to allow easy testing of AnyOf matchers with num parameters.
+static void AnyOfMatches(int num, const Matcher<int>& m) {
+  SCOPED_TRACE(Describe(m));
+  EXPECT_FALSE(m.Matches(0));
+  for (int i = 1; i <= num; ++i) {
+    EXPECT_TRUE(m.Matches(i));
+  }
+  EXPECT_FALSE(m.Matches(num + 1));
+}
+
+static void AnyOfStringMatches(int num, const Matcher<std::string>& m) {
+  SCOPED_TRACE(Describe(m));
+  EXPECT_FALSE(m.Matches(std::to_string(0)));
+
+  for (int i = 1; i <= num; ++i) {
+    EXPECT_TRUE(m.Matches(std::to_string(i)));
+  }
+  EXPECT_FALSE(m.Matches(std::to_string(num + 1)));
+}
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(AnyOfTest);
+
+// Tests that AnyOf(m1, ..., mn) matches any value that matches at
+// least one of the given matchers.
+TEST(AnyOfTest, MatchesWhenAnyMatches) {
+  Matcher<int> m;
+  m = AnyOf(Le(1), Ge(3));
+  EXPECT_TRUE(m.Matches(1));
+  EXPECT_TRUE(m.Matches(4));
+  EXPECT_FALSE(m.Matches(2));
+
+  m = AnyOf(Lt(0), Eq(1), Eq(2));
+  EXPECT_TRUE(m.Matches(-1));
+  EXPECT_TRUE(m.Matches(1));
+  EXPECT_TRUE(m.Matches(2));
+  EXPECT_FALSE(m.Matches(0));
+
+  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
+  EXPECT_TRUE(m.Matches(-1));
+  EXPECT_TRUE(m.Matches(1));
+  EXPECT_TRUE(m.Matches(2));
+  EXPECT_TRUE(m.Matches(3));
+  EXPECT_FALSE(m.Matches(0));
+
+  m = AnyOf(Le(0), Gt(10), 3, 5, 7);
+  EXPECT_TRUE(m.Matches(0));
+  EXPECT_TRUE(m.Matches(11));
+  EXPECT_TRUE(m.Matches(3));
+  EXPECT_FALSE(m.Matches(2));
+
+  // The following tests for varying number of sub-matchers. Due to the way
+  // the sub-matchers are handled it is enough to test every sub-matcher once
+  // with sub-matchers using the same matcher type. Varying matcher types are
+  // checked for above.
+  AnyOfMatches(2, AnyOf(1, 2));
+  AnyOfMatches(3, AnyOf(1, 2, 3));
+  AnyOfMatches(4, AnyOf(1, 2, 3, 4));
+  AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
+  AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
+  AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
+  AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
+  AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
+  AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
+}
+
+// Tests the variadic version of the AnyOfMatcher.
+TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
+  // Also make sure AnyOf is defined in the right namespace and does not depend
+  // on ADL.
+  Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
+
+  EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)"));
+  AnyOfMatches(11, m);
+  AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
+                         17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
+                         31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
+                         45, 46, 47, 48, 49, 50));
+  AnyOfStringMatches(
+      50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
+                "13", "14", "15", "16", "17", "18", "19", "20", "21", "22",
+                "23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
+                "33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
+                "43", "44", "45", "46", "47", "48", "49", "50"));
+}
+
+TEST(ConditionalTest, MatchesFirstIfCondition) {
+  Matcher<std::string> eq_red = Eq("red");
+  Matcher<std::string> ne_red = Ne("red");
+  Matcher<std::string> m = Conditional(true, eq_red, ne_red);
+  EXPECT_TRUE(m.Matches("red"));
+  EXPECT_FALSE(m.Matches("green"));
+
+  StringMatchResultListener listener;
+  StringMatchResultListener expected;
+  EXPECT_FALSE(m.MatchAndExplain("green", &listener));
+  EXPECT_FALSE(eq_red.MatchAndExplain("green", &expected));
+  EXPECT_THAT(listener.str(), Eq(expected.str()));
+}
+
+TEST(ConditionalTest, MatchesSecondIfCondition) {
+  Matcher<std::string> eq_red = Eq("red");
+  Matcher<std::string> ne_red = Ne("red");
+  Matcher<std::string> m = Conditional(false, eq_red, ne_red);
+  EXPECT_FALSE(m.Matches("red"));
+  EXPECT_TRUE(m.Matches("green"));
+
+  StringMatchResultListener listener;
+  StringMatchResultListener expected;
+  EXPECT_FALSE(m.MatchAndExplain("red", &listener));
+  EXPECT_FALSE(ne_red.MatchAndExplain("red", &expected));
+  EXPECT_THAT(listener.str(), Eq(expected.str()));
+}
+
+// Tests that AnyOf(m1, ..., mn) describes itself properly.
+TEST(AnyOfTest, CanDescribeSelf) {
+  Matcher<int> m;
+  m = AnyOf(Le(1), Ge(3));
+
+  EXPECT_EQ("(is <= 1) or (is >= 3)", Describe(m));
+
+  m = AnyOf(Lt(0), Eq(1), Eq(2));
+  EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)", Describe(m));
+
+  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
+  EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)",
+            Describe(m));
+
+  m = AnyOf(Le(0), Gt(10), 3, 5, 7);
+  EXPECT_EQ(
+      "(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is "
+      "equal to 7)",
+      Describe(m));
+}
+
+// Tests that AnyOf(m1, ..., mn) describes its negation properly.
+TEST(AnyOfTest, CanDescribeNegation) {
+  Matcher<int> m;
+  m = AnyOf(Le(1), Ge(3));
+  EXPECT_EQ("(isn't <= 1) and (isn't >= 3)", DescribeNegation(m));
+
+  m = AnyOf(Lt(0), Eq(1), Eq(2));
+  EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)",
+            DescribeNegation(m));
+
+  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
+  EXPECT_EQ(
+      "(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't "
+      "equal to 3)",
+      DescribeNegation(m));
+
+  m = AnyOf(Le(0), Gt(10), 3, 5, 7);
+  EXPECT_EQ(
+      "(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal "
+      "to 5) and (isn't equal to 7)",
+      DescribeNegation(m));
+}
+
+// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
+TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
+  // greater_than_5 and less_than_10 are monomorphic matchers.
+  Matcher<int> greater_than_5 = Gt(5);
+  Matcher<int> less_than_10 = Lt(10);
+
+  Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
+  Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
+  Matcher<int&> m3 = AnyOf(greater_than_5, m2);
+
+  // Tests that EitherOf works when composing itself.
+  Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
+  Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
+}
+
+TEST_P(AnyOfTestP, ExplainsResult) {
+  Matcher<int> m;
+
+  // Failed match.  Both matchers need to explain.  The second
+  // matcher doesn't give an explanation, so only the first matcher's
+  // explanation is printed.
+  m = AnyOf(GreaterThan(10), Lt(0));
+  EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
+
+  // Failed match.  Both matchers need to explain.
+  m = AnyOf(GreaterThan(10), GreaterThan(20));
+  EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
+            Explain(m, 5));
+
+  // Failed match.  All matchers need to explain.  The second
+  // matcher doesn't given an explanation.
+  m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
+  EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
+            Explain(m, 5));
+
+  // Failed match.  All matchers need to explain.
+  m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
+  EXPECT_EQ(
+      "which is 5 less than 10, and which is 15 less than 20, "
+      "and which is 25 less than 30",
+      Explain(m, 5));
+
+  // Successful match.  The first matcher, which succeeded, needs to
+  // explain.
+  m = AnyOf(GreaterThan(10), GreaterThan(20));
+  EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
+
+  // Successful match.  The second matcher, which succeeded, needs to
+  // explain.  Since it doesn't given an explanation, nothing is
+  // printed.
+  m = AnyOf(GreaterThan(10), Lt(30));
+  EXPECT_EQ("", Explain(m, 0));
+
+  // Successful match.  The second matcher, which succeeded, needs to
+  // explain.
+  m = AnyOf(GreaterThan(30), GreaterThan(20));
+  EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
+}
+
+// The following predicate function and predicate functor are for
+// testing the Truly(predicate) matcher.
+
+// Returns non-zero if the input is positive.  Note that the return
+// type of this function is not bool.  It's OK as Truly() accepts any
+// unary function or functor whose return type can be implicitly
+// converted to bool.
+int IsPositive(double x) { return x > 0 ? 1 : 0; }
+
+// This functor returns true if the input is greater than the given
+// number.
+class IsGreaterThan {
+ public:
+  explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
+
+  bool operator()(int n) const { return n > threshold_; }
+
+ private:
+  int threshold_;
+};
+
+// For testing Truly().
+const int foo = 0;
+
+// This predicate returns true if and only if the argument references foo and
+// has a zero value.
+bool ReferencesFooAndIsZero(const int& n) { return (&n == &foo) && (n == 0); }
+
+// Tests that Truly(predicate) matches what satisfies the given
+// predicate.
+TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
+  Matcher<double> m = Truly(IsPositive);
+  EXPECT_TRUE(m.Matches(2.0));
+  EXPECT_FALSE(m.Matches(-1.5));
+}
+
+// Tests that Truly(predicate_functor) works too.
+TEST(TrulyTest, CanBeUsedWithFunctor) {
+  Matcher<int> m = Truly(IsGreaterThan(5));
+  EXPECT_TRUE(m.Matches(6));
+  EXPECT_FALSE(m.Matches(4));
+}
+
+// A class that can be implicitly converted to bool.
+class ConvertibleToBool {
+ public:
+  explicit ConvertibleToBool(int number) : number_(number) {}
+  operator bool() const { return number_ != 0; }
+
+ private:
+  int number_;
+};
+
+ConvertibleToBool IsNotZero(int number) { return ConvertibleToBool(number); }
+
+// Tests that the predicate used in Truly() may return a class that's
+// implicitly convertible to bool, even when the class has no
+// operator!().
+TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
+  Matcher<int> m = Truly(IsNotZero);
+  EXPECT_TRUE(m.Matches(1));
+  EXPECT_FALSE(m.Matches(0));
+}
+
+// Tests that Truly(predicate) can describe itself properly.
+TEST(TrulyTest, CanDescribeSelf) {
+  Matcher<double> m = Truly(IsPositive);
+  EXPECT_EQ("satisfies the given predicate", Describe(m));
+}
+
+// Tests that Truly(predicate) works when the matcher takes its
+// argument by reference.
+TEST(TrulyTest, WorksForByRefArguments) {
+  Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
+  EXPECT_TRUE(m.Matches(foo));
+  int n = 0;
+  EXPECT_FALSE(m.Matches(n));
+}
+
+// Tests that Truly(predicate) provides a helpful reason when it fails.
+TEST(TrulyTest, ExplainsFailures) {
+  StringMatchResultListener listener;
+  EXPECT_FALSE(ExplainMatchResult(Truly(IsPositive), -1, &listener));
+  EXPECT_EQ(listener.str(), "didn't satisfy the given predicate");
+}
+
+// Tests that Matches(m) is a predicate satisfied by whatever that
+// matches matcher m.
+TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
+  EXPECT_TRUE(Matches(Ge(0))(1));
+  EXPECT_FALSE(Matches(Eq('a'))('b'));
+}
+
+// Tests that Matches(m) works when the matcher takes its argument by
+// reference.
+TEST(MatchesTest, WorksOnByRefArguments) {
+  int m = 0, n = 0;
+  EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
+  EXPECT_FALSE(Matches(Ref(m))(n));
+}
+
+// Tests that a Matcher on non-reference type can be used in
+// Matches().
+TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
+  Matcher<int> eq5 = Eq(5);
+  EXPECT_TRUE(Matches(eq5)(5));
+  EXPECT_FALSE(Matches(eq5)(2));
+}
+
+// Tests Value(value, matcher).  Since Value() is a simple wrapper for
+// Matches(), which has been tested already, we don't spend a lot of
+// effort on testing Value().
+TEST(ValueTest, WorksWithPolymorphicMatcher) {
+  EXPECT_TRUE(Value("hi", StartsWith("h")));
+  EXPECT_FALSE(Value(5, Gt(10)));
+}
+
+TEST(ValueTest, WorksWithMonomorphicMatcher) {
+  const Matcher<int> is_zero = Eq(0);
+  EXPECT_TRUE(Value(0, is_zero));
+  EXPECT_FALSE(Value('a', is_zero));
+
+  int n = 0;
+  const Matcher<const int&> ref_n = Ref(n);
+  EXPECT_TRUE(Value(n, ref_n));
+  EXPECT_FALSE(Value(1, ref_n));
+}
+
+TEST(AllArgsTest, WorksForTuple) {
+  EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt()));
+  EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt())));
+}
+
+TEST(AllArgsTest, WorksForNonTuple) {
+  EXPECT_THAT(42, AllArgs(Gt(0)));
+  EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
+}
+
+class AllArgsHelper {
+ public:
+  AllArgsHelper() {}
+
+  MOCK_METHOD2(Helper, int(char x, int y));
+
+ private:
+  AllArgsHelper(const AllArgsHelper&) = delete;
+  AllArgsHelper& operator=(const AllArgsHelper&) = delete;
+};
+
+TEST(AllArgsTest, WorksInWithClause) {
+  AllArgsHelper helper;
+  ON_CALL(helper, Helper(_, _)).With(AllArgs(Lt())).WillByDefault(Return(1));
+  EXPECT_CALL(helper, Helper(_, _));
+  EXPECT_CALL(helper, Helper(_, _)).With(AllArgs(Gt())).WillOnce(Return(2));
+
+  EXPECT_EQ(1, helper.Helper('\1', 2));
+  EXPECT_EQ(2, helper.Helper('a', 1));
+}
+
+class OptionalMatchersHelper {
+ public:
+  OptionalMatchersHelper() {}
+
+  MOCK_METHOD0(NoArgs, int());
+
+  MOCK_METHOD1(OneArg, int(int y));
+
+  MOCK_METHOD2(TwoArgs, int(char x, int y));
+
+  MOCK_METHOD1(Overloaded, int(char x));
+  MOCK_METHOD2(Overloaded, int(char x, int y));
+
+ private:
+  OptionalMatchersHelper(const OptionalMatchersHelper&) = delete;
+  OptionalMatchersHelper& operator=(const OptionalMatchersHelper&) = delete;
+};
+
+TEST(AllArgsTest, WorksWithoutMatchers) {
+  OptionalMatchersHelper helper;
+
+  ON_CALL(helper, NoArgs).WillByDefault(Return(10));
+  ON_CALL(helper, OneArg).WillByDefault(Return(20));
+  ON_CALL(helper, TwoArgs).WillByDefault(Return(30));
+
+  EXPECT_EQ(10, helper.NoArgs());
+  EXPECT_EQ(20, helper.OneArg(1));
+  EXPECT_EQ(30, helper.TwoArgs('\1', 2));
+
+  EXPECT_CALL(helper, NoArgs).Times(1);
+  EXPECT_CALL(helper, OneArg).WillOnce(Return(100));
+  EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200));
+  EXPECT_CALL(helper, TwoArgs).Times(0);
+
+  EXPECT_EQ(10, helper.NoArgs());
+  EXPECT_EQ(100, helper.OneArg(1));
+  EXPECT_EQ(200, helper.OneArg(17));
+}
+
+// Tests floating-point matchers.
+template <typename RawType>
+class FloatingPointTest : public testing::Test {
+ protected:
+  typedef testing::internal::FloatingPoint<RawType> Floating;
+  typedef typename Floating::Bits Bits;
+
+  FloatingPointTest()
+      : max_ulps_(Floating::kMaxUlps),
+        zero_bits_(Floating(0).bits()),
+        one_bits_(Floating(1).bits()),
+        infinity_bits_(Floating(Floating::Infinity()).bits()),
+        close_to_positive_zero_(
+            Floating::ReinterpretBits(zero_bits_ + max_ulps_ / 2)),
+        close_to_negative_zero_(
+            -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_ / 2)),
+        further_from_negative_zero_(-Floating::ReinterpretBits(
+            zero_bits_ + max_ulps_ + 1 - max_ulps_ / 2)),
+        close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
+        further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
+        infinity_(Floating::Infinity()),
+        close_to_infinity_(
+            Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
+        further_from_infinity_(
+            Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
+        max_(Floating::Max()),
+        nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
+        nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {}
+
+  void TestSize() { EXPECT_EQ(sizeof(RawType), sizeof(Bits)); }
+
+  // A battery of tests for FloatingEqMatcher::Matches.
+  // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
+  void TestMatches(
+      testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
+    Matcher<RawType> m1 = matcher_maker(0.0);
+    EXPECT_TRUE(m1.Matches(-0.0));
+    EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
+    EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
+    EXPECT_FALSE(m1.Matches(1.0));
+
+    Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
+    EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
+
+    Matcher<RawType> m3 = matcher_maker(1.0);
+    EXPECT_TRUE(m3.Matches(close_to_one_));
+    EXPECT_FALSE(m3.Matches(further_from_one_));
+
+    // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
+    EXPECT_FALSE(m3.Matches(0.0));
+
+    Matcher<RawType> m4 = matcher_maker(-infinity_);
+    EXPECT_TRUE(m4.Matches(-close_to_infinity_));
+
+    Matcher<RawType> m5 = matcher_maker(infinity_);
+    EXPECT_TRUE(m5.Matches(close_to_infinity_));
+
+    // This is interesting as the representations of infinity_ and nan1_
+    // are only 1 DLP apart.
+    EXPECT_FALSE(m5.Matches(nan1_));
+
+    // matcher_maker can produce a Matcher<const RawType&>, which is needed in
+    // some cases.
+    Matcher<const RawType&> m6 = matcher_maker(0.0);
+    EXPECT_TRUE(m6.Matches(-0.0));
+    EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
+    EXPECT_FALSE(m6.Matches(1.0));
+
+    // matcher_maker can produce a Matcher<RawType&>, which is needed in some
+    // cases.
+    Matcher<RawType&> m7 = matcher_maker(0.0);
+    RawType x = 0.0;
+    EXPECT_TRUE(m7.Matches(x));
+    x = 0.01f;
+    EXPECT_FALSE(m7.Matches(x));
+  }
+
+  // Pre-calculated numbers to be used by the tests.
+
+  const Bits max_ulps_;
+
+  const Bits zero_bits_;      // The bits that represent 0.0.
+  const Bits one_bits_;       // The bits that represent 1.0.
+  const Bits infinity_bits_;  // The bits that represent +infinity.
+
+  // Some numbers close to 0.0.
+  const RawType close_to_positive_zero_;
+  const RawType close_to_negative_zero_;
+  const RawType further_from_negative_zero_;
+
+  // Some numbers close to 1.0.
+  const RawType close_to_one_;
+  const RawType further_from_one_;
+
+  // Some numbers close to +infinity.
+  const RawType infinity_;
+  const RawType close_to_infinity_;
+  const RawType further_from_infinity_;
+
+  // Maximum representable value that's not infinity.
+  const RawType max_;
+
+  // Some NaNs.
+  const RawType nan1_;
+  const RawType nan2_;
+};
+
+// Tests floating-point matchers with fixed epsilons.
+template <typename RawType>
+class FloatingPointNearTest : public FloatingPointTest<RawType> {
+ protected:
+  typedef FloatingPointTest<RawType> ParentType;
+
+  // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
+  // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
+  void TestNearMatches(testing::internal::FloatingEqMatcher<RawType> (
+      *matcher_maker)(RawType, RawType)) {
+    Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
+    EXPECT_TRUE(m1.Matches(0.0));
+    EXPECT_TRUE(m1.Matches(-0.0));
+    EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
+    EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
+    EXPECT_FALSE(m1.Matches(1.0));
+
+    Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
+    EXPECT_TRUE(m2.Matches(0.0));
+    EXPECT_TRUE(m2.Matches(-0.0));
+    EXPECT_TRUE(m2.Matches(1.0));
+    EXPECT_TRUE(m2.Matches(-1.0));
+    EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
+    EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
+
+    // Check that inf matches inf, regardless of the of the specified max
+    // absolute error.
+    Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
+    EXPECT_TRUE(m3.Matches(ParentType::infinity_));
+    EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
+    EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
+
+    Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
+    EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
+    EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
+    EXPECT_FALSE(m4.Matches(ParentType::infinity_));
+
+    // Test various overflow scenarios.
+    Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
+    EXPECT_TRUE(m5.Matches(ParentType::max_));
+    EXPECT_FALSE(m5.Matches(-ParentType::max_));
+
+    Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
+    EXPECT_FALSE(m6.Matches(ParentType::max_));
+    EXPECT_TRUE(m6.Matches(-ParentType::max_));
+
+    Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
+    EXPECT_TRUE(m7.Matches(ParentType::max_));
+    EXPECT_FALSE(m7.Matches(-ParentType::max_));
+
+    Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
+    EXPECT_FALSE(m8.Matches(ParentType::max_));
+    EXPECT_TRUE(m8.Matches(-ParentType::max_));
+
+    // The difference between max() and -max() normally overflows to infinity,
+    // but it should still match if the max_abs_error is also infinity.
+    Matcher<RawType> m9 =
+        matcher_maker(ParentType::max_, ParentType::infinity_);
+    EXPECT_TRUE(m8.Matches(-ParentType::max_));
+
+    // matcher_maker can produce a Matcher<const RawType&>, which is needed in
+    // some cases.
+    Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
+    EXPECT_TRUE(m10.Matches(-0.0));
+    EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
+    EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
+
+    // matcher_maker can produce a Matcher<RawType&>, which is needed in some
+    // cases.
+    Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
+    RawType x = 0.0;
+    EXPECT_TRUE(m11.Matches(x));
+    x = 1.0f;
+    EXPECT_TRUE(m11.Matches(x));
+    x = -1.0f;
+    EXPECT_TRUE(m11.Matches(x));
+    x = 1.1f;
+    EXPECT_FALSE(m11.Matches(x));
+    x = -1.1f;
+    EXPECT_FALSE(m11.Matches(x));
+  }
+};
+
+// Instantiate FloatingPointTest for testing floats.
+typedef FloatingPointTest<float> FloatTest;
+
+TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) { TestMatches(&FloatEq); }
+
+TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
+  TestMatches(&NanSensitiveFloatEq);
+}
+
+TEST_F(FloatTest, FloatEqCannotMatchNaN) {
+  // FloatEq never matches NaN.
+  Matcher<float> m = FloatEq(nan1_);
+  EXPECT_FALSE(m.Matches(nan1_));
+  EXPECT_FALSE(m.Matches(nan2_));
+  EXPECT_FALSE(m.Matches(1.0));
+}
+
+TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
+  // NanSensitiveFloatEq will match NaN.
+  Matcher<float> m = NanSensitiveFloatEq(nan1_);
+  EXPECT_TRUE(m.Matches(nan1_));
+  EXPECT_TRUE(m.Matches(nan2_));
+  EXPECT_FALSE(m.Matches(1.0));
+}
+
+TEST_F(FloatTest, FloatEqCanDescribeSelf) {
+  Matcher<float> m1 = FloatEq(2.0f);
+  EXPECT_EQ("is approximately 2", Describe(m1));
+  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
+
+  Matcher<float> m2 = FloatEq(0.5f);
+  EXPECT_EQ("is approximately 0.5", Describe(m2));
+  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
+
+  Matcher<float> m3 = FloatEq(nan1_);
+  EXPECT_EQ("never matches", Describe(m3));
+  EXPECT_EQ("is anything", DescribeNegation(m3));
+}
+
+TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
+  Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
+  EXPECT_EQ("is approximately 2", Describe(m1));
+  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
+
+  Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
+  EXPECT_EQ("is approximately 0.5", Describe(m2));
+  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
+
+  Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
+  EXPECT_EQ("is NaN", Describe(m3));
+  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
+}
+
+// Instantiate FloatingPointTest for testing floats with a user-specified
+// max absolute error.
+typedef FloatingPointNearTest<float> FloatNearTest;
+
+TEST_F(FloatNearTest, FloatNearMatches) { TestNearMatches(&FloatNear); }
+
+TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
+  TestNearMatches(&NanSensitiveFloatNear);
+}
+
+TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
+  Matcher<float> m1 = FloatNear(2.0f, 0.5f);
+  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
+  EXPECT_EQ("isn't approximately 2 (absolute error > 0.5)",
+            DescribeNegation(m1));
+
+  Matcher<float> m2 = FloatNear(0.5f, 0.5f);
+  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
+  EXPECT_EQ("isn't approximately 0.5 (absolute error > 0.5)",
+            DescribeNegation(m2));
+
+  Matcher<float> m3 = FloatNear(nan1_, 0.0);
+  EXPECT_EQ("never matches", Describe(m3));
+  EXPECT_EQ("is anything", DescribeNegation(m3));
+}
+
+TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
+  Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
+  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
+  EXPECT_EQ("isn't approximately 2 (absolute error > 0.5)",
+            DescribeNegation(m1));
+
+  Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
+  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
+  EXPECT_EQ("isn't approximately 0.5 (absolute error > 0.5)",
+            DescribeNegation(m2));
+
+  Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
+  EXPECT_EQ("is NaN", Describe(m3));
+  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
+}
+
+TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
+  // FloatNear never matches NaN.
+  Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
+  EXPECT_FALSE(m.Matches(nan1_));
+  EXPECT_FALSE(m.Matches(nan2_));
+  EXPECT_FALSE(m.Matches(1.0));
+}
+
+TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
+  // NanSensitiveFloatNear will match NaN.
+  Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
+  EXPECT_TRUE(m.Matches(nan1_));
+  EXPECT_TRUE(m.Matches(nan2_));
+  EXPECT_FALSE(m.Matches(1.0));
+}
+
+// Instantiate FloatingPointTest for testing doubles.
+typedef FloatingPointTest<double> DoubleTest;
+
+TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
+  TestMatches(&DoubleEq);
+}
+
+TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
+  TestMatches(&NanSensitiveDoubleEq);
+}
+
+TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
+  // DoubleEq never matches NaN.
+  Matcher<double> m = DoubleEq(nan1_);
+  EXPECT_FALSE(m.Matches(nan1_));
+  EXPECT_FALSE(m.Matches(nan2_));
+  EXPECT_FALSE(m.Matches(1.0));
+}
+
+TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
+  // NanSensitiveDoubleEq will match NaN.
+  Matcher<double> m = NanSensitiveDoubleEq(nan1_);
+  EXPECT_TRUE(m.Matches(nan1_));
+  EXPECT_TRUE(m.Matches(nan2_));
+  EXPECT_FALSE(m.Matches(1.0));
+}
+
+TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
+  Matcher<double> m1 = DoubleEq(2.0);
+  EXPECT_EQ("is approximately 2", Describe(m1));
+  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
+
+  Matcher<double> m2 = DoubleEq(0.5);
+  EXPECT_EQ("is approximately 0.5", Describe(m2));
+  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
+
+  Matcher<double> m3 = DoubleEq(nan1_);
+  EXPECT_EQ("never matches", Describe(m3));
+  EXPECT_EQ("is anything", DescribeNegation(m3));
+}
+
+TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
+  Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
+  EXPECT_EQ("is approximately 2", Describe(m1));
+  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
+
+  Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
+  EXPECT_EQ("is approximately 0.5", Describe(m2));
+  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
+
+  Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
+  EXPECT_EQ("is NaN", Describe(m3));
+  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
+}
+
+// Instantiate FloatingPointTest for testing floats with a user-specified
+// max absolute error.
+typedef FloatingPointNearTest<double> DoubleNearTest;
+
+TEST_F(DoubleNearTest, DoubleNearMatches) { TestNearMatches(&DoubleNear); }
+
+TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
+  TestNearMatches(&NanSensitiveDoubleNear);
+}
+
+TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
+  Matcher<double> m1 = DoubleNear(2.0, 0.5);
+  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
+  EXPECT_EQ("isn't approximately 2 (absolute error > 0.5)",
+            DescribeNegation(m1));
+
+  Matcher<double> m2 = DoubleNear(0.5, 0.5);
+  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
+  EXPECT_EQ("isn't approximately 0.5 (absolute error > 0.5)",
+            DescribeNegation(m2));
+
+  Matcher<double> m3 = DoubleNear(nan1_, 0.0);
+  EXPECT_EQ("never matches", Describe(m3));
+  EXPECT_EQ("is anything", DescribeNegation(m3));
+}
+
+TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
+  EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
+  EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
+  EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
+
+  const std::string explanation =
+      Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
+  // Different C++ implementations may print floating-point numbers
+  // slightly differently.
+  EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" ||  // GCC
+              explanation == "which is 1.2e-010 from 2.1")   // MSVC
+      << " where explanation is \"" << explanation << "\".";
+}
+
+TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
+  Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
+  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
+  EXPECT_EQ("isn't approximately 2 (absolute error > 0.5)",
+            DescribeNegation(m1));
+
+  Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
+  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
+  EXPECT_EQ("isn't approximately 0.5 (absolute error > 0.5)",
+            DescribeNegation(m2));
+
+  Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
+  EXPECT_EQ("is NaN", Describe(m3));
+  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
+}
+
+TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
+  // DoubleNear never matches NaN.
+  Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
+  EXPECT_FALSE(m.Matches(nan1_));
+  EXPECT_FALSE(m.Matches(nan2_));
+  EXPECT_FALSE(m.Matches(1.0));
+}
+
+TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
+  // NanSensitiveDoubleNear will match NaN.
+  Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
+  EXPECT_TRUE(m.Matches(nan1_));
+  EXPECT_TRUE(m.Matches(nan2_));
+  EXPECT_FALSE(m.Matches(1.0));
+}
+
+TEST(NotTest, WorksOnMoveOnlyType) {
+  std::unique_ptr<int> p(new int(3));
+  EXPECT_THAT(p, Pointee(Eq(3)));
+  EXPECT_THAT(p, Not(Pointee(Eq(2))));
+}
+
+TEST(AllOfTest, HugeMatcher) {
+  // Verify that using AllOf with many arguments doesn't cause
+  // the compiler to exceed template instantiation depth limit.
+  EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
+                                testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
+}
+
+TEST(AnyOfTest, HugeMatcher) {
+  // Verify that using AnyOf with many arguments doesn't cause
+  // the compiler to exceed template instantiation depth limit.
+  EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
+                                testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
+}
+
+namespace adl_test {
+
+// Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf
+// don't issue unqualified recursive calls.  If they do, the argument dependent
+// name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found
+// as a candidate and the compilation will break due to an ambiguous overload.
+
+// The matcher must be in the same namespace as AllOf/AnyOf to make argument
+// dependent lookup find those.
+MATCHER(M, "") {
+  (void)arg;
+  return true;
+}
+
+template <typename T1, typename T2>
+bool AllOf(const T1& /*t1*/, const T2& /*t2*/) {
+  return true;
+}
+
+TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
+  EXPECT_THAT(42,
+              testing::AllOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
+}
+
+template <typename T1, typename T2>
+bool AnyOf(const T1&, const T2&) {
+  return true;
+}
+
+TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
+  EXPECT_THAT(42,
+              testing::AnyOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
+}
+
+}  // namespace adl_test
+
+TEST(AllOfTest, WorksOnMoveOnlyType) {
+  std::unique_ptr<int> p(new int(3));
+  EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));
+  EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
+}
+
+TEST(AnyOfTest, WorksOnMoveOnlyType) {
+  std::unique_ptr<int> p(new int(3));
+  EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));
+  EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
+}
+
+}  // namespace
+}  // namespace gmock_matchers_test
+}  // namespace testing
+
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
diff --git a/googlemock/test/gmock-matchers-comparisons_test.cc b/googlemock/test/gmock-matchers-comparisons_test.cc
new file mode 100644 (file)
index 0000000..eb8f3f6
--- /dev/null
@@ -0,0 +1,2318 @@
+// Copyright 2007, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Google Mock - a framework for writing C++ mock classes.
+//
+// This file tests some commonly used argument matchers.
+
+// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
+// possible loss of data and C4100, unreferenced local parameter
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4244)
+#pragma warning(disable : 4100)
+#endif
+
+#include "test/gmock-matchers_test.h"
+
+namespace testing {
+namespace gmock_matchers_test {
+namespace {
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(MonotonicMatcherTest);
+
+TEST_P(MonotonicMatcherTestP, IsPrintable) {
+  stringstream ss;
+  ss << GreaterThan(5);
+  EXPECT_EQ("is > 5", ss.str());
+}
+
+TEST(MatchResultListenerTest, StreamingWorks) {
+  StringMatchResultListener listener;
+  listener << "hi" << 5;
+  EXPECT_EQ("hi5", listener.str());
+
+  listener.Clear();
+  EXPECT_EQ("", listener.str());
+
+  listener << 42;
+  EXPECT_EQ("42", listener.str());
+
+  // Streaming shouldn't crash when the underlying ostream is NULL.
+  DummyMatchResultListener dummy;
+  dummy << "hi" << 5;
+}
+
+TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
+  EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr);
+  EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr);
+
+  EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
+}
+
+TEST(MatchResultListenerTest, IsInterestedWorks) {
+  EXPECT_TRUE(StringMatchResultListener().IsInterested());
+  EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
+
+  EXPECT_FALSE(DummyMatchResultListener().IsInterested());
+  EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested());
+}
+
+// Makes sure that the MatcherInterface<T> interface doesn't
+// change.
+class EvenMatcherImpl : public MatcherInterface<int> {
+ public:
+  bool MatchAndExplain(int x,
+                       MatchResultListener* /* listener */) const override {
+    return x % 2 == 0;
+  }
+
+  void DescribeTo(ostream* os) const override { *os << "is an even number"; }
+
+  // We deliberately don't define DescribeNegationTo() and
+  // ExplainMatchResultTo() here, to make sure the definition of these
+  // two methods is optional.
+};
+
+// Makes sure that the MatcherInterface API doesn't change.
+TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
+  EvenMatcherImpl m;
+}
+
+// Tests implementing a monomorphic matcher using MatchAndExplain().
+
+class NewEvenMatcherImpl : public MatcherInterface<int> {
+ public:
+  bool MatchAndExplain(int x, MatchResultListener* listener) const override {
+    const bool match = x % 2 == 0;
+    // Verifies that we can stream to a listener directly.
+    *listener << "value % " << 2;
+    if (listener->stream() != nullptr) {
+      // Verifies that we can stream to a listener's underlying stream
+      // too.
+      *listener->stream() << " == " << (x % 2);
+    }
+    return match;
+  }
+
+  void DescribeTo(ostream* os) const override { *os << "is an even number"; }
+};
+
+TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
+  Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
+  EXPECT_TRUE(m.Matches(2));
+  EXPECT_FALSE(m.Matches(3));
+  EXPECT_EQ("value % 2 == 0", Explain(m, 2));
+  EXPECT_EQ("value % 2 == 1", Explain(m, 3));
+}
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(MatcherTest);
+
+// Tests default-constructing a matcher.
+TEST(MatcherTest, CanBeDefaultConstructed) { Matcher<double> m; }
+
+// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
+TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
+  const MatcherInterface<int>* impl = new EvenMatcherImpl;
+  Matcher<int> m(impl);
+  EXPECT_TRUE(m.Matches(4));
+  EXPECT_FALSE(m.Matches(5));
+}
+
+// Tests that value can be used in place of Eq(value).
+TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
+  Matcher<int> m1 = 5;
+  EXPECT_TRUE(m1.Matches(5));
+  EXPECT_FALSE(m1.Matches(6));
+}
+
+// Tests that NULL can be used in place of Eq(NULL).
+TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
+  Matcher<int*> m1 = nullptr;
+  EXPECT_TRUE(m1.Matches(nullptr));
+  int n = 0;
+  EXPECT_FALSE(m1.Matches(&n));
+}
+
+// Tests that matchers can be constructed from a variable that is not properly
+// defined. This should be illegal, but many users rely on this accidentally.
+struct Undefined {
+  virtual ~Undefined() = 0;
+  static const int kInt = 1;
+};
+
+TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {
+  Matcher<int> m1 = Undefined::kInt;
+  EXPECT_TRUE(m1.Matches(1));
+  EXPECT_FALSE(m1.Matches(2));
+}
+
+// Test that a matcher parameterized with an abstract class compiles.
+TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; }
+
+// Tests that matchers are copyable.
+TEST(MatcherTest, IsCopyable) {
+  // Tests the copy constructor.
+  Matcher<bool> m1 = Eq(false);
+  EXPECT_TRUE(m1.Matches(false));
+  EXPECT_FALSE(m1.Matches(true));
+
+  // Tests the assignment operator.
+  m1 = Eq(true);
+  EXPECT_TRUE(m1.Matches(true));
+  EXPECT_FALSE(m1.Matches(false));
+}
+
+// Tests that Matcher<T>::DescribeTo() calls
+// MatcherInterface<T>::DescribeTo().
+TEST(MatcherTest, CanDescribeItself) {
+  EXPECT_EQ("is an even number", Describe(Matcher<int>(new EvenMatcherImpl)));
+}
+
+// Tests Matcher<T>::MatchAndExplain().
+TEST_P(MatcherTestP, MatchAndExplain) {
+  Matcher<int> m = GreaterThan(0);
+  StringMatchResultListener listener1;
+  EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
+  EXPECT_EQ("which is 42 more than 0", listener1.str());
+
+  StringMatchResultListener listener2;
+  EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
+  EXPECT_EQ("which is 9 less than 0", listener2.str());
+}
+
+// Tests that a C-string literal can be implicitly converted to a
+// Matcher<std::string> or Matcher<const std::string&>.
+TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
+  Matcher<std::string> m1 = "hi";
+  EXPECT_TRUE(m1.Matches("hi"));
+  EXPECT_FALSE(m1.Matches("hello"));
+
+  Matcher<const std::string&> m2 = "hi";
+  EXPECT_TRUE(m2.Matches("hi"));
+  EXPECT_FALSE(m2.Matches("hello"));
+}
+
+// Tests that a string object can be implicitly converted to a
+// Matcher<std::string> or Matcher<const std::string&>.
+TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
+  Matcher<std::string> m1 = std::string("hi");
+  EXPECT_TRUE(m1.Matches("hi"));
+  EXPECT_FALSE(m1.Matches("hello"));
+
+  Matcher<const std::string&> m2 = std::string("hi");
+  EXPECT_TRUE(m2.Matches("hi"));
+  EXPECT_FALSE(m2.Matches("hello"));
+}
+
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+// Tests that a C-string literal can be implicitly converted to a
+// Matcher<StringView> or Matcher<const StringView&>.
+TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
+  Matcher<internal::StringView> m1 = "cats";
+  EXPECT_TRUE(m1.Matches("cats"));
+  EXPECT_FALSE(m1.Matches("dogs"));
+
+  Matcher<const internal::StringView&> m2 = "cats";
+  EXPECT_TRUE(m2.Matches("cats"));
+  EXPECT_FALSE(m2.Matches("dogs"));
+}
+
+// Tests that a std::string object can be implicitly converted to a
+// Matcher<StringView> or Matcher<const StringView&>.
+TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
+  Matcher<internal::StringView> m1 = std::string("cats");
+  EXPECT_TRUE(m1.Matches("cats"));
+  EXPECT_FALSE(m1.Matches("dogs"));
+
+  Matcher<const internal::StringView&> m2 = std::string("cats");
+  EXPECT_TRUE(m2.Matches("cats"));
+  EXPECT_FALSE(m2.Matches("dogs"));
+}
+
+// Tests that a StringView object can be implicitly converted to a
+// Matcher<StringView> or Matcher<const StringView&>.
+TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
+  Matcher<internal::StringView> m1 = internal::StringView("cats");
+  EXPECT_TRUE(m1.Matches("cats"));
+  EXPECT_FALSE(m1.Matches("dogs"));
+
+  Matcher<const internal::StringView&> m2 = internal::StringView("cats");
+  EXPECT_TRUE(m2.Matches("cats"));
+  EXPECT_FALSE(m2.Matches("dogs"));
+}
+#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
+
+// Tests that a std::reference_wrapper<std::string> object can be implicitly
+// converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().
+TEST(StringMatcherTest,
+     CanBeImplicitlyConstructedFromEqReferenceWrapperString) {
+  std::string value = "cats";
+  Matcher<std::string> m1 = Eq(std::ref(value));
+  EXPECT_TRUE(m1.Matches("cats"));
+  EXPECT_FALSE(m1.Matches("dogs"));
+
+  Matcher<const std::string&> m2 = Eq(std::ref(value));
+  EXPECT_TRUE(m2.Matches("cats"));
+  EXPECT_FALSE(m2.Matches("dogs"));
+}
+
+// Tests that MakeMatcher() constructs a Matcher<T> from a
+// MatcherInterface* without requiring the user to explicitly
+// write the type.
+TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
+  const MatcherInterface<int>* dummy_impl = new EvenMatcherImpl;
+  Matcher<int> m = MakeMatcher(dummy_impl);
+}
+
+// Tests that MakePolymorphicMatcher() can construct a polymorphic
+// matcher from its implementation using the old API.
+const int g_bar = 1;
+class ReferencesBarOrIsZeroImpl {
+ public:
+  template <typename T>
+  bool MatchAndExplain(const T& x, MatchResultListener* /* listener */) const {
+    const void* p = &x;
+    return p == &g_bar || x == 0;
+  }
+
+  void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
+
+  void DescribeNegationTo(ostream* os) const {
+    *os << "doesn't reference g_bar and is not zero";
+  }
+};
+
+// This function verifies that MakePolymorphicMatcher() returns a
+// PolymorphicMatcher<T> where T is the argument's type.
+PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
+  return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
+}
+
+TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
+  // Using a polymorphic matcher to match a reference type.
+  Matcher<const int&> m1 = ReferencesBarOrIsZero();
+  EXPECT_TRUE(m1.Matches(0));
+  // Verifies that the identity of a by-reference argument is preserved.
+  EXPECT_TRUE(m1.Matches(g_bar));
+  EXPECT_FALSE(m1.Matches(1));
+  EXPECT_EQ("g_bar or zero", Describe(m1));
+
+  // Using a polymorphic matcher to match a value type.
+  Matcher<double> m2 = ReferencesBarOrIsZero();
+  EXPECT_TRUE(m2.Matches(0.0));
+  EXPECT_FALSE(m2.Matches(0.1));
+  EXPECT_EQ("g_bar or zero", Describe(m2));
+}
+
+// Tests implementing a polymorphic matcher using MatchAndExplain().
+
+class PolymorphicIsEvenImpl {
+ public:
+  void DescribeTo(ostream* os) const { *os << "is even"; }
+
+  void DescribeNegationTo(ostream* os) const { *os << "is odd"; }
+
+  template <typename T>
+  bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
+    // Verifies that we can stream to the listener directly.
+    *listener << "% " << 2;
+    if (listener->stream() != nullptr) {
+      // Verifies that we can stream to the listener's underlying stream
+      // too.
+      *listener->stream() << " == " << (x % 2);
+    }
+    return (x % 2) == 0;
+  }
+};
+
+PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
+  return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
+}
+
+TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
+  // Using PolymorphicIsEven() as a Matcher<int>.
+  const Matcher<int> m1 = PolymorphicIsEven();
+  EXPECT_TRUE(m1.Matches(42));
+  EXPECT_FALSE(m1.Matches(43));
+  EXPECT_EQ("is even", Describe(m1));
+
+  const Matcher<int> not_m1 = Not(m1);
+  EXPECT_EQ("is odd", Describe(not_m1));
+
+  EXPECT_EQ("% 2 == 0", Explain(m1, 42));
+
+  // Using PolymorphicIsEven() as a Matcher<char>.
+  const Matcher<char> m2 = PolymorphicIsEven();
+  EXPECT_TRUE(m2.Matches('\x42'));
+  EXPECT_FALSE(m2.Matches('\x43'));
+  EXPECT_EQ("is even", Describe(m2));
+
+  const Matcher<char> not_m2 = Not(m2);
+  EXPECT_EQ("is odd", Describe(not_m2));
+
+  EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
+}
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(MatcherCastTest);
+
+// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
+TEST_P(MatcherCastTestP, FromPolymorphicMatcher) {
+  Matcher<int16_t> m;
+  if (use_gtest_matcher_) {
+    m = MatcherCast<int16_t>(GtestGreaterThan(int64_t{5}));
+  } else {
+    m = MatcherCast<int16_t>(Gt(int64_t{5}));
+  }
+  EXPECT_TRUE(m.Matches(6));
+  EXPECT_FALSE(m.Matches(4));
+}
+
+// For testing casting matchers between compatible types.
+class IntValue {
+ public:
+  // An int can be statically (although not implicitly) cast to a
+  // IntValue.
+  explicit IntValue(int a_value) : value_(a_value) {}
+
+  int value() const { return value_; }
+
+ private:
+  int value_;
+};
+
+// For testing casting matchers between compatible types.
+bool IsPositiveIntValue(const IntValue& foo) { return foo.value() > 0; }
+
+// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
+// can be statically converted to U.
+TEST(MatcherCastTest, FromCompatibleType) {
+  Matcher<double> m1 = Eq(2.0);
+  Matcher<int> m2 = MatcherCast<int>(m1);
+  EXPECT_TRUE(m2.Matches(2));
+  EXPECT_FALSE(m2.Matches(3));
+
+  Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
+  Matcher<int> m4 = MatcherCast<int>(m3);
+  // In the following, the arguments 1 and 0 are statically converted
+  // to IntValue objects, and then tested by the IsPositiveIntValue()
+  // predicate.
+  EXPECT_TRUE(m4.Matches(1));
+  EXPECT_FALSE(m4.Matches(0));
+}
+
+// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
+TEST(MatcherCastTest, FromConstReferenceToNonReference) {
+  Matcher<const int&> m1 = Eq(0);
+  Matcher<int> m2 = MatcherCast<int>(m1);
+  EXPECT_TRUE(m2.Matches(0));
+  EXPECT_FALSE(m2.Matches(1));
+}
+
+// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
+TEST(MatcherCastTest, FromReferenceToNonReference) {
+  Matcher<int&> m1 = Eq(0);
+  Matcher<int> m2 = MatcherCast<int>(m1);
+  EXPECT_TRUE(m2.Matches(0));
+  EXPECT_FALSE(m2.Matches(1));
+}
+
+// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
+TEST(MatcherCastTest, FromNonReferenceToConstReference) {
+  Matcher<int> m1 = Eq(0);
+  Matcher<const int&> m2 = MatcherCast<const int&>(m1);
+  EXPECT_TRUE(m2.Matches(0));
+  EXPECT_FALSE(m2.Matches(1));
+}
+
+// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
+TEST(MatcherCastTest, FromNonReferenceToReference) {
+  Matcher<int> m1 = Eq(0);
+  Matcher<int&> m2 = MatcherCast<int&>(m1);
+  int n = 0;
+  EXPECT_TRUE(m2.Matches(n));
+  n = 1;
+  EXPECT_FALSE(m2.Matches(n));
+}
+
+// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
+TEST(MatcherCastTest, FromSameType) {
+  Matcher<int> m1 = Eq(0);
+  Matcher<int> m2 = MatcherCast<int>(m1);
+  EXPECT_TRUE(m2.Matches(0));
+  EXPECT_FALSE(m2.Matches(1));
+}
+
+// Tests that MatcherCast<T>(m) works when m is a value of the same type as the
+// value type of the Matcher.
+TEST(MatcherCastTest, FromAValue) {
+  Matcher<int> m = MatcherCast<int>(42);
+  EXPECT_TRUE(m.Matches(42));
+  EXPECT_FALSE(m.Matches(239));
+}
+
+// Tests that MatcherCast<T>(m) works when m is a value of the type implicitly
+// convertible to the value type of the Matcher.
+TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {
+  const int kExpected = 'c';
+  Matcher<int> m = MatcherCast<int>('c');
+  EXPECT_TRUE(m.Matches(kExpected));
+  EXPECT_FALSE(m.Matches(kExpected + 1));
+}
+
+struct NonImplicitlyConstructibleTypeWithOperatorEq {
+  friend bool operator==(
+      const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */,
+      int rhs) {
+    return 42 == rhs;
+  }
+  friend bool operator==(
+      int lhs,
+      const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) {
+    return lhs == 42;
+  }
+};
+
+// Tests that MatcherCast<T>(m) works when m is a neither a matcher nor
+// implicitly convertible to the value type of the Matcher, but the value type
+// of the matcher has operator==() overload accepting m.
+TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {
+  Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 =
+      MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42);
+  EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
+
+  Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 =
+      MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239);
+  EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
+
+  // When updating the following lines please also change the comment to
+  // namespace convertible_from_any.
+  Matcher<int> m3 =
+      MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq());
+  EXPECT_TRUE(m3.Matches(42));
+  EXPECT_FALSE(m3.Matches(239));
+}
+
+// ConvertibleFromAny does not work with MSVC. resulting in
+// error C2440: 'initializing': cannot convert from 'Eq' to 'M'
+// No constructor could take the source type, or constructor overload
+// resolution was ambiguous
+
+#if !defined _MSC_VER
+
+// The below ConvertibleFromAny struct is implicitly constructible from anything
+// and when in the same namespace can interact with other tests. In particular,
+// if it is in the same namespace as other tests and one removes
+//   NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...);
+// then the corresponding test still compiles (and it should not!) by implicitly
+// converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny
+// in m3.Matcher().
+namespace convertible_from_any {
+// Implicitly convertible from any type.
+struct ConvertibleFromAny {
+  ConvertibleFromAny(int a_value) : value(a_value) {}
+  template <typename T>
+  ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
+    ADD_FAILURE() << "Conversion constructor called";
+  }
+  int value;
+};
+
+bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
+  return a.value == b.value;
+}
+
+ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
+  return os << a.value;
+}
+
+TEST(MatcherCastTest, ConversionConstructorIsUsed) {
+  Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
+  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
+  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
+}
+
+TEST(MatcherCastTest, FromConvertibleFromAny) {
+  Matcher<ConvertibleFromAny> m =
+      MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
+  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
+  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
+}
+}  // namespace convertible_from_any
+
+#endif  // !defined _MSC_VER
+
+struct IntReferenceWrapper {
+  IntReferenceWrapper(const int& a_value) : value(&a_value) {}
+  const int* value;
+};
+
+bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
+  return a.value == b.value;
+}
+
+TEST(MatcherCastTest, ValueIsNotCopied) {
+  int n = 42;
+  Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
+  // Verify that the matcher holds a reference to n, not to its temporary copy.
+  EXPECT_TRUE(m.Matches(n));
+}
+
+class Base {
+ public:
+  virtual ~Base() {}
+  Base() {}
+
+ private:
+  Base(const Base&) = delete;
+  Base& operator=(const Base&) = delete;
+};
+
+class Derived : public Base {
+ public:
+  Derived() : Base() {}
+  int i;
+};
+
+class OtherDerived : public Base {};
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(SafeMatcherCastTest);
+
+// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
+TEST_P(SafeMatcherCastTestP, FromPolymorphicMatcher) {
+  Matcher<char> m2;
+  if (use_gtest_matcher_) {
+    m2 = SafeMatcherCast<char>(GtestGreaterThan(32));
+  } else {
+    m2 = SafeMatcherCast<char>(Gt(32));
+  }
+  EXPECT_TRUE(m2.Matches('A'));
+  EXPECT_FALSE(m2.Matches('\n'));
+}
+
+// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
+// T and U are arithmetic types and T can be losslessly converted to
+// U.
+TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
+  Matcher<double> m1 = DoubleEq(1.0);
+  Matcher<float> m2 = SafeMatcherCast<float>(m1);
+  EXPECT_TRUE(m2.Matches(1.0f));
+  EXPECT_FALSE(m2.Matches(2.0f));
+
+  Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
+  EXPECT_TRUE(m3.Matches('a'));
+  EXPECT_FALSE(m3.Matches('b'));
+}
+
+// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
+// are pointers or references to a derived and a base class, correspondingly.
+TEST(SafeMatcherCastTest, FromBaseClass) {
+  Derived d, d2;
+  Matcher<Base*> m1 = Eq(&d);
+  Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
+  EXPECT_TRUE(m2.Matches(&d));
+  EXPECT_FALSE(m2.Matches(&d2));
+
+  Matcher<Base&> m3 = Ref(d);
+  Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
+  EXPECT_TRUE(m4.Matches(d));
+  EXPECT_FALSE(m4.Matches(d2));
+}
+
+// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
+TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
+  int n = 0;
+  Matcher<const int&> m1 = Ref(n);
+  Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
+  int n1 = 0;
+  EXPECT_TRUE(m2.Matches(n));
+  EXPECT_FALSE(m2.Matches(n1));
+}
+
+// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
+TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
+  Matcher<std::unique_ptr<int>> m1 = IsNull();
+  Matcher<const std::unique_ptr<int>&> m2 =
+      SafeMatcherCast<const std::unique_ptr<int>&>(m1);
+  EXPECT_TRUE(m2.Matches(std::unique_ptr<int>()));
+  EXPECT_FALSE(m2.Matches(std::unique_ptr<int>(new int)));
+}
+
+// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
+TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
+  Matcher<int> m1 = Eq(0);
+  Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
+  int n = 0;
+  EXPECT_TRUE(m2.Matches(n));
+  n = 1;
+  EXPECT_FALSE(m2.Matches(n));
+}
+
+// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
+TEST(SafeMatcherCastTest, FromSameType) {
+  Matcher<int> m1 = Eq(0);
+  Matcher<int> m2 = SafeMatcherCast<int>(m1);
+  EXPECT_TRUE(m2.Matches(0));
+  EXPECT_FALSE(m2.Matches(1));
+}
+
+#if !defined _MSC_VER
+
+namespace convertible_from_any {
+TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
+  Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
+  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
+  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
+}
+
+TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
+  Matcher<ConvertibleFromAny> m =
+      SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
+  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
+  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
+}
+}  // namespace convertible_from_any
+
+#endif  // !defined _MSC_VER
+
+TEST(SafeMatcherCastTest, ValueIsNotCopied) {
+  int n = 42;
+  Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
+  // Verify that the matcher holds a reference to n, not to its temporary copy.
+  EXPECT_TRUE(m.Matches(n));
+}
+
+TEST(ExpectThat, TakesLiterals) {
+  EXPECT_THAT(1, 1);
+  EXPECT_THAT(1.0, 1.0);
+  EXPECT_THAT(std::string(), "");
+}
+
+TEST(ExpectThat, TakesFunctions) {
+  struct Helper {
+    static void Func() {}
+  };
+  void (*func)() = Helper::Func;
+  EXPECT_THAT(func, Helper::Func);
+  EXPECT_THAT(func, &Helper::Func);
+}
+
+// Tests that A<T>() matches any value of type T.
+TEST(ATest, MatchesAnyValue) {
+  // Tests a matcher for a value type.
+  Matcher<double> m1 = A<double>();
+  EXPECT_TRUE(m1.Matches(91.43));
+  EXPECT_TRUE(m1.Matches(-15.32));
+
+  // Tests a matcher for a reference type.
+  int a = 2;
+  int b = -6;
+  Matcher<int&> m2 = A<int&>();
+  EXPECT_TRUE(m2.Matches(a));
+  EXPECT_TRUE(m2.Matches(b));
+}
+
+TEST(ATest, WorksForDerivedClass) {
+  Base base;
+  Derived derived;
+  EXPECT_THAT(&base, A<Base*>());
+  // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
+  EXPECT_THAT(&derived, A<Base*>());
+  EXPECT_THAT(&derived, A<Derived*>());
+}
+
+// Tests that A<T>() describes itself properly.
+TEST(ATest, CanDescribeSelf) { EXPECT_EQ("is anything", Describe(A<bool>())); }
+
+// Tests that An<T>() matches any value of type T.
+TEST(AnTest, MatchesAnyValue) {
+  // Tests a matcher for a value type.
+  Matcher<int> m1 = An<int>();
+  EXPECT_TRUE(m1.Matches(9143));
+  EXPECT_TRUE(m1.Matches(-1532));
+
+  // Tests a matcher for a reference type.
+  int a = 2;
+  int b = -6;
+  Matcher<int&> m2 = An<int&>();
+  EXPECT_TRUE(m2.Matches(a));
+  EXPECT_TRUE(m2.Matches(b));
+}
+
+// Tests that An<T>() describes itself properly.
+TEST(AnTest, CanDescribeSelf) { EXPECT_EQ("is anything", Describe(An<int>())); }
+
+// Tests that _ can be used as a matcher for any type and matches any
+// value of that type.
+TEST(UnderscoreTest, MatchesAnyValue) {
+  // Uses _ as a matcher for a value type.
+  Matcher<int> m1 = _;
+  EXPECT_TRUE(m1.Matches(123));
+  EXPECT_TRUE(m1.Matches(-242));
+
+  // Uses _ as a matcher for a reference type.
+  bool a = false;
+  const bool b = true;
+  Matcher<const bool&> m2 = _;
+  EXPECT_TRUE(m2.Matches(a));
+  EXPECT_TRUE(m2.Matches(b));
+}
+
+// Tests that _ describes itself properly.
+TEST(UnderscoreTest, CanDescribeSelf) {
+  Matcher<int> m = _;
+  EXPECT_EQ("is anything", Describe(m));
+}
+
+// Tests that Eq(x) matches any value equal to x.
+TEST(EqTest, MatchesEqualValue) {
+  // 2 C-strings with same content but different addresses.
+  const char a1[] = "hi";
+  const char a2[] = "hi";
+
+  Matcher<const char*> m1 = Eq(a1);
+  EXPECT_TRUE(m1.Matches(a1));
+  EXPECT_FALSE(m1.Matches(a2));
+}
+
+// Tests that Eq(v) describes itself properly.
+
+class Unprintable {
+ public:
+  Unprintable() : c_('a') {}
+
+  bool operator==(const Unprintable& /* rhs */) const { return true; }
+  // -Wunused-private-field: dummy accessor for `c_`.
+  char dummy_c() { return c_; }
+
+ private:
+  char c_;
+};
+
+TEST(EqTest, CanDescribeSelf) {
+  Matcher<Unprintable> m = Eq(Unprintable());
+  EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
+}
+
+// Tests that Eq(v) can be used to match any type that supports
+// comparing with type T, where T is v's type.
+TEST(EqTest, IsPolymorphic) {
+  Matcher<int> m1 = Eq(1);
+  EXPECT_TRUE(m1.Matches(1));
+  EXPECT_FALSE(m1.Matches(2));
+
+  Matcher<char> m2 = Eq(1);
+  EXPECT_TRUE(m2.Matches('\1'));
+  EXPECT_FALSE(m2.Matches('a'));
+}
+
+// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
+TEST(TypedEqTest, ChecksEqualityForGivenType) {
+  Matcher<char> m1 = TypedEq<char>('a');
+  EXPECT_TRUE(m1.Matches('a'));
+  EXPECT_FALSE(m1.Matches('b'));
+
+  Matcher<int> m2 = TypedEq<int>(6);
+  EXPECT_TRUE(m2.Matches(6));
+  EXPECT_FALSE(m2.Matches(7));
+}
+
+// Tests that TypedEq(v) describes itself properly.
+TEST(TypedEqTest, CanDescribeSelf) {
+  EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
+}
+
+// Tests that TypedEq<T>(v) has type Matcher<T>.
+
+// Type<T>::IsTypeOf(v) compiles if and only if the type of value v is T, where
+// T is a "bare" type (i.e. not in the form of const U or U&).  If v's type is
+// not T, the compiler will generate a message about "undefined reference".
+template <typename T>
+struct Type {
+  static bool IsTypeOf(const T& /* v */) { return true; }
+
+  template <typename T2>
+  static void IsTypeOf(T2 v);
+};
+
+TEST(TypedEqTest, HasSpecifiedType) {
+  // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
+  Type<Matcher<int>>::IsTypeOf(TypedEq<int>(5));
+  Type<Matcher<double>>::IsTypeOf(TypedEq<double>(5));
+}
+
+// Tests that Ge(v) matches anything >= v.
+TEST(GeTest, ImplementsGreaterThanOrEqual) {
+  Matcher<int> m1 = Ge(0);
+  EXPECT_TRUE(m1.Matches(1));
+  EXPECT_TRUE(m1.Matches(0));
+  EXPECT_FALSE(m1.Matches(-1));
+}
+
+// Tests that Ge(v) describes itself properly.
+TEST(GeTest, CanDescribeSelf) {
+  Matcher<int> m = Ge(5);
+  EXPECT_EQ("is >= 5", Describe(m));
+}
+
+// Tests that Gt(v) matches anything > v.
+TEST(GtTest, ImplementsGreaterThan) {
+  Matcher<double> m1 = Gt(0);
+  EXPECT_TRUE(m1.Matches(1.0));
+  EXPECT_FALSE(m1.Matches(0.0));
+  EXPECT_FALSE(m1.Matches(-1.0));
+}
+
+// Tests that Gt(v) describes itself properly.
+TEST(GtTest, CanDescribeSelf) {
+  Matcher<int> m = Gt(5);
+  EXPECT_EQ("is > 5", Describe(m));
+}
+
+// Tests that Le(v) matches anything <= v.
+TEST(LeTest, ImplementsLessThanOrEqual) {
+  Matcher<char> m1 = Le('b');
+  EXPECT_TRUE(m1.Matches('a'));
+  EXPECT_TRUE(m1.Matches('b'));
+  EXPECT_FALSE(m1.Matches('c'));
+}
+
+// Tests that Le(v) describes itself properly.
+TEST(LeTest, CanDescribeSelf) {
+  Matcher<int> m = Le(5);
+  EXPECT_EQ("is <= 5", Describe(m));
+}
+
+// Tests that Lt(v) matches anything < v.
+TEST(LtTest, ImplementsLessThan) {
+  Matcher<const std::string&> m1 = Lt("Hello");
+  EXPECT_TRUE(m1.Matches("Abc"));
+  EXPECT_FALSE(m1.Matches("Hello"));
+  EXPECT_FALSE(m1.Matches("Hello, world!"));
+}
+
+// Tests that Lt(v) describes itself properly.
+TEST(LtTest, CanDescribeSelf) {
+  Matcher<int> m = Lt(5);
+  EXPECT_EQ("is < 5", Describe(m));
+}
+
+// Tests that Ne(v) matches anything != v.
+TEST(NeTest, ImplementsNotEqual) {
+  Matcher<int> m1 = Ne(0);
+  EXPECT_TRUE(m1.Matches(1));
+  EXPECT_TRUE(m1.Matches(-1));
+  EXPECT_FALSE(m1.Matches(0));
+}
+
+// Tests that Ne(v) describes itself properly.
+TEST(NeTest, CanDescribeSelf) {
+  Matcher<int> m = Ne(5);
+  EXPECT_EQ("isn't equal to 5", Describe(m));
+}
+
+class MoveOnly {
+ public:
+  explicit MoveOnly(int i) : i_(i) {}
+  MoveOnly(const MoveOnly&) = delete;
+  MoveOnly(MoveOnly&&) = default;
+  MoveOnly& operator=(const MoveOnly&) = delete;
+  MoveOnly& operator=(MoveOnly&&) = default;
+
+  bool operator==(const MoveOnly& other) const { return i_ == other.i_; }
+  bool operator!=(const MoveOnly& other) const { return i_ != other.i_; }
+  bool operator<(const MoveOnly& other) const { return i_ < other.i_; }
+  bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; }
+  bool operator>(const MoveOnly& other) const { return i_ > other.i_; }
+  bool operator>=(const MoveOnly& other) const { return i_ >= other.i_; }
+
+ private:
+  int i_;
+};
+
+struct MoveHelper {
+  MOCK_METHOD1(Call, void(MoveOnly));
+};
+
+// Disable this test in VS 2015 (version 14), where it fails when SEH is enabled
+#if defined(_MSC_VER) && (_MSC_VER < 1910)
+TEST(ComparisonBaseTest, DISABLED_WorksWithMoveOnly) {
+#else
+TEST(ComparisonBaseTest, WorksWithMoveOnly) {
+#endif
+  MoveOnly m{0};
+  MoveHelper helper;
+
+  EXPECT_CALL(helper, Call(Eq(ByRef(m))));
+  helper.Call(MoveOnly(0));
+  EXPECT_CALL(helper, Call(Ne(ByRef(m))));
+  helper.Call(MoveOnly(1));
+  EXPECT_CALL(helper, Call(Le(ByRef(m))));
+  helper.Call(MoveOnly(0));
+  EXPECT_CALL(helper, Call(Lt(ByRef(m))));
+  helper.Call(MoveOnly(-1));
+  EXPECT_CALL(helper, Call(Ge(ByRef(m))));
+  helper.Call(MoveOnly(0));
+  EXPECT_CALL(helper, Call(Gt(ByRef(m))));
+  helper.Call(MoveOnly(1));
+}
+
+// Tests that IsNull() matches any NULL pointer of any type.
+TEST(IsNullTest, MatchesNullPointer) {
+  Matcher<int*> m1 = IsNull();
+  int* p1 = nullptr;
+  int n = 0;
+  EXPECT_TRUE(m1.Matches(p1));
+  EXPECT_FALSE(m1.Matches(&n));
+
+  Matcher<const char*> m2 = IsNull();
+  const char* p2 = nullptr;
+  EXPECT_TRUE(m2.Matches(p2));
+  EXPECT_FALSE(m2.Matches("hi"));
+
+  Matcher<void*> m3 = IsNull();
+  void* p3 = nullptr;
+  EXPECT_TRUE(m3.Matches(p3));
+  EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
+}
+
+TEST(IsNullTest, StdFunction) {
+  const Matcher<std::function<void()>> m = IsNull();
+
+  EXPECT_TRUE(m.Matches(std::function<void()>()));
+  EXPECT_FALSE(m.Matches([] {}));
+}
+
+// Tests that IsNull() describes itself properly.
+TEST(IsNullTest, CanDescribeSelf) {
+  Matcher<int*> m = IsNull();
+  EXPECT_EQ("is NULL", Describe(m));
+  EXPECT_EQ("isn't NULL", DescribeNegation(m));
+}
+
+// Tests that NotNull() matches any non-NULL pointer of any type.
+TEST(NotNullTest, MatchesNonNullPointer) {
+  Matcher<int*> m1 = NotNull();
+  int* p1 = nullptr;
+  int n = 0;
+  EXPECT_FALSE(m1.Matches(p1));
+  EXPECT_TRUE(m1.Matches(&n));
+
+  Matcher<const char*> m2 = NotNull();
+  const char* p2 = nullptr;
+  EXPECT_FALSE(m2.Matches(p2));
+  EXPECT_TRUE(m2.Matches("hi"));
+}
+
+TEST(NotNullTest, LinkedPtr) {
+  const Matcher<std::shared_ptr<int>> m = NotNull();
+  const std::shared_ptr<int> null_p;
+  const std::shared_ptr<int> non_null_p(new int);
+
+  EXPECT_FALSE(m.Matches(null_p));
+  EXPECT_TRUE(m.Matches(non_null_p));
+}
+
+TEST(NotNullTest, ReferenceToConstLinkedPtr) {
+  const Matcher<const std::shared_ptr<double>&> m = NotNull();
+  const std::shared_ptr<double> null_p;
+  const std::shared_ptr<double> non_null_p(new double);
+
+  EXPECT_FALSE(m.Matches(null_p));
+  EXPECT_TRUE(m.Matches(non_null_p));
+}
+
+TEST(NotNullTest, StdFunction) {
+  const Matcher<std::function<void()>> m = NotNull();
+
+  EXPECT_TRUE(m.Matches([] {}));
+  EXPECT_FALSE(m.Matches(std::function<void()>()));
+}
+
+// Tests that NotNull() describes itself properly.
+TEST(NotNullTest, CanDescribeSelf) {
+  Matcher<int*> m = NotNull();
+  EXPECT_EQ("isn't NULL", Describe(m));
+}
+
+// Tests that Ref(variable) matches an argument that references
+// 'variable'.
+TEST(RefTest, MatchesSameVariable) {
+  int a = 0;
+  int b = 0;
+  Matcher<int&> m = Ref(a);
+  EXPECT_TRUE(m.Matches(a));
+  EXPECT_FALSE(m.Matches(b));
+}
+
+// Tests that Ref(variable) describes itself properly.
+TEST(RefTest, CanDescribeSelf) {
+  int n = 5;
+  Matcher<int&> m = Ref(n);
+  stringstream ss;
+  ss << "references the variable @" << &n << " 5";
+  EXPECT_EQ(ss.str(), Describe(m));
+}
+
+// Test that Ref(non_const_varialbe) can be used as a matcher for a
+// const reference.
+TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
+  int a = 0;
+  int b = 0;
+  Matcher<const int&> m = Ref(a);
+  EXPECT_TRUE(m.Matches(a));
+  EXPECT_FALSE(m.Matches(b));
+}
+
+// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
+// used wherever Ref(base) can be used (Ref(derived) is a sub-type
+// of Ref(base), but not vice versa.
+
+TEST(RefTest, IsCovariant) {
+  Base base, base2;
+  Derived derived;
+  Matcher<const Base&> m1 = Ref(base);
+  EXPECT_TRUE(m1.Matches(base));
+  EXPECT_FALSE(m1.Matches(base2));
+  EXPECT_FALSE(m1.Matches(derived));
+
+  m1 = Ref(derived);
+  EXPECT_TRUE(m1.Matches(derived));
+  EXPECT_FALSE(m1.Matches(base));
+  EXPECT_FALSE(m1.Matches(base2));
+}
+
+TEST(RefTest, ExplainsResult) {
+  int n = 0;
+  EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
+              StartsWith("which is located @"));
+
+  int m = 0;
+  EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
+              StartsWith("which is located @"));
+}
+
+// Tests string comparison matchers.
+
+template <typename T = std::string>
+std::string FromStringLike(internal::StringLike<T> str) {
+  return std::string(str);
+}
+
+TEST(StringLike, TestConversions) {
+  EXPECT_EQ("foo", FromStringLike("foo"));
+  EXPECT_EQ("foo", FromStringLike(std::string("foo")));
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+  EXPECT_EQ("foo", FromStringLike(internal::StringView("foo")));
+#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
+
+  // Non deducible types.
+  EXPECT_EQ("", FromStringLike({}));
+  EXPECT_EQ("foo", FromStringLike({'f', 'o', 'o'}));
+  const char buf[] = "foo";
+  EXPECT_EQ("foo", FromStringLike({buf, buf + 3}));
+}
+
+TEST(StrEqTest, MatchesEqualString) {
+  Matcher<const char*> m = StrEq(std::string("Hello"));
+  EXPECT_TRUE(m.Matches("Hello"));
+  EXPECT_FALSE(m.Matches("hello"));
+  EXPECT_FALSE(m.Matches(nullptr));
+
+  Matcher<const std::string&> m2 = StrEq("Hello");
+  EXPECT_TRUE(m2.Matches("Hello"));
+  EXPECT_FALSE(m2.Matches("Hi"));
+
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+  Matcher<const internal::StringView&> m3 =
+      StrEq(internal::StringView("Hello"));
+  EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
+  EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
+  EXPECT_FALSE(m3.Matches(internal::StringView()));
+
+  Matcher<const internal::StringView&> m_empty = StrEq("");
+  EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
+  EXPECT_TRUE(m_empty.Matches(internal::StringView()));
+  EXPECT_FALSE(m_empty.Matches(internal::StringView("hello")));
+#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
+}
+
+TEST(StrEqTest, CanDescribeSelf) {
+  Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
+  EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
+            Describe(m));
+
+  std::string str("01204500800");
+  str[3] = '\0';
+  Matcher<std::string> m2 = StrEq(str);
+  EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
+  str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
+  Matcher<std::string> m3 = StrEq(str);
+  EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
+}
+
+TEST(StrNeTest, MatchesUnequalString) {
+  Matcher<const char*> m = StrNe("Hello");
+  EXPECT_TRUE(m.Matches(""));
+  EXPECT_TRUE(m.Matches(nullptr));
+  EXPECT_FALSE(m.Matches("Hello"));
+
+  Matcher<std::string> m2 = StrNe(std::string("Hello"));
+  EXPECT_TRUE(m2.Matches("hello"));
+  EXPECT_FALSE(m2.Matches("Hello"));
+
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+  Matcher<const internal::StringView> m3 = StrNe(internal::StringView("Hello"));
+  EXPECT_TRUE(m3.Matches(internal::StringView("")));
+  EXPECT_TRUE(m3.Matches(internal::StringView()));
+  EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
+#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
+}
+
+TEST(StrNeTest, CanDescribeSelf) {
+  Matcher<const char*> m = StrNe("Hi");
+  EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
+}
+
+TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
+  Matcher<const char*> m = StrCaseEq(std::string("Hello"));
+  EXPECT_TRUE(m.Matches("Hello"));
+  EXPECT_TRUE(m.Matches("hello"));
+  EXPECT_FALSE(m.Matches("Hi"));
+  EXPECT_FALSE(m.Matches(nullptr));
+
+  Matcher<const std::string&> m2 = StrCaseEq("Hello");
+  EXPECT_TRUE(m2.Matches("hello"));
+  EXPECT_FALSE(m2.Matches("Hi"));
+
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+  Matcher<const internal::StringView&> m3 =
+      StrCaseEq(internal::StringView("Hello"));
+  EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
+  EXPECT_TRUE(m3.Matches(internal::StringView("hello")));
+  EXPECT_FALSE(m3.Matches(internal::StringView("Hi")));
+  EXPECT_FALSE(m3.Matches(internal::StringView()));
+#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
+}
+
+TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
+  std::string str1("oabocdooeoo");
+  std::string str2("OABOCDOOEOO");
+  Matcher<const std::string&> m0 = StrCaseEq(str1);
+  EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
+
+  str1[3] = str2[3] = '\0';
+  Matcher<const std::string&> m1 = StrCaseEq(str1);
+  EXPECT_TRUE(m1.Matches(str2));
+
+  str1[0] = str1[6] = str1[7] = str1[10] = '\0';
+  str2[0] = str2[6] = str2[7] = str2[10] = '\0';
+  Matcher<const std::string&> m2 = StrCaseEq(str1);
+  str1[9] = str2[9] = '\0';
+  EXPECT_FALSE(m2.Matches(str2));
+
+  Matcher<const std::string&> m3 = StrCaseEq(str1);
+  EXPECT_TRUE(m3.Matches(str2));
+
+  EXPECT_FALSE(m3.Matches(str2 + "x"));
+  str2.append(1, '\0');
+  EXPECT_FALSE(m3.Matches(str2));
+  EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
+}
+
+TEST(StrCaseEqTest, CanDescribeSelf) {
+  Matcher<std::string> m = StrCaseEq("Hi");
+  EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
+}
+
+TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
+  Matcher<const char*> m = StrCaseNe("Hello");
+  EXPECT_TRUE(m.Matches("Hi"));
+  EXPECT_TRUE(m.Matches(nullptr));
+  EXPECT_FALSE(m.Matches("Hello"));
+  EXPECT_FALSE(m.Matches("hello"));
+
+  Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
+  EXPECT_TRUE(m2.Matches(""));
+  EXPECT_FALSE(m2.Matches("Hello"));
+
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+  Matcher<const internal::StringView> m3 =
+      StrCaseNe(internal::StringView("Hello"));
+  EXPECT_TRUE(m3.Matches(internal::StringView("Hi")));
+  EXPECT_TRUE(m3.Matches(internal::StringView()));
+  EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
+  EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
+#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
+}
+
+TEST(StrCaseNeTest, CanDescribeSelf) {
+  Matcher<const char*> m = StrCaseNe("Hi");
+  EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
+}
+
+// Tests that HasSubstr() works for matching string-typed values.
+TEST(HasSubstrTest, WorksForStringClasses) {
+  const Matcher<std::string> m1 = HasSubstr("foo");
+  EXPECT_TRUE(m1.Matches(std::string("I love food.")));
+  EXPECT_FALSE(m1.Matches(std::string("tofo")));
+
+  const Matcher<const std::string&> m2 = HasSubstr("foo");
+  EXPECT_TRUE(m2.Matches(std::string("I love food.")));
+  EXPECT_FALSE(m2.Matches(std::string("tofo")));
+
+  const Matcher<std::string> m_empty = HasSubstr("");
+  EXPECT_TRUE(m_empty.Matches(std::string()));
+  EXPECT_TRUE(m_empty.Matches(std::string("not empty")));
+}
+
+// Tests that HasSubstr() works for matching C-string-typed values.
+TEST(HasSubstrTest, WorksForCStrings) {
+  const Matcher<char*> m1 = HasSubstr("foo");
+  EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
+  EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
+  EXPECT_FALSE(m1.Matches(nullptr));
+
+  const Matcher<const char*> m2 = HasSubstr("foo");
+  EXPECT_TRUE(m2.Matches("I love food."));
+  EXPECT_FALSE(m2.Matches("tofo"));
+  EXPECT_FALSE(m2.Matches(nullptr));
+
+  const Matcher<const char*> m_empty = HasSubstr("");
+  EXPECT_TRUE(m_empty.Matches("not empty"));
+  EXPECT_TRUE(m_empty.Matches(""));
+  EXPECT_FALSE(m_empty.Matches(nullptr));
+}
+
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+// Tests that HasSubstr() works for matching StringView-typed values.
+TEST(HasSubstrTest, WorksForStringViewClasses) {
+  const Matcher<internal::StringView> m1 =
+      HasSubstr(internal::StringView("foo"));
+  EXPECT_TRUE(m1.Matches(internal::StringView("I love food.")));
+  EXPECT_FALSE(m1.Matches(internal::StringView("tofo")));
+  EXPECT_FALSE(m1.Matches(internal::StringView()));
+
+  const Matcher<const internal::StringView&> m2 = HasSubstr("foo");
+  EXPECT_TRUE(m2.Matches(internal::StringView("I love food.")));
+  EXPECT_FALSE(m2.Matches(internal::StringView("tofo")));
+  EXPECT_FALSE(m2.Matches(internal::StringView()));
+
+  const Matcher<const internal::StringView&> m3 = HasSubstr("");
+  EXPECT_TRUE(m3.Matches(internal::StringView("foo")));
+  EXPECT_TRUE(m3.Matches(internal::StringView("")));
+  EXPECT_TRUE(m3.Matches(internal::StringView()));
+}
+#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
+
+// Tests that HasSubstr(s) describes itself properly.
+TEST(HasSubstrTest, CanDescribeSelf) {
+  Matcher<std::string> m = HasSubstr("foo\n\"");
+  EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
+}
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(KeyTest);
+
+TEST(KeyTest, CanDescribeSelf) {
+  Matcher<const pair<std::string, int>&> m = Key("foo");
+  EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
+  EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
+}
+
+TEST_P(KeyTestP, ExplainsResult) {
+  Matcher<pair<int, bool>> m = Key(GreaterThan(10));
+  EXPECT_EQ("whose first field is a value which is 5 less than 10",
+            Explain(m, make_pair(5, true)));
+  EXPECT_EQ("whose first field is a value which is 5 more than 10",
+            Explain(m, make_pair(15, true)));
+}
+
+TEST(KeyTest, MatchesCorrectly) {
+  pair<int, std::string> p(25, "foo");
+  EXPECT_THAT(p, Key(25));
+  EXPECT_THAT(p, Not(Key(42)));
+  EXPECT_THAT(p, Key(Ge(20)));
+  EXPECT_THAT(p, Not(Key(Lt(25))));
+}
+
+TEST(KeyTest, WorksWithMoveOnly) {
+  pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
+  EXPECT_THAT(p, Key(Eq(nullptr)));
+}
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(PairTest);
+
+template <size_t I>
+struct Tag {};
+
+struct PairWithGet {
+  int member_1;
+  std::string member_2;
+  using first_type = int;
+  using second_type = std::string;
+
+  const int& GetImpl(Tag<0>) const { return member_1; }
+  const std::string& GetImpl(Tag<1>) const { return member_2; }
+};
+template <size_t I>
+auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) {
+  return value.GetImpl(Tag<I>());
+}
+TEST(PairTest, MatchesPairWithGetCorrectly) {
+  PairWithGet p{25, "foo"};
+  EXPECT_THAT(p, Key(25));
+  EXPECT_THAT(p, Not(Key(42)));
+  EXPECT_THAT(p, Key(Ge(20)));
+  EXPECT_THAT(p, Not(Key(Lt(25))));
+
+  std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
+  EXPECT_THAT(v, Contains(Key(29)));
+}
+
+TEST(KeyTest, SafelyCastsInnerMatcher) {
+  Matcher<int> is_positive = Gt(0);
+  Matcher<int> is_negative = Lt(0);
+  pair<char, bool> p('a', true);
+  EXPECT_THAT(p, Key(is_positive));
+  EXPECT_THAT(p, Not(Key(is_negative)));
+}
+
+TEST(KeyTest, InsideContainsUsingMap) {
+  map<int, char> container;
+  container.insert(make_pair(1, 'a'));
+  container.insert(make_pair(2, 'b'));
+  container.insert(make_pair(4, 'c'));
+  EXPECT_THAT(container, Contains(Key(1)));
+  EXPECT_THAT(container, Not(Contains(Key(3))));
+}
+
+TEST(KeyTest, InsideContainsUsingMultimap) {
+  multimap<int, char> container;
+  container.insert(make_pair(1, 'a'));
+  container.insert(make_pair(2, 'b'));
+  container.insert(make_pair(4, 'c'));
+
+  EXPECT_THAT(container, Not(Contains(Key(25))));
+  container.insert(make_pair(25, 'd'));
+  EXPECT_THAT(container, Contains(Key(25)));
+  container.insert(make_pair(25, 'e'));
+  EXPECT_THAT(container, Contains(Key(25)));
+
+  EXPECT_THAT(container, Contains(Key(1)));
+  EXPECT_THAT(container, Not(Contains(Key(3))));
+}
+
+TEST(PairTest, Typing) {
+  // Test verifies the following type conversions can be compiled.
+  Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
+  Matcher<const pair<const char*, int>> m2 = Pair("foo", 42);
+  Matcher<pair<const char*, int>> m3 = Pair("foo", 42);
+
+  Matcher<pair<int, const std::string>> m4 = Pair(25, "42");
+  Matcher<pair<const std::string, int>> m5 = Pair("25", 42);
+}
+
+TEST(PairTest, CanDescribeSelf) {
+  Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
+  EXPECT_EQ(
+      "has a first field that is equal to \"foo\""
+      ", and has a second field that is equal to 42",
+      Describe(m1));
+  EXPECT_EQ(
+      "has a first field that isn't equal to \"foo\""
+      ", or has a second field that isn't equal to 42",
+      DescribeNegation(m1));
+  // Double and triple negation (1 or 2 times not and description of negation).
+  Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
+  EXPECT_EQ(
+      "has a first field that isn't equal to 13"
+      ", and has a second field that is equal to 42",
+      DescribeNegation(m2));
+}
+
+TEST_P(PairTestP, CanExplainMatchResultTo) {
+  // If neither field matches, Pair() should explain about the first
+  // field.
+  const Matcher<pair<int, int>> m = Pair(GreaterThan(0), GreaterThan(0));
+  EXPECT_EQ("whose first field does not match, which is 1 less than 0",
+            Explain(m, make_pair(-1, -2)));
+
+  // If the first field matches but the second doesn't, Pair() should
+  // explain about the second field.
+  EXPECT_EQ("whose second field does not match, which is 2 less than 0",
+            Explain(m, make_pair(1, -2)));
+
+  // If the first field doesn't match but the second does, Pair()
+  // should explain about the first field.
+  EXPECT_EQ("whose first field does not match, which is 1 less than 0",
+            Explain(m, make_pair(-1, 2)));
+
+  // If both fields match, Pair() should explain about them both.
+  EXPECT_EQ(
+      "whose both fields match, where the first field is a value "
+      "which is 1 more than 0, and the second field is a value "
+      "which is 2 more than 0",
+      Explain(m, make_pair(1, 2)));
+
+  // If only the first match has an explanation, only this explanation should
+  // be printed.
+  const Matcher<pair<int, int>> explain_first = Pair(GreaterThan(0), 0);
+  EXPECT_EQ(
+      "whose both fields match, where the first field is a value "
+      "which is 1 more than 0",
+      Explain(explain_first, make_pair(1, 0)));
+
+  // If only the second match has an explanation, only this explanation should
+  // be printed.
+  const Matcher<pair<int, int>> explain_second = Pair(0, GreaterThan(0));
+  EXPECT_EQ(
+      "whose both fields match, where the second field is a value "
+      "which is 1 more than 0",
+      Explain(explain_second, make_pair(0, 1)));
+}
+
+TEST(PairTest, MatchesCorrectly) {
+  pair<int, std::string> p(25, "foo");
+
+  // Both fields match.
+  EXPECT_THAT(p, Pair(25, "foo"));
+  EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
+
+  // 'first' doesnt' match, but 'second' matches.
+  EXPECT_THAT(p, Not(Pair(42, "foo")));
+  EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
+
+  // 'first' matches, but 'second' doesn't match.
+  EXPECT_THAT(p, Not(Pair(25, "bar")));
+  EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
+
+  // Neither field matches.
+  EXPECT_THAT(p, Not(Pair(13, "bar")));
+  EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
+}
+
+TEST(PairTest, WorksWithMoveOnly) {
+  pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
+  p.second.reset(new int(7));
+  EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));
+}
+
+TEST(PairTest, SafelyCastsInnerMatchers) {
+  Matcher<int> is_positive = Gt(0);
+  Matcher<int> is_negative = Lt(0);
+  pair<char, bool> p('a', true);
+  EXPECT_THAT(p, Pair(is_positive, _));
+  EXPECT_THAT(p, Not(Pair(is_negative, _)));
+  EXPECT_THAT(p, Pair(_, is_positive));
+  EXPECT_THAT(p, Not(Pair(_, is_negative)));
+}
+
+TEST(PairTest, InsideContainsUsingMap) {
+  map<int, char> container;
+  container.insert(make_pair(1, 'a'));
+  container.insert(make_pair(2, 'b'));
+  container.insert(make_pair(4, 'c'));
+  EXPECT_THAT(container, Contains(Pair(1, 'a')));
+  EXPECT_THAT(container, Contains(Pair(1, _)));
+  EXPECT_THAT(container, Contains(Pair(_, 'a')));
+  EXPECT_THAT(container, Not(Contains(Pair(3, _))));
+}
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(FieldsAreTest);
+
+TEST(FieldsAreTest, MatchesCorrectly) {
+  std::tuple<int, std::string, double> p(25, "foo", .5);
+
+  // All fields match.
+  EXPECT_THAT(p, FieldsAre(25, "foo", .5));
+  EXPECT_THAT(p, FieldsAre(Ge(20), HasSubstr("o"), DoubleEq(.5)));
+
+  // Some don't match.
+  EXPECT_THAT(p, Not(FieldsAre(26, "foo", .5)));
+  EXPECT_THAT(p, Not(FieldsAre(25, "fo", .5)));
+  EXPECT_THAT(p, Not(FieldsAre(25, "foo", .6)));
+}
+
+TEST(FieldsAreTest, CanDescribeSelf) {
+  Matcher<const pair<std::string, int>&> m1 = FieldsAre("foo", 42);
+  EXPECT_EQ(
+      "has field #0 that is equal to \"foo\""
+      ", and has field #1 that is equal to 42",
+      Describe(m1));
+  EXPECT_EQ(
+      "has field #0 that isn't equal to \"foo\""
+      ", or has field #1 that isn't equal to 42",
+      DescribeNegation(m1));
+}
+
+TEST_P(FieldsAreTestP, CanExplainMatchResultTo) {
+  // The first one that fails is the one that gives the error.
+  Matcher<std::tuple<int, int, int>> m =
+      FieldsAre(GreaterThan(0), GreaterThan(0), GreaterThan(0));
+
+  EXPECT_EQ("whose field #0 does not match, which is 1 less than 0",
+            Explain(m, std::make_tuple(-1, -2, -3)));
+  EXPECT_EQ("whose field #1 does not match, which is 2 less than 0",
+            Explain(m, std::make_tuple(1, -2, -3)));
+  EXPECT_EQ("whose field #2 does not match, which is 3 less than 0",
+            Explain(m, std::make_tuple(1, 2, -3)));
+
+  // If they all match, we get a long explanation of success.
+  EXPECT_EQ(
+      "whose all elements match, "
+      "where field #0 is a value which is 1 more than 0"
+      ", and field #1 is a value which is 2 more than 0"
+      ", and field #2 is a value which is 3 more than 0",
+      Explain(m, std::make_tuple(1, 2, 3)));
+
+  // Only print those that have an explanation.
+  m = FieldsAre(GreaterThan(0), 0, GreaterThan(0));
+  EXPECT_EQ(
+      "whose all elements match, "
+      "where field #0 is a value which is 1 more than 0"
+      ", and field #2 is a value which is 3 more than 0",
+      Explain(m, std::make_tuple(1, 0, 3)));
+
+  // If only one has an explanation, then print that one.
+  m = FieldsAre(0, GreaterThan(0), 0);
+  EXPECT_EQ(
+      "whose all elements match, "
+      "where field #1 is a value which is 1 more than 0",
+      Explain(m, std::make_tuple(0, 1, 0)));
+}
+
+#if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
+TEST(FieldsAreTest, StructuredBindings) {
+  // testing::FieldsAre can also match aggregates and such with C++17 and up.
+  struct MyType {
+    int i;
+    std::string str;
+  };
+  EXPECT_THAT((MyType{17, "foo"}), FieldsAre(Eq(17), HasSubstr("oo")));
+
+  // Test all the supported arities.
+  struct MyVarType1 {
+    int a;
+  };
+  EXPECT_THAT(MyVarType1{}, FieldsAre(0));
+  struct MyVarType2 {
+    int a, b;
+  };
+  EXPECT_THAT(MyVarType2{}, FieldsAre(0, 0));
+  struct MyVarType3 {
+    int a, b, c;
+  };
+  EXPECT_THAT(MyVarType3{}, FieldsAre(0, 0, 0));
+  struct MyVarType4 {
+    int a, b, c, d;
+  };
+  EXPECT_THAT(MyVarType4{}, FieldsAre(0, 0, 0, 0));
+  struct MyVarType5 {
+    int a, b, c, d, e;
+  };
+  EXPECT_THAT(MyVarType5{}, FieldsAre(0, 0, 0, 0, 0));
+  struct MyVarType6 {
+    int a, b, c, d, e, f;
+  };
+  EXPECT_THAT(MyVarType6{}, FieldsAre(0, 0, 0, 0, 0, 0));
+  struct MyVarType7 {
+    int a, b, c, d, e, f, g;
+  };
+  EXPECT_THAT(MyVarType7{}, FieldsAre(0, 0, 0, 0, 0, 0, 0));
+  struct MyVarType8 {
+    int a, b, c, d, e, f, g, h;
+  };
+  EXPECT_THAT(MyVarType8{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0));
+  struct MyVarType9 {
+    int a, b, c, d, e, f, g, h, i;
+  };
+  EXPECT_THAT(MyVarType9{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0));
+  struct MyVarType10 {
+    int a, b, c, d, e, f, g, h, i, j;
+  };
+  EXPECT_THAT(MyVarType10{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
+  struct MyVarType11 {
+    int a, b, c, d, e, f, g, h, i, j, k;
+  };
+  EXPECT_THAT(MyVarType11{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
+  struct MyVarType12 {
+    int a, b, c, d, e, f, g, h, i, j, k, l;
+  };
+  EXPECT_THAT(MyVarType12{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
+  struct MyVarType13 {
+    int a, b, c, d, e, f, g, h, i, j, k, l, m;
+  };
+  EXPECT_THAT(MyVarType13{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
+  struct MyVarType14 {
+    int a, b, c, d, e, f, g, h, i, j, k, l, m, n;
+  };
+  EXPECT_THAT(MyVarType14{},
+              FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
+  struct MyVarType15 {
+    int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o;
+  };
+  EXPECT_THAT(MyVarType15{},
+              FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
+  struct MyVarType16 {
+    int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p;
+  };
+  EXPECT_THAT(MyVarType16{},
+              FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
+}
+#endif
+
+TEST(PairTest, UseGetInsteadOfMembers) {
+  PairWithGet pair{7, "ABC"};
+  EXPECT_THAT(pair, Pair(7, "ABC"));
+  EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB")));
+  EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC")));
+
+  std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
+  EXPECT_THAT(v,
+              ElementsAre(Pair(11, std::string("Foo")), Pair(Ge(10), Not(""))));
+}
+
+// Tests StartsWith(s).
+
+TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
+  const Matcher<const char*> m1 = StartsWith(std::string(""));
+  EXPECT_TRUE(m1.Matches("Hi"));
+  EXPECT_TRUE(m1.Matches(""));
+  EXPECT_FALSE(m1.Matches(nullptr));
+
+  const Matcher<const std::string&> m2 = StartsWith("Hi");
+  EXPECT_TRUE(m2.Matches("Hi"));
+  EXPECT_TRUE(m2.Matches("Hi Hi!"));
+  EXPECT_TRUE(m2.Matches("High"));
+  EXPECT_FALSE(m2.Matches("H"));
+  EXPECT_FALSE(m2.Matches(" Hi"));
+
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+  const Matcher<internal::StringView> m_empty =
+      StartsWith(internal::StringView(""));
+  EXPECT_TRUE(m_empty.Matches(internal::StringView()));
+  EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
+  EXPECT_TRUE(m_empty.Matches(internal::StringView("not empty")));
+#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
+}
+
+TEST(StartsWithTest, CanDescribeSelf) {
+  Matcher<const std::string> m = StartsWith("Hi");
+  EXPECT_EQ("starts with \"Hi\"", Describe(m));
+}
+
+// Tests EndsWith(s).
+
+TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
+  const Matcher<const char*> m1 = EndsWith("");
+  EXPECT_TRUE(m1.Matches("Hi"));
+  EXPECT_TRUE(m1.Matches(""));
+  EXPECT_FALSE(m1.Matches(nullptr));
+
+  const Matcher<const std::string&> m2 = EndsWith(std::string("Hi"));
+  EXPECT_TRUE(m2.Matches("Hi"));
+  EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
+  EXPECT_TRUE(m2.Matches("Super Hi"));
+  EXPECT_FALSE(m2.Matches("i"));
+  EXPECT_FALSE(m2.Matches("Hi "));
+
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+  const Matcher<const internal::StringView&> m4 =
+      EndsWith(internal::StringView(""));
+  EXPECT_TRUE(m4.Matches("Hi"));
+  EXPECT_TRUE(m4.Matches(""));
+  EXPECT_TRUE(m4.Matches(internal::StringView()));
+  EXPECT_TRUE(m4.Matches(internal::StringView("")));
+#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
+}
+
+TEST(EndsWithTest, CanDescribeSelf) {
+  Matcher<const std::string> m = EndsWith("Hi");
+  EXPECT_EQ("ends with \"Hi\"", Describe(m));
+}
+
+// Tests WhenBase64Unescaped.
+
+TEST(WhenBase64UnescapedTest, MatchesUnescapedBase64Strings) {
+  const Matcher<const char*> m1 = WhenBase64Unescaped(EndsWith("!"));
+  EXPECT_FALSE(m1.Matches("invalid base64"));
+  EXPECT_FALSE(m1.Matches("aGVsbG8gd29ybGQ="));  // hello world
+  EXPECT_TRUE(m1.Matches("aGVsbG8gd29ybGQh"));   // hello world!
+
+  const Matcher<const std::string&> m2 = WhenBase64Unescaped(EndsWith("!"));
+  EXPECT_FALSE(m2.Matches("invalid base64"));
+  EXPECT_FALSE(m2.Matches("aGVsbG8gd29ybGQ="));  // hello world
+  EXPECT_TRUE(m2.Matches("aGVsbG8gd29ybGQh"));   // hello world!
+
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+  const Matcher<const internal::StringView&> m3 =
+      WhenBase64Unescaped(EndsWith("!"));
+  EXPECT_FALSE(m3.Matches("invalid base64"));
+  EXPECT_FALSE(m3.Matches("aGVsbG8gd29ybGQ="));  // hello world
+  EXPECT_TRUE(m3.Matches("aGVsbG8gd29ybGQh"));   // hello world!
+#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
+}
+
+TEST(WhenBase64UnescapedTest, CanDescribeSelf) {
+  const Matcher<const char*> m = WhenBase64Unescaped(EndsWith("!"));
+  EXPECT_EQ("matches after Base64Unescape ends with \"!\"", Describe(m));
+}
+
+// Tests MatchesRegex().
+
+TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
+  const Matcher<const char*> m1 = MatchesRegex("a.*z");
+  EXPECT_TRUE(m1.Matches("az"));
+  EXPECT_TRUE(m1.Matches("abcz"));
+  EXPECT_FALSE(m1.Matches(nullptr));
+
+  const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
+  EXPECT_TRUE(m2.Matches("azbz"));
+  EXPECT_FALSE(m2.Matches("az1"));
+  EXPECT_FALSE(m2.Matches("1az"));
+
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+  const Matcher<const internal::StringView&> m3 = MatchesRegex("a.*z");
+  EXPECT_TRUE(m3.Matches(internal::StringView("az")));
+  EXPECT_TRUE(m3.Matches(internal::StringView("abcz")));
+  EXPECT_FALSE(m3.Matches(internal::StringView("1az")));
+  EXPECT_FALSE(m3.Matches(internal::StringView()));
+  const Matcher<const internal::StringView&> m4 =
+      MatchesRegex(internal::StringView(""));
+  EXPECT_TRUE(m4.Matches(internal::StringView("")));
+  EXPECT_TRUE(m4.Matches(internal::StringView()));
+#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
+}
+
+TEST(MatchesRegexTest, CanDescribeSelf) {
+  Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
+  EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
+
+  Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
+  EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
+
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+  Matcher<const internal::StringView> m3 = MatchesRegex(new RE("0.*"));
+  EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
+#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
+}
+
+// Tests ContainsRegex().
+
+TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
+  const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
+  EXPECT_TRUE(m1.Matches("az"));
+  EXPECT_TRUE(m1.Matches("0abcz1"));
+  EXPECT_FALSE(m1.Matches(nullptr));
+
+  const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
+  EXPECT_TRUE(m2.Matches("azbz"));
+  EXPECT_TRUE(m2.Matches("az1"));
+  EXPECT_FALSE(m2.Matches("1a"));
+
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+  const Matcher<const internal::StringView&> m3 = ContainsRegex(new RE("a.*z"));
+  EXPECT_TRUE(m3.Matches(internal::StringView("azbz")));
+  EXPECT_TRUE(m3.Matches(internal::StringView("az1")));
+  EXPECT_FALSE(m3.Matches(internal::StringView("1a")));
+  EXPECT_FALSE(m3.Matches(internal::StringView()));
+  const Matcher<const internal::StringView&> m4 =
+      ContainsRegex(internal::StringView(""));
+  EXPECT_TRUE(m4.Matches(internal::StringView("")));
+  EXPECT_TRUE(m4.Matches(internal::StringView()));
+#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
+}
+
+TEST(ContainsRegexTest, CanDescribeSelf) {
+  Matcher<const std::string> m1 = ContainsRegex("Hi.*");
+  EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
+
+  Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
+  EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
+
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+  Matcher<const internal::StringView> m3 = ContainsRegex(new RE("0.*"));
+  EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
+#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
+}
+
+// Tests for wide strings.
+#if GTEST_HAS_STD_WSTRING
+TEST(StdWideStrEqTest, MatchesEqual) {
+  Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
+  EXPECT_TRUE(m.Matches(L"Hello"));
+  EXPECT_FALSE(m.Matches(L"hello"));
+  EXPECT_FALSE(m.Matches(nullptr));
+
+  Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
+  EXPECT_TRUE(m2.Matches(L"Hello"));
+  EXPECT_FALSE(m2.Matches(L"Hi"));
+
+  Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
+  EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
+  EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
+
+  ::std::wstring str(L"01204500800");
+  str[3] = L'\0';
+  Matcher<const ::std::wstring&> m4 = StrEq(str);
+  EXPECT_TRUE(m4.Matches(str));
+  str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
+  Matcher<const ::std::wstring&> m5 = StrEq(str);
+  EXPECT_TRUE(m5.Matches(str));
+}
+
+TEST(StdWideStrEqTest, CanDescribeSelf) {
+  Matcher<::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
+  EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
+            Describe(m));
+
+  Matcher<::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
+  EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"", Describe(m2));
+
+  ::std::wstring str(L"01204500800");
+  str[3] = L'\0';
+  Matcher<const ::std::wstring&> m4 = StrEq(str);
+  EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
+  str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
+  Matcher<const ::std::wstring&> m5 = StrEq(str);
+  EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
+}
+
+TEST(StdWideStrNeTest, MatchesUnequalString) {
+  Matcher<const wchar_t*> m = StrNe(L"Hello");
+  EXPECT_TRUE(m.Matches(L""));
+  EXPECT_TRUE(m.Matches(nullptr));
+  EXPECT_FALSE(m.Matches(L"Hello"));
+
+  Matcher<::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
+  EXPECT_TRUE(m2.Matches(L"hello"));
+  EXPECT_FALSE(m2.Matches(L"Hello"));
+}
+
+TEST(StdWideStrNeTest, CanDescribeSelf) {
+  Matcher<const wchar_t*> m = StrNe(L"Hi");
+  EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
+}
+
+TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
+  Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
+  EXPECT_TRUE(m.Matches(L"Hello"));
+  EXPECT_TRUE(m.Matches(L"hello"));
+  EXPECT_FALSE(m.Matches(L"Hi"));
+  EXPECT_FALSE(m.Matches(nullptr));
+
+  Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
+  EXPECT_TRUE(m2.Matches(L"hello"));
+  EXPECT_FALSE(m2.Matches(L"Hi"));
+}
+
+TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
+  ::std::wstring str1(L"oabocdooeoo");
+  ::std::wstring str2(L"OABOCDOOEOO");
+  Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
+  EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
+
+  str1[3] = str2[3] = L'\0';
+  Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
+  EXPECT_TRUE(m1.Matches(str2));
+
+  str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
+  str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
+  Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
+  str1[9] = str2[9] = L'\0';
+  EXPECT_FALSE(m2.Matches(str2));
+
+  Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
+  EXPECT_TRUE(m3.Matches(str2));
+
+  EXPECT_FALSE(m3.Matches(str2 + L"x"));
+  str2.append(1, L'\0');
+  EXPECT_FALSE(m3.Matches(str2));
+  EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
+}
+
+TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
+  Matcher<::std::wstring> m = StrCaseEq(L"Hi");
+  EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
+}
+
+TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
+  Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
+  EXPECT_TRUE(m.Matches(L"Hi"));
+  EXPECT_TRUE(m.Matches(nullptr));
+  EXPECT_FALSE(m.Matches(L"Hello"));
+  EXPECT_FALSE(m.Matches(L"hello"));
+
+  Matcher<::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
+  EXPECT_TRUE(m2.Matches(L""));
+  EXPECT_FALSE(m2.Matches(L"Hello"));
+}
+
+TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
+  Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
+  EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
+}
+
+// Tests that HasSubstr() works for matching wstring-typed values.
+TEST(StdWideHasSubstrTest, WorksForStringClasses) {
+  const Matcher<::std::wstring> m1 = HasSubstr(L"foo");
+  EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
+  EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
+
+  const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
+  EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
+  EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
+}
+
+// Tests that HasSubstr() works for matching C-wide-string-typed values.
+TEST(StdWideHasSubstrTest, WorksForCStrings) {
+  const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
+  EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
+  EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
+  EXPECT_FALSE(m1.Matches(nullptr));
+
+  const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
+  EXPECT_TRUE(m2.Matches(L"I love food."));
+  EXPECT_FALSE(m2.Matches(L"tofo"));
+  EXPECT_FALSE(m2.Matches(nullptr));
+}
+
+// Tests that HasSubstr(s) describes itself properly.
+TEST(StdWideHasSubstrTest, CanDescribeSelf) {
+  Matcher<::std::wstring> m = HasSubstr(L"foo\n\"");
+  EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
+}
+
+// Tests StartsWith(s).
+
+TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
+  const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
+  EXPECT_TRUE(m1.Matches(L"Hi"));
+  EXPECT_TRUE(m1.Matches(L""));
+  EXPECT_FALSE(m1.Matches(nullptr));
+
+  const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
+  EXPECT_TRUE(m2.Matches(L"Hi"));
+  EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
+  EXPECT_TRUE(m2.Matches(L"High"));
+  EXPECT_FALSE(m2.Matches(L"H"));
+  EXPECT_FALSE(m2.Matches(L" Hi"));
+}
+
+TEST(StdWideStartsWithTest, CanDescribeSelf) {
+  Matcher<const ::std::wstring> m = StartsWith(L"Hi");
+  EXPECT_EQ("starts with L\"Hi\"", Describe(m));
+}
+
+// Tests EndsWith(s).
+
+TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
+  const Matcher<const wchar_t*> m1 = EndsWith(L"");
+  EXPECT_TRUE(m1.Matches(L"Hi"));
+  EXPECT_TRUE(m1.Matches(L""));
+  EXPECT_FALSE(m1.Matches(nullptr));
+
+  const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
+  EXPECT_TRUE(m2.Matches(L"Hi"));
+  EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
+  EXPECT_TRUE(m2.Matches(L"Super Hi"));
+  EXPECT_FALSE(m2.Matches(L"i"));
+  EXPECT_FALSE(m2.Matches(L"Hi "));
+}
+
+TEST(StdWideEndsWithTest, CanDescribeSelf) {
+  Matcher<const ::std::wstring> m = EndsWith(L"Hi");
+  EXPECT_EQ("ends with L\"Hi\"", Describe(m));
+}
+
+#endif  // GTEST_HAS_STD_WSTRING
+
+TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
+  StringMatchResultListener listener1;
+  EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
+  EXPECT_EQ("% 2 == 0", listener1.str());
+
+  StringMatchResultListener listener2;
+  EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
+  EXPECT_EQ("", listener2.str());
+}
+
+TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
+  const Matcher<int> is_even = PolymorphicIsEven();
+  StringMatchResultListener listener1;
+  EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
+  EXPECT_EQ("% 2 == 0", listener1.str());
+
+  const Matcher<const double&> is_zero = Eq(0);
+  StringMatchResultListener listener2;
+  EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
+  EXPECT_EQ("", listener2.str());
+}
+
+MATCHER(ConstructNoArg, "") { return true; }
+MATCHER_P(Construct1Arg, arg1, "") { return true; }
+MATCHER_P2(Construct2Args, arg1, arg2, "") { return true; }
+
+TEST(MatcherConstruct, ExplicitVsImplicit) {
+  {
+    // No arg constructor can be constructed with empty brace.
+    ConstructNoArgMatcher m = {};
+    (void)m;
+    // And with no args
+    ConstructNoArgMatcher m2;
+    (void)m2;
+  }
+  {
+    // The one arg constructor has an explicit constructor.
+    // This is to prevent the implicit conversion.
+    using M = Construct1ArgMatcherP<int>;
+    EXPECT_TRUE((std::is_constructible<M, int>::value));
+    EXPECT_FALSE((std::is_convertible<int, M>::value));
+  }
+  {
+    // Multiple arg matchers can be constructed with an implicit construction.
+    Construct2ArgsMatcherP2<int, double> m = {1, 2.2};
+    (void)m;
+  }
+}
+
+MATCHER_P(Really, inner_matcher, "") {
+  return ExplainMatchResult(inner_matcher, arg, result_listener);
+}
+
+TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
+  EXPECT_THAT(0, Really(Eq(0)));
+}
+
+TEST(DescribeMatcherTest, WorksWithValue) {
+  EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42));
+  EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true));
+}
+
+TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) {
+  const Matcher<int> monomorphic = Le(0);
+  EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic));
+  EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true));
+}
+
+TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {
+  EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven()));
+  EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true));
+}
+
+MATCHER_P(FieldIIs, inner_matcher, "") {
+  return ExplainMatchResult(inner_matcher, arg.i, result_listener);
+}
+
+#if GTEST_HAS_RTTI
+TEST(WhenDynamicCastToTest, SameType) {
+  Derived derived;
+  derived.i = 4;
+
+  // Right type. A pointer is passed down.
+  Base* as_base_ptr = &derived;
+  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
+  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
+  EXPECT_THAT(as_base_ptr,
+              Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
+}
+
+TEST(WhenDynamicCastToTest, WrongTypes) {
+  Base base;
+  Derived derived;
+  OtherDerived other_derived;
+
+  // Wrong types. NULL is passed.
+  EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
+  EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
+  Base* as_base_ptr = &derived;
+  EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
+  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
+  as_base_ptr = &other_derived;
+  EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
+  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
+}
+
+TEST(WhenDynamicCastToTest, AlreadyNull) {
+  // Already NULL.
+  Base* as_base_ptr = nullptr;
+  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
+}
+
+struct AmbiguousCastTypes {
+  class VirtualDerived : public virtual Base {};
+  class DerivedSub1 : public VirtualDerived {};
+  class DerivedSub2 : public VirtualDerived {};
+  class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
+};
+
+TEST(WhenDynamicCastToTest, AmbiguousCast) {
+  AmbiguousCastTypes::DerivedSub1 sub1;
+  AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
+  // Multiply derived from Base. dynamic_cast<> returns NULL.
+  Base* as_base_ptr =
+      static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
+  EXPECT_THAT(as_base_ptr,
+              WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
+  as_base_ptr = &sub1;
+  EXPECT_THAT(
+      as_base_ptr,
+      WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
+}
+
+TEST(WhenDynamicCastToTest, Describe) {
+  Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
+  const std::string prefix =
+      "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
+  EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
+  EXPECT_EQ(prefix + "does not point to a value that is anything",
+            DescribeNegation(matcher));
+}
+
+TEST(WhenDynamicCastToTest, Explain) {
+  Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
+  Base* null = nullptr;
+  EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
+  Derived derived;
+  EXPECT_TRUE(matcher.Matches(&derived));
+  EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
+
+  // With references, the matcher itself can fail. Test for that one.
+  Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
+  EXPECT_THAT(Explain(ref_matcher, derived),
+              HasSubstr("which cannot be dynamic_cast"));
+}
+
+TEST(WhenDynamicCastToTest, GoodReference) {
+  Derived derived;
+  derived.i = 4;
+  Base& as_base_ref = derived;
+  EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
+  EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
+}
+
+TEST(WhenDynamicCastToTest, BadReference) {
+  Derived derived;
+  Base& as_base_ref = derived;
+  EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
+}
+#endif  // GTEST_HAS_RTTI
+
+class DivisibleByImpl {
+ public:
+  explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
+
+  // For testing using ExplainMatchResultTo() with polymorphic matchers.
+  template <typename T>
+  bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
+    *listener << "which is " << (n % divider_) << " modulo " << divider_;
+    return (n % divider_) == 0;
+  }
+
+  void DescribeTo(ostream* os) const { *os << "is divisible by " << divider_; }
+
+  void DescribeNegationTo(ostream* os) const {
+    *os << "is not divisible by " << divider_;
+  }
+
+  void set_divider(int a_divider) { divider_ = a_divider; }
+  int divider() const { return divider_; }
+
+ private:
+  int divider_;
+};
+
+PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
+  return MakePolymorphicMatcher(DivisibleByImpl(n));
+}
+
+// Tests that when AllOf() fails, only the first failing matcher is
+// asked to explain why.
+TEST(ExplainMatchResultTest, AllOf_False_False) {
+  const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
+  EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
+}
+
+// Tests that when AllOf() fails, only the first failing matcher is
+// asked to explain why.
+TEST(ExplainMatchResultTest, AllOf_False_True) {
+  const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
+  EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
+}
+
+// Tests that when AllOf() fails, only the first failing matcher is
+// asked to explain why.
+TEST(ExplainMatchResultTest, AllOf_True_False) {
+  const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
+  EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
+}
+
+// Tests that when AllOf() succeeds, all matchers are asked to explain
+// why.
+TEST(ExplainMatchResultTest, AllOf_True_True) {
+  const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
+  EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
+}
+
+TEST(ExplainMatchResultTest, AllOf_True_True_2) {
+  const Matcher<int> m = AllOf(Ge(2), Le(3));
+  EXPECT_EQ("", Explain(m, 2));
+}
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(ExplainmatcherResultTest);
+
+TEST_P(ExplainmatcherResultTestP, MonomorphicMatcher) {
+  const Matcher<int> m = GreaterThan(5);
+  EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
+}
+
+// Tests PolymorphicMatcher::mutable_impl().
+TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
+  PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
+  DivisibleByImpl& impl = m.mutable_impl();
+  EXPECT_EQ(42, impl.divider());
+
+  impl.set_divider(0);
+  EXPECT_EQ(0, m.mutable_impl().divider());
+}
+
+// Tests PolymorphicMatcher::impl().
+TEST(PolymorphicMatcherTest, CanAccessImpl) {
+  const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
+  const DivisibleByImpl& impl = m.impl();
+  EXPECT_EQ(42, impl.divider());
+}
+
+}  // namespace
+}  // namespace gmock_matchers_test
+}  // namespace testing
+
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
diff --git a/googlemock/test/gmock-matchers-containers_test.cc b/googlemock/test/gmock-matchers-containers_test.cc
new file mode 100644 (file)
index 0000000..f50159f
--- /dev/null
@@ -0,0 +1,3129 @@
+// Copyright 2007, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Google Mock - a framework for writing C++ mock classes.
+//
+// This file tests some commonly used argument matchers.
+
+// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
+// possible loss of data and C4100, unreferenced local parameter
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4244)
+#pragma warning(disable : 4100)
+#endif
+
+#include "test/gmock-matchers_test.h"
+
+namespace testing {
+namespace gmock_matchers_test {
+namespace {
+
+std::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) {
+  std::vector<std::unique_ptr<int>> pointers;
+  for (int i : ints) pointers.emplace_back(new int(i));
+  return pointers;
+}
+
+std::string OfType(const std::string& type_name) {
+#if GTEST_HAS_RTTI
+  return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : "";
+#else
+  return "";
+#endif
+}
+
+TEST(ContainsTest, WorksWithMoveOnly) {
+  ContainerHelper helper;
+  EXPECT_CALL(helper, Call(Contains(Pointee(2))));
+  helper.Call(MakeUniquePtrs({1, 2}));
+}
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(ElementsAreTest);
+
+// Tests the variadic version of the ElementsAreMatcher
+TEST(ElementsAreTest, HugeMatcher) {
+  vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
+
+  EXPECT_THAT(test_vector,
+              ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
+                          Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
+}
+
+// Tests the variadic version of the UnorderedElementsAreMatcher
+TEST(ElementsAreTest, HugeMatcherStr) {
+  vector<std::string> test_vector{
+      "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
+
+  EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
+                                                _, _, _, _, _, _));
+}
+
+// Tests the variadic version of the UnorderedElementsAreMatcher
+TEST(ElementsAreTest, HugeMatcherUnordered) {
+  vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
+
+  EXPECT_THAT(test_vector, UnorderedElementsAre(
+                               Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
+                               Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
+}
+
+// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
+// matches the matcher.
+TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
+  ASSERT_THAT(5, Ge(2)) << "This should succeed.";
+  ASSERT_THAT("Foo", EndsWith("oo"));
+  EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
+  EXPECT_THAT("Hello", StartsWith("Hell"));
+}
+
+// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
+// doesn't match the matcher.
+TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
+  // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
+  // which cannot reference auto variables.
+  static unsigned short n;  // NOLINT
+  n = 5;
+
+  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)),
+                       "Value of: n\n"
+                       "Expected: is > 10\n"
+                       "  Actual: 5" +
+                           OfType("unsigned short"));
+  n = 0;
+  EXPECT_NONFATAL_FAILURE(EXPECT_THAT(n, AllOf(Le(7), Ge(5))),
+                          "Value of: n\n"
+                          "Expected: (is <= 7) and (is >= 5)\n"
+                          "  Actual: 0" +
+                              OfType("unsigned short"));
+}
+
+// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
+// has a reference type.
+TEST(MatcherAssertionTest, WorksForByRefArguments) {
+  // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
+  // reference auto variables.
+  static int n;
+  n = 0;
+  EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
+  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
+                       "Value of: n\n"
+                       "Expected: does not reference the variable @");
+  // Tests the "Actual" part.
+  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
+                       "Actual: 0" + OfType("int") + ", which is located @");
+}
+
+// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
+// monomorphic.
+TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
+  Matcher<const char*> starts_with_he = StartsWith("he");
+  ASSERT_THAT("hello", starts_with_he);
+
+  Matcher<const std::string&> ends_with_ok = EndsWith("ok");
+  ASSERT_THAT("book", ends_with_ok);
+  const std::string bad = "bad";
+  EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
+                          "Value of: bad\n"
+                          "Expected: ends with \"ok\"\n"
+                          "  Actual: \"bad\"");
+  Matcher<int> is_greater_than_5 = Gt(5);
+  EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
+                          "Value of: 5\n"
+                          "Expected: is > 5\n"
+                          "  Actual: 5" +
+                              OfType("int"));
+}
+
+TEST(PointeeTest, RawPointer) {
+  const Matcher<int*> m = Pointee(Ge(0));
+
+  int n = 1;
+  EXPECT_TRUE(m.Matches(&n));
+  n = -1;
+  EXPECT_FALSE(m.Matches(&n));
+  EXPECT_FALSE(m.Matches(nullptr));
+}
+
+TEST(PointeeTest, RawPointerToConst) {
+  const Matcher<const double*> m = Pointee(Ge(0));
+
+  double x = 1;
+  EXPECT_TRUE(m.Matches(&x));
+  x = -1;
+  EXPECT_FALSE(m.Matches(&x));
+  EXPECT_FALSE(m.Matches(nullptr));
+}
+
+TEST(PointeeTest, ReferenceToConstRawPointer) {
+  const Matcher<int* const&> m = Pointee(Ge(0));
+
+  int n = 1;
+  EXPECT_TRUE(m.Matches(&n));
+  n = -1;
+  EXPECT_FALSE(m.Matches(&n));
+  EXPECT_FALSE(m.Matches(nullptr));
+}
+
+TEST(PointeeTest, ReferenceToNonConstRawPointer) {
+  const Matcher<double*&> m = Pointee(Ge(0));
+
+  double x = 1.0;
+  double* p = &x;
+  EXPECT_TRUE(m.Matches(p));
+  x = -1;
+  EXPECT_FALSE(m.Matches(p));
+  p = nullptr;
+  EXPECT_FALSE(m.Matches(p));
+}
+
+TEST(PointeeTest, SmartPointer) {
+  const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));
+
+  std::unique_ptr<int> n(new int(1));
+  EXPECT_TRUE(m.Matches(n));
+}
+
+TEST(PointeeTest, SmartPointerToConst) {
+  const Matcher<std::unique_ptr<const int>> m = Pointee(Ge(0));
+
+  // There's no implicit conversion from unique_ptr<int> to const
+  // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
+  // matcher.
+  std::unique_ptr<const int> n(new int(1));
+  EXPECT_TRUE(m.Matches(n));
+}
+
+TEST(PointerTest, RawPointer) {
+  int n = 1;
+  const Matcher<int*> m = Pointer(Eq(&n));
+
+  EXPECT_TRUE(m.Matches(&n));
+
+  int* p = nullptr;
+  EXPECT_FALSE(m.Matches(p));
+  EXPECT_FALSE(m.Matches(nullptr));
+}
+
+TEST(PointerTest, RawPointerToConst) {
+  int n = 1;
+  const Matcher<const int*> m = Pointer(Eq(&n));
+
+  EXPECT_TRUE(m.Matches(&n));
+
+  int* p = nullptr;
+  EXPECT_FALSE(m.Matches(p));
+  EXPECT_FALSE(m.Matches(nullptr));
+}
+
+TEST(PointerTest, SmartPointer) {
+  std::unique_ptr<int> n(new int(10));
+  int* raw_n = n.get();
+  const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n));
+
+  EXPECT_TRUE(m.Matches(n));
+}
+
+TEST(PointerTest, SmartPointerToConst) {
+  std::unique_ptr<const int> n(new int(10));
+  const int* raw_n = n.get();
+  const Matcher<std::unique_ptr<const int>> m = Pointer(Eq(raw_n));
+
+  // There's no implicit conversion from unique_ptr<int> to const
+  // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
+  // matcher.
+  std::unique_ptr<const int> p(new int(10));
+  EXPECT_FALSE(m.Matches(p));
+}
+
+// Minimal const-propagating pointer.
+template <typename T>
+class ConstPropagatingPtr {
+ public:
+  typedef T element_type;
+
+  ConstPropagatingPtr() : val_() {}
+  explicit ConstPropagatingPtr(T* t) : val_(t) {}
+  ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
+
+  T* get() { return val_; }
+  T& operator*() { return *val_; }
+  // Most smart pointers return non-const T* and T& from the next methods.
+  const T* get() const { return val_; }
+  const T& operator*() const { return *val_; }
+
+ private:
+  T* val_;
+};
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(PointeeTest);
+
+TEST(PointeeTest, WorksWithConstPropagatingPointers) {
+  const Matcher<ConstPropagatingPtr<int>> m = Pointee(Lt(5));
+  int three = 3;
+  const ConstPropagatingPtr<int> co(&three);
+  ConstPropagatingPtr<int> o(&three);
+  EXPECT_TRUE(m.Matches(o));
+  EXPECT_TRUE(m.Matches(co));
+  *o = 6;
+  EXPECT_FALSE(m.Matches(o));
+  EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
+}
+
+TEST(PointeeTest, NeverMatchesNull) {
+  const Matcher<const char*> m = Pointee(_);
+  EXPECT_FALSE(m.Matches(nullptr));
+}
+
+// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
+TEST(PointeeTest, MatchesAgainstAValue) {
+  const Matcher<int*> m = Pointee(5);
+
+  int n = 5;
+  EXPECT_TRUE(m.Matches(&n));
+  n = -1;
+  EXPECT_FALSE(m.Matches(&n));
+  EXPECT_FALSE(m.Matches(nullptr));
+}
+
+TEST(PointeeTest, CanDescribeSelf) {
+  const Matcher<int*> m = Pointee(Gt(3));
+  EXPECT_EQ("points to a value that is > 3", Describe(m));
+  EXPECT_EQ("does not point to a value that is > 3", DescribeNegation(m));
+}
+
+TEST_P(PointeeTestP, CanExplainMatchResult) {
+  const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
+
+  EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr)));
+
+  const Matcher<long*> m2 = Pointee(GreaterThan(1));  // NOLINT
+  long n = 3;                                         // NOLINT
+  EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
+            Explain(m2, &n));
+}
+
+TEST(PointeeTest, AlwaysExplainsPointee) {
+  const Matcher<int*> m = Pointee(0);
+  int n = 42;
+  EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
+}
+
+// An uncopyable class.
+class Uncopyable {
+ public:
+  Uncopyable() : value_(-1) {}
+  explicit Uncopyable(int a_value) : value_(a_value) {}
+
+  int value() const { return value_; }
+  void set_value(int i) { value_ = i; }
+
+ private:
+  int value_;
+  Uncopyable(const Uncopyable&) = delete;
+  Uncopyable& operator=(const Uncopyable&) = delete;
+};
+
+// Returns true if and only if x.value() is positive.
+bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
+
+MATCHER_P(UncopyableIs, inner_matcher, "") {
+  return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
+}
+
+// A user-defined struct for testing Field().
+struct AStruct {
+  AStruct() : x(0), y(1.0), z(5), p(nullptr) {}
+  AStruct(const AStruct& rhs)
+      : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
+
+  int x;           // A non-const field.
+  const double y;  // A const field.
+  Uncopyable z;    // An uncopyable field.
+  const char* p;   // A pointer field.
+};
+
+// A derived struct for testing Field().
+struct DerivedStruct : public AStruct {
+  char ch;
+};
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(FieldTest);
+
+// Tests that Field(&Foo::field, ...) works when field is non-const.
+TEST(FieldTest, WorksForNonConstField) {
+  Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
+  Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
+
+  AStruct a;
+  EXPECT_TRUE(m.Matches(a));
+  EXPECT_TRUE(m_with_name.Matches(a));
+  a.x = -1;
+  EXPECT_FALSE(m.Matches(a));
+  EXPECT_FALSE(m_with_name.Matches(a));
+}
+
+// Tests that Field(&Foo::field, ...) works when field is const.
+TEST(FieldTest, WorksForConstField) {
+  AStruct a;
+
+  Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
+  Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0));
+  EXPECT_TRUE(m.Matches(a));
+  EXPECT_TRUE(m_with_name.Matches(a));
+  m = Field(&AStruct::y, Le(0.0));
+  m_with_name = Field("y", &AStruct::y, Le(0.0));
+  EXPECT_FALSE(m.Matches(a));
+  EXPECT_FALSE(m_with_name.Matches(a));
+}
+
+// Tests that Field(&Foo::field, ...) works when field is not copyable.
+TEST(FieldTest, WorksForUncopyableField) {
+  AStruct a;
+
+  Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
+  EXPECT_TRUE(m.Matches(a));
+  m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
+  EXPECT_FALSE(m.Matches(a));
+}
+
+// Tests that Field(&Foo::field, ...) works when field is a pointer.
+TEST(FieldTest, WorksForPointerField) {
+  // Matching against NULL.
+  Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));
+  AStruct a;
+  EXPECT_TRUE(m.Matches(a));
+  a.p = "hi";
+  EXPECT_FALSE(m.Matches(a));
+
+  // Matching a pointer that is not NULL.
+  m = Field(&AStruct::p, StartsWith("hi"));
+  a.p = "hill";
+  EXPECT_TRUE(m.Matches(a));
+  a.p = "hole";
+  EXPECT_FALSE(m.Matches(a));
+}
+
+// Tests that Field() works when the object is passed by reference.
+TEST(FieldTest, WorksForByRefArgument) {
+  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
+
+  AStruct a;
+  EXPECT_TRUE(m.Matches(a));
+  a.x = -1;
+  EXPECT_FALSE(m.Matches(a));
+}
+
+// Tests that Field(&Foo::field, ...) works when the argument's type
+// is a sub-type of Foo.
+TEST(FieldTest, WorksForArgumentOfSubType) {
+  // Note that the matcher expects DerivedStruct but we say AStruct
+  // inside Field().
+  Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
+
+  DerivedStruct d;
+  EXPECT_TRUE(m.Matches(d));
+  d.x = -1;
+  EXPECT_FALSE(m.Matches(d));
+}
+
+// Tests that Field(&Foo::field, m) works when field's type and m's
+// argument type are compatible but not the same.
+TEST(FieldTest, WorksForCompatibleMatcherType) {
+  // The field is an int, but the inner matcher expects a signed char.
+  Matcher<const AStruct&> m = Field(&AStruct::x, Matcher<signed char>(Ge(0)));
+
+  AStruct a;
+  EXPECT_TRUE(m.Matches(a));
+  a.x = -1;
+  EXPECT_FALSE(m.Matches(a));
+}
+
+// Tests that Field() can describe itself.
+TEST(FieldTest, CanDescribeSelf) {
+  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
+
+  EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
+  EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
+}
+
+TEST(FieldTest, CanDescribeSelfWithFieldName) {
+  Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
+
+  EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
+  EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
+            DescribeNegation(m));
+}
+
+// Tests that Field() can explain the match result.
+TEST_P(FieldTestP, CanExplainMatchResult) {
+  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
+
+  AStruct a;
+  a.x = 1;
+  EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
+
+  m = Field(&AStruct::x, GreaterThan(0));
+  EXPECT_EQ(
+      "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
+      Explain(m, a));
+}
+
+TEST_P(FieldTestP, CanExplainMatchResultWithFieldName) {
+  Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
+
+  AStruct a;
+  a.x = 1;
+  EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
+
+  m = Field("field_name", &AStruct::x, GreaterThan(0));
+  EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +
+                ", which is 1 more than 0",
+            Explain(m, a));
+}
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(FieldForPointerTest);
+
+// Tests that Field() works when the argument is a pointer to const.
+TEST(FieldForPointerTest, WorksForPointerToConst) {
+  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
+
+  AStruct a;
+  EXPECT_TRUE(m.Matches(&a));
+  a.x = -1;
+  EXPECT_FALSE(m.Matches(&a));
+}
+
+// Tests that Field() works when the argument is a pointer to non-const.
+TEST(FieldForPointerTest, WorksForPointerToNonConst) {
+  Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
+
+  AStruct a;
+  EXPECT_TRUE(m.Matches(&a));
+  a.x = -1;
+  EXPECT_FALSE(m.Matches(&a));
+}
+
+// Tests that Field() works when the argument is a reference to a const pointer.
+TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
+  Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
+
+  AStruct a;
+  EXPECT_TRUE(m.Matches(&a));
+  a.x = -1;
+  EXPECT_FALSE(m.Matches(&a));
+}
+
+// Tests that Field() does not match the NULL pointer.
+TEST(FieldForPointerTest, DoesNotMatchNull) {
+  Matcher<const AStruct*> m = Field(&AStruct::x, _);
+  EXPECT_FALSE(m.Matches(nullptr));
+}
+
+// Tests that Field(&Foo::field, ...) works when the argument's type
+// is a sub-type of const Foo*.
+TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
+  // Note that the matcher expects DerivedStruct but we say AStruct
+  // inside Field().
+  Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
+
+  DerivedStruct d;
+  EXPECT_TRUE(m.Matches(&d));
+  d.x = -1;
+  EXPECT_FALSE(m.Matches(&d));
+}
+
+// Tests that Field() can describe itself when used to match a pointer.
+TEST(FieldForPointerTest, CanDescribeSelf) {
+  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
+
+  EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
+  EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
+}
+
+TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
+  Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
+
+  EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
+  EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
+            DescribeNegation(m));
+}
+
+// Tests that Field() can explain the result of matching a pointer.
+TEST_P(FieldForPointerTestP, CanExplainMatchResult) {
+  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
+
+  AStruct a;
+  a.x = 1;
+  EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
+  EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
+            Explain(m, &a));
+
+  m = Field(&AStruct::x, GreaterThan(0));
+  EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
+                ", which is 1 more than 0",
+            Explain(m, &a));
+}
+
+TEST_P(FieldForPointerTestP, CanExplainMatchResultWithFieldName) {
+  Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
+
+  AStruct a;
+  a.x = 1;
+  EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
+  EXPECT_EQ(
+      "which points to an object whose field `field_name` is 1" + OfType("int"),
+      Explain(m, &a));
+
+  m = Field("field_name", &AStruct::x, GreaterThan(0));
+  EXPECT_EQ("which points to an object whose field `field_name` is 1" +
+                OfType("int") + ", which is 1 more than 0",
+            Explain(m, &a));
+}
+
+// A user-defined class for testing Property().
+class AClass {
+ public:
+  AClass() : n_(0) {}
+
+  // A getter that returns a non-reference.
+  int n() const { return n_; }
+
+  void set_n(int new_n) { n_ = new_n; }
+
+  // A getter that returns a reference to const.
+  const std::string& s() const { return s_; }
+
+  const std::string& s_ref() const& { return s_; }
+
+  void set_s(const std::string& new_s) { s_ = new_s; }
+
+  // A getter that returns a reference to non-const.
+  double& x() const { return x_; }
+
+ private:
+  int n_;
+  std::string s_;
+
+  static double x_;
+};
+
+double AClass::x_ = 0.0;
+
+// A derived class for testing Property().
+class DerivedClass : public AClass {
+ public:
+  int k() const { return k_; }
+
+ private:
+  int k_;
+};
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(PropertyTest);
+
+// Tests that Property(&Foo::property, ...) works when property()
+// returns a non-reference.
+TEST(PropertyTest, WorksForNonReferenceProperty) {
+  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
+  Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
+
+  AClass a;
+  a.set_n(1);
+  EXPECT_TRUE(m.Matches(a));
+  EXPECT_TRUE(m_with_name.Matches(a));
+
+  a.set_n(-1);
+  EXPECT_FALSE(m.Matches(a));
+  EXPECT_FALSE(m_with_name.Matches(a));
+}
+
+// Tests that Property(&Foo::property, ...) works when property()
+// returns a reference to const.
+TEST(PropertyTest, WorksForReferenceToConstProperty) {
+  Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
+  Matcher<const AClass&> m_with_name =
+      Property("s", &AClass::s, StartsWith("hi"));
+
+  AClass a;
+  a.set_s("hill");
+  EXPECT_TRUE(m.Matches(a));
+  EXPECT_TRUE(m_with_name.Matches(a));
+
+  a.set_s("hole");
+  EXPECT_FALSE(m.Matches(a));
+  EXPECT_FALSE(m_with_name.Matches(a));
+}
+
+// Tests that Property(&Foo::property, ...) works when property() is
+// ref-qualified.
+TEST(PropertyTest, WorksForRefQualifiedProperty) {
+  Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
+  Matcher<const AClass&> m_with_name =
+      Property("s", &AClass::s_ref, StartsWith("hi"));
+
+  AClass a;
+  a.set_s("hill");
+  EXPECT_TRUE(m.Matches(a));
+  EXPECT_TRUE(m_with_name.Matches(a));
+
+  a.set_s("hole");
+  EXPECT_FALSE(m.Matches(a));
+  EXPECT_FALSE(m_with_name.Matches(a));
+}
+
+// Tests that Property(&Foo::property, ...) works when property()
+// returns a reference to non-const.
+TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
+  double x = 0.0;
+  AClass a;
+
+  Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
+  EXPECT_FALSE(m.Matches(a));
+
+  m = Property(&AClass::x, Not(Ref(x)));
+  EXPECT_TRUE(m.Matches(a));
+}
+
+// Tests that Property(&Foo::property, ...) works when the argument is
+// passed by value.
+TEST(PropertyTest, WorksForByValueArgument) {
+  Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
+
+  AClass a;
+  a.set_s("hill");
+  EXPECT_TRUE(m.Matches(a));
+
+  a.set_s("hole");
+  EXPECT_FALSE(m.Matches(a));
+}
+
+// Tests that Property(&Foo::property, ...) works when the argument's
+// type is a sub-type of Foo.
+TEST(PropertyTest, WorksForArgumentOfSubType) {
+  // The matcher expects a DerivedClass, but inside the Property() we
+  // say AClass.
+  Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
+
+  DerivedClass d;
+  d.set_n(1);
+  EXPECT_TRUE(m.Matches(d));
+
+  d.set_n(-1);
+  EXPECT_FALSE(m.Matches(d));
+}
+
+// Tests that Property(&Foo::property, m) works when property()'s type
+// and m's argument type are compatible but different.
+TEST(PropertyTest, WorksForCompatibleMatcherType) {
+  // n() returns an int but the inner matcher expects a signed char.
+  Matcher<const AClass&> m = Property(&AClass::n, Matcher<signed char>(Ge(0)));
+
+  Matcher<const AClass&> m_with_name =
+      Property("n", &AClass::n, Matcher<signed char>(Ge(0)));
+
+  AClass a;
+  EXPECT_TRUE(m.Matches(a));
+  EXPECT_TRUE(m_with_name.Matches(a));
+  a.set_n(-1);
+  EXPECT_FALSE(m.Matches(a));
+  EXPECT_FALSE(m_with_name.Matches(a));
+}
+
+// Tests that Property() can describe itself.
+TEST(PropertyTest, CanDescribeSelf) {
+  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
+
+  EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
+  EXPECT_EQ("is an object whose given property isn't >= 0",
+            DescribeNegation(m));
+}
+
+TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
+  Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
+
+  EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
+  EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
+            DescribeNegation(m));
+}
+
+// Tests that Property() can explain the match result.
+TEST_P(PropertyTestP, CanExplainMatchResult) {
+  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
+
+  AClass a;
+  a.set_n(1);
+  EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
+
+  m = Property(&AClass::n, GreaterThan(0));
+  EXPECT_EQ(
+      "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
+      Explain(m, a));
+}
+
+TEST_P(PropertyTestP, CanExplainMatchResultWithPropertyName) {
+  Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
+
+  AClass a;
+  a.set_n(1);
+  EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
+
+  m = Property("fancy_name", &AClass::n, GreaterThan(0));
+  EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +
+                ", which is 1 more than 0",
+            Explain(m, a));
+}
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(PropertyForPointerTest);
+
+// Tests that Property() works when the argument is a pointer to const.
+TEST(PropertyForPointerTest, WorksForPointerToConst) {
+  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
+
+  AClass a;
+  a.set_n(1);
+  EXPECT_TRUE(m.Matches(&a));
+
+  a.set_n(-1);
+  EXPECT_FALSE(m.Matches(&a));
+}
+
+// Tests that Property() works when the argument is a pointer to non-const.
+TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
+  Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
+
+  AClass a;
+  a.set_s("hill");
+  EXPECT_TRUE(m.Matches(&a));
+
+  a.set_s("hole");
+  EXPECT_FALSE(m.Matches(&a));
+}
+
+// Tests that Property() works when the argument is a reference to a
+// const pointer.
+TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
+  Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
+
+  AClass a;
+  a.set_s("hill");
+  EXPECT_TRUE(m.Matches(&a));
+
+  a.set_s("hole");
+  EXPECT_FALSE(m.Matches(&a));
+}
+
+// Tests that Property() does not match the NULL pointer.
+TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
+  Matcher<const AClass*> m = Property(&AClass::x, _);
+  EXPECT_FALSE(m.Matches(nullptr));
+}
+
+// Tests that Property(&Foo::property, ...) works when the argument's
+// type is a sub-type of const Foo*.
+TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
+  // The matcher expects a DerivedClass, but inside the Property() we
+  // say AClass.
+  Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
+
+  DerivedClass d;
+  d.set_n(1);
+  EXPECT_TRUE(m.Matches(&d));
+
+  d.set_n(-1);
+  EXPECT_FALSE(m.Matches(&d));
+}
+
+// Tests that Property() can describe itself when used to match a pointer.
+TEST(PropertyForPointerTest, CanDescribeSelf) {
+  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
+
+  EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
+  EXPECT_EQ("is an object whose given property isn't >= 0",
+            DescribeNegation(m));
+}
+
+TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
+  Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
+
+  EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
+  EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
+            DescribeNegation(m));
+}
+
+// Tests that Property() can explain the result of matching a pointer.
+TEST_P(PropertyForPointerTestP, CanExplainMatchResult) {
+  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
+
+  AClass a;
+  a.set_n(1);
+  EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
+  EXPECT_EQ(
+      "which points to an object whose given property is 1" + OfType("int"),
+      Explain(m, &a));
+
+  m = Property(&AClass::n, GreaterThan(0));
+  EXPECT_EQ("which points to an object whose given property is 1" +
+                OfType("int") + ", which is 1 more than 0",
+            Explain(m, &a));
+}
+
+TEST_P(PropertyForPointerTestP, CanExplainMatchResultWithPropertyName) {
+  Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
+
+  AClass a;
+  a.set_n(1);
+  EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
+  EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
+                OfType("int"),
+            Explain(m, &a));
+
+  m = Property("fancy_name", &AClass::n, GreaterThan(0));
+  EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
+                OfType("int") + ", which is 1 more than 0",
+            Explain(m, &a));
+}
+
+// Tests ResultOf.
+
+// Tests that ResultOf(f, ...) compiles and works as expected when f is a
+// function pointer.
+std::string IntToStringFunction(int input) {
+  return input == 1 ? "foo" : "bar";
+}
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(ResultOfTest);
+
+TEST(ResultOfTest, WorksForFunctionPointers) {
+  Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
+
+  EXPECT_TRUE(matcher.Matches(1));
+  EXPECT_FALSE(matcher.Matches(2));
+}
+
+// Tests that ResultOf() can describe itself.
+TEST(ResultOfTest, CanDescribeItself) {
+  Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
+
+  EXPECT_EQ(
+      "is mapped by the given callable to a value that "
+      "is equal to \"foo\"",
+      Describe(matcher));
+  EXPECT_EQ(
+      "is mapped by the given callable to a value that "
+      "isn't equal to \"foo\"",
+      DescribeNegation(matcher));
+}
+
+// Tests that ResultOf() can describe itself when provided a result description.
+TEST(ResultOfTest, CanDescribeItselfWithResultDescription) {
+  Matcher<int> matcher =
+      ResultOf("string conversion", &IntToStringFunction, StrEq("foo"));
+
+  EXPECT_EQ("whose string conversion is equal to \"foo\"", Describe(matcher));
+  EXPECT_EQ("whose string conversion isn't equal to \"foo\"",
+            DescribeNegation(matcher));
+}
+
+// Tests that ResultOf() can explain the match result.
+int IntFunction(int input) { return input == 42 ? 80 : 90; }
+
+TEST_P(ResultOfTestP, CanExplainMatchResult) {
+  Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
+  EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
+            Explain(matcher, 36));
+
+  matcher = ResultOf(&IntFunction, GreaterThan(85));
+  EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
+                ", which is 5 more than 85",
+            Explain(matcher, 36));
+}
+
+TEST_P(ResultOfTestP, CanExplainMatchResultWithResultDescription) {
+  Matcher<int> matcher = ResultOf("magic int conversion", &IntFunction, Ge(85));
+  EXPECT_EQ("whose magic int conversion is 90" + OfType("int"),
+            Explain(matcher, 36));
+
+  matcher = ResultOf("magic int conversion", &IntFunction, GreaterThan(85));
+  EXPECT_EQ("whose magic int conversion is 90" + OfType("int") +
+                ", which is 5 more than 85",
+            Explain(matcher, 36));
+}
+
+// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
+// returns a non-reference.
+TEST(ResultOfTest, WorksForNonReferenceResults) {
+  Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
+
+  EXPECT_TRUE(matcher.Matches(42));
+  EXPECT_FALSE(matcher.Matches(36));
+}
+
+// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
+// returns a reference to non-const.
+double& DoubleFunction(double& input) { return input; }  // NOLINT
+
+Uncopyable& RefUncopyableFunction(Uncopyable& obj) {  // NOLINT
+  return obj;
+}
+
+TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
+  double x = 3.14;
+  double x2 = x;
+  Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
+
+  EXPECT_TRUE(matcher.Matches(x));
+  EXPECT_FALSE(matcher.Matches(x2));
+
+  // Test that ResultOf works with uncopyable objects
+  Uncopyable obj(0);
+  Uncopyable obj2(0);
+  Matcher<Uncopyable&> matcher2 = ResultOf(&RefUncopyableFunction, Ref(obj));
+
+  EXPECT_TRUE(matcher2.Matches(obj));
+  EXPECT_FALSE(matcher2.Matches(obj2));
+}
+
+// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
+// returns a reference to const.
+const std::string& StringFunction(const std::string& input) { return input; }
+
+TEST(ResultOfTest, WorksForReferenceToConstResults) {
+  std::string s = "foo";
+  std::string s2 = s;
+  Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
+
+  EXPECT_TRUE(matcher.Matches(s));
+  EXPECT_FALSE(matcher.Matches(s2));
+}
+
+// Tests that ResultOf(f, m) works when f(x) and m's
+// argument types are compatible but different.
+TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
+  // IntFunction() returns int but the inner matcher expects a signed char.
+  Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
+
+  EXPECT_TRUE(matcher.Matches(36));
+  EXPECT_FALSE(matcher.Matches(42));
+}
+
+// Tests that the program aborts when ResultOf is passed
+// a NULL function pointer.
+TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
+  EXPECT_DEATH_IF_SUPPORTED(
+      ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
+               Eq(std::string("foo"))),
+      "NULL function pointer is passed into ResultOf\\(\\)\\.");
+}
+
+// Tests that ResultOf(f, ...) compiles and works as expected when f is a
+// function reference.
+TEST(ResultOfTest, WorksForFunctionReferences) {
+  Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
+  EXPECT_TRUE(matcher.Matches(1));
+  EXPECT_FALSE(matcher.Matches(2));
+}
+
+// Tests that ResultOf(f, ...) compiles and works as expected when f is a
+// function object.
+struct Functor {
+  std::string operator()(int input) const { return IntToStringFunction(input); }
+};
+
+TEST(ResultOfTest, WorksForFunctors) {
+  Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
+
+  EXPECT_TRUE(matcher.Matches(1));
+  EXPECT_FALSE(matcher.Matches(2));
+}
+
+// Tests that ResultOf(f, ...) compiles and works as expected when f is a
+// functor with more than one operator() defined. ResultOf() must work
+// for each defined operator().
+struct PolymorphicFunctor {
+  typedef int result_type;
+  int operator()(int n) { return n; }
+  int operator()(const char* s) { return static_cast<int>(strlen(s)); }
+  std::string operator()(int* p) { return p ? "good ptr" : "null"; }
+};
+
+TEST(ResultOfTest, WorksForPolymorphicFunctors) {
+  Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
+
+  EXPECT_TRUE(matcher_int.Matches(10));
+  EXPECT_FALSE(matcher_int.Matches(2));
+
+  Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
+
+  EXPECT_TRUE(matcher_string.Matches("long string"));
+  EXPECT_FALSE(matcher_string.Matches("shrt"));
+}
+
+TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
+  Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");
+
+  int n = 0;
+  EXPECT_TRUE(matcher.Matches(&n));
+  EXPECT_FALSE(matcher.Matches(nullptr));
+}
+
+TEST(ResultOfTest, WorksForLambdas) {
+  Matcher<int> matcher = ResultOf(
+      [](int str_len) {
+        return std::string(static_cast<size_t>(str_len), 'x');
+      },
+      "xxx");
+  EXPECT_TRUE(matcher.Matches(3));
+  EXPECT_FALSE(matcher.Matches(1));
+}
+
+TEST(ResultOfTest, WorksForNonCopyableArguments) {
+  Matcher<std::unique_ptr<int>> matcher = ResultOf(
+      [](const std::unique_ptr<int>& str_len) {
+        return std::string(static_cast<size_t>(*str_len), 'x');
+      },
+      "xxx");
+  EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3))));
+  EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1))));
+}
+
+const int* ReferencingFunction(const int& n) { return &n; }
+
+struct ReferencingFunctor {
+  typedef const int* result_type;
+  result_type operator()(const int& n) { return &n; }
+};
+
+TEST(ResultOfTest, WorksForReferencingCallables) {
+  const int n = 1;
+  const int n2 = 1;
+  Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
+  EXPECT_TRUE(matcher2.Matches(n));
+  EXPECT_FALSE(matcher2.Matches(n2));
+
+  Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
+  EXPECT_TRUE(matcher3.Matches(n));
+  EXPECT_FALSE(matcher3.Matches(n2));
+}
+
+TEST(SizeIsTest, ImplementsSizeIs) {
+  vector<int> container;
+  EXPECT_THAT(container, SizeIs(0));
+  EXPECT_THAT(container, Not(SizeIs(1)));
+  container.push_back(0);
+  EXPECT_THAT(container, Not(SizeIs(0)));
+  EXPECT_THAT(container, SizeIs(1));
+  container.push_back(0);
+  EXPECT_THAT(container, Not(SizeIs(0)));
+  EXPECT_THAT(container, SizeIs(2));
+}
+
+TEST(SizeIsTest, WorksWithMap) {
+  map<std::string, int> container;
+  EXPECT_THAT(container, SizeIs(0));
+  EXPECT_THAT(container, Not(SizeIs(1)));
+  container.insert(make_pair("foo", 1));
+  EXPECT_THAT(container, Not(SizeIs(0)));
+  EXPECT_THAT(container, SizeIs(1));
+  container.insert(make_pair("bar", 2));
+  EXPECT_THAT(container, Not(SizeIs(0)));
+  EXPECT_THAT(container, SizeIs(2));
+}
+
+TEST(SizeIsTest, WorksWithReferences) {
+  vector<int> container;
+  Matcher<const vector<int>&> m = SizeIs(1);
+  EXPECT_THAT(container, Not(m));
+  container.push_back(0);
+  EXPECT_THAT(container, m);
+}
+
+TEST(SizeIsTest, WorksWithMoveOnly) {
+  ContainerHelper helper;
+  EXPECT_CALL(helper, Call(SizeIs(3)));
+  helper.Call(MakeUniquePtrs({1, 2, 3}));
+}
+
+// SizeIs should work for any type that provides a size() member function.
+// For example, a size_type member type should not need to be provided.
+struct MinimalistCustomType {
+  int size() const { return 1; }
+};
+TEST(SizeIsTest, WorksWithMinimalistCustomType) {
+  MinimalistCustomType container;
+  EXPECT_THAT(container, SizeIs(1));
+  EXPECT_THAT(container, Not(SizeIs(0)));
+}
+
+TEST(SizeIsTest, CanDescribeSelf) {
+  Matcher<vector<int>> m = SizeIs(2);
+  EXPECT_EQ("size is equal to 2", Describe(m));
+  EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
+}
+
+TEST(SizeIsTest, ExplainsResult) {
+  Matcher<vector<int>> m1 = SizeIs(2);
+  Matcher<vector<int>> m2 = SizeIs(Lt(2u));
+  Matcher<vector<int>> m3 = SizeIs(AnyOf(0, 3));
+  Matcher<vector<int>> m4 = SizeIs(Gt(1u));
+  vector<int> container;
+  EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
+  EXPECT_EQ("whose size 0 matches", Explain(m2, container));
+  EXPECT_EQ("whose size 0 matches", Explain(m3, container));
+  EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
+  container.push_back(0);
+  container.push_back(0);
+  EXPECT_EQ("whose size 2 matches", Explain(m1, container));
+  EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
+  EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
+  EXPECT_EQ("whose size 2 matches", Explain(m4, container));
+}
+
+TEST(WhenSortedByTest, WorksForEmptyContainer) {
+  const vector<int> numbers;
+  EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
+  EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
+}
+
+TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
+  vector<unsigned> numbers;
+  numbers.push_back(3);
+  numbers.push_back(1);
+  numbers.push_back(2);
+  numbers.push_back(2);
+  EXPECT_THAT(numbers,
+              WhenSortedBy(greater<unsigned>(), ElementsAre(3, 2, 2, 1)));
+  EXPECT_THAT(numbers,
+              Not(WhenSortedBy(greater<unsigned>(), ElementsAre(1, 2, 2, 3))));
+}
+
+TEST(WhenSortedByTest, WorksForNonVectorContainer) {
+  list<std::string> words;
+  words.push_back("say");
+  words.push_back("hello");
+  words.push_back("world");
+  EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
+                                  ElementsAre("hello", "say", "world")));
+  EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
+                                      ElementsAre("say", "hello", "world"))));
+}
+
+TEST(WhenSortedByTest, WorksForNativeArray) {
+  const int numbers[] = {1, 3, 2, 4};
+  const int sorted_numbers[] = {1, 2, 3, 4};
+  EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
+  EXPECT_THAT(numbers,
+              WhenSortedBy(less<int>(), ElementsAreArray(sorted_numbers)));
+  EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
+}
+
+TEST(WhenSortedByTest, CanDescribeSelf) {
+  const Matcher<vector<int>> m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
+  EXPECT_EQ(
+      "(when sorted) has 2 elements where\n"
+      "element #0 is equal to 1,\n"
+      "element #1 is equal to 2",
+      Describe(m));
+  EXPECT_EQ(
+      "(when sorted) doesn't have 2 elements, or\n"
+      "element #0 isn't equal to 1, or\n"
+      "element #1 isn't equal to 2",
+      DescribeNegation(m));
+}
+
+TEST(WhenSortedByTest, ExplainsMatchResult) {
+  const int a[] = {2, 1};
+  EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
+            Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
+  EXPECT_EQ("which is { 1, 2 } when sorted",
+            Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
+}
+
+// WhenSorted() is a simple wrapper on WhenSortedBy().  Hence we don't
+// need to test it as exhaustively as we test the latter.
+
+TEST(WhenSortedTest, WorksForEmptyContainer) {
+  const vector<int> numbers;
+  EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
+  EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
+}
+
+TEST(WhenSortedTest, WorksForNonEmptyContainer) {
+  list<std::string> words;
+  words.push_back("3");
+  words.push_back("1");
+  words.push_back("2");
+  words.push_back("2");
+  EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
+  EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
+}
+
+TEST(WhenSortedTest, WorksForMapTypes) {
+  map<std::string, int> word_counts;
+  word_counts["and"] = 1;
+  word_counts["the"] = 1;
+  word_counts["buffalo"] = 2;
+  EXPECT_THAT(word_counts,
+              WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
+                                     Pair("the", 1))));
+  EXPECT_THAT(word_counts,
+              Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
+                                         Pair("buffalo", 2)))));
+}
+
+TEST(WhenSortedTest, WorksForMultiMapTypes) {
+  multimap<int, int> ifib;
+  ifib.insert(make_pair(8, 6));
+  ifib.insert(make_pair(2, 3));
+  ifib.insert(make_pair(1, 1));
+  ifib.insert(make_pair(3, 4));
+  ifib.insert(make_pair(1, 2));
+  ifib.insert(make_pair(5, 5));
+  EXPECT_THAT(ifib,
+              WhenSorted(ElementsAre(Pair(1, 1), Pair(1, 2), Pair(2, 3),
+                                     Pair(3, 4), Pair(5, 5), Pair(8, 6))));
+  EXPECT_THAT(ifib,
+              Not(WhenSorted(ElementsAre(Pair(8, 6), Pair(2, 3), Pair(1, 1),
+                                         Pair(3, 4), Pair(1, 2), Pair(5, 5)))));
+}
+
+TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
+  std::deque<int> d;
+  d.push_back(2);
+  d.push_back(1);
+  EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
+  EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
+}
+
+TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
+  std::deque<int> d;
+  d.push_back(2);
+  d.push_back(1);
+  Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
+  EXPECT_THAT(d, WhenSorted(vector_match));
+  Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
+  EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
+}
+
+// Deliberately bare pseudo-container.
+// Offers only begin() and end() accessors, yielding InputIterator.
+template <typename T>
+class Streamlike {
+ private:
+  class ConstIter;
+
+ public:
+  typedef ConstIter const_iterator;
+  typedef T value_type;
+
+  template <typename InIter>
+  Streamlike(InIter first, InIter last) : remainder_(first, last) {}
+
+  const_iterator begin() const {
+    return const_iterator(this, remainder_.begin());
+  }
+  const_iterator end() const { return const_iterator(this, remainder_.end()); }
+
+ private:
+  class ConstIter {
+   public:
+    using iterator_category = std::input_iterator_tag;
+    using value_type = T;
+    using difference_type = ptrdiff_t;
+    using pointer = const value_type*;
+    using reference = const value_type&;
+
+    ConstIter(const Streamlike* s, typename std::list<value_type>::iterator pos)
+        : s_(s), pos_(pos) {}
+
+    const value_type& operator*() const { return *pos_; }
+    const value_type* operator->() const { return &*pos_; }
+    ConstIter& operator++() {
+      s_->remainder_.erase(pos_++);
+      return *this;
+    }
+
+    // *iter++ is required to work (see std::istreambuf_iterator).
+    // (void)iter++ is also required to work.
+    class PostIncrProxy {
+     public:
+      explicit PostIncrProxy(const value_type& value) : value_(value) {}
+      value_type operator*() const { return value_; }
+
+     private:
+      value_type value_;
+    };
+    PostIncrProxy operator++(int) {
+      PostIncrProxy proxy(**this);
+      ++(*this);
+      return proxy;
+    }
+
+    friend bool operator==(const ConstIter& a, const ConstIter& b) {
+      return a.s_ == b.s_ && a.pos_ == b.pos_;
+    }
+    friend bool operator!=(const ConstIter& a, const ConstIter& b) {
+      return !(a == b);
+    }
+
+   private:
+    const Streamlike* s_;
+    typename std::list<value_type>::iterator pos_;
+  };
+
+  friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
+    os << "[";
+    typedef typename std::list<value_type>::const_iterator Iter;
+    const char* sep = "";
+    for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
+      os << sep << *it;
+      sep = ",";
+    }
+    os << "]";
+    return os;
+  }
+
+  mutable std::list<value_type> remainder_;  // modified by iteration
+};
+
+TEST(StreamlikeTest, Iteration) {
+  const int a[5] = {2, 1, 4, 5, 3};
+  Streamlike<int> s(a, a + 5);
+  Streamlike<int>::const_iterator it = s.begin();
+  const int* ip = a;
+  while (it != s.end()) {
+    SCOPED_TRACE(ip - a);
+    EXPECT_EQ(*ip++, *it++);
+  }
+}
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(BeginEndDistanceIsTest);
+
+TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
+  std::forward_list<int> container;
+  EXPECT_THAT(container, BeginEndDistanceIs(0));
+  EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
+  container.push_front(0);
+  EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
+  EXPECT_THAT(container, BeginEndDistanceIs(1));
+  container.push_front(0);
+  EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
+  EXPECT_THAT(container, BeginEndDistanceIs(2));
+}
+
+TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
+  const int a[5] = {1, 2, 3, 4, 5};
+  Streamlike<int> s(a, a + 5);
+  EXPECT_THAT(s, BeginEndDistanceIs(5));
+}
+
+TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
+  Matcher<vector<int>> m = BeginEndDistanceIs(2);
+  EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
+  EXPECT_EQ("distance between begin() and end() isn't equal to 2",
+            DescribeNegation(m));
+}
+
+TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
+  ContainerHelper helper;
+  EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));
+  helper.Call(MakeUniquePtrs({1, 2}));
+}
+
+TEST_P(BeginEndDistanceIsTestP, ExplainsResult) {
+  Matcher<vector<int>> m1 = BeginEndDistanceIs(2);
+  Matcher<vector<int>> m2 = BeginEndDistanceIs(Lt(2));
+  Matcher<vector<int>> m3 = BeginEndDistanceIs(AnyOf(0, 3));
+  Matcher<vector<int>> m4 = BeginEndDistanceIs(GreaterThan(1));
+  vector<int> container;
+  EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
+            Explain(m1, container));
+  EXPECT_EQ("whose distance between begin() and end() 0 matches",
+            Explain(m2, container));
+  EXPECT_EQ("whose distance between begin() and end() 0 matches",
+            Explain(m3, container));
+  EXPECT_EQ(
+      "whose distance between begin() and end() 0 doesn't match, which is 1 "
+      "less than 1",
+      Explain(m4, container));
+  container.push_back(0);
+  container.push_back(0);
+  EXPECT_EQ("whose distance between begin() and end() 2 matches",
+            Explain(m1, container));
+  EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
+            Explain(m2, container));
+  EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
+            Explain(m3, container));
+  EXPECT_EQ(
+      "whose distance between begin() and end() 2 matches, which is 1 more "
+      "than 1",
+      Explain(m4, container));
+}
+
+TEST(WhenSortedTest, WorksForStreamlike) {
+  // Streamlike 'container' provides only minimal iterator support.
+  // Its iterators are tagged with input_iterator_tag.
+  const int a[5] = {2, 1, 4, 5, 3};
+  Streamlike<int> s(std::begin(a), std::end(a));
+  EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
+  EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
+}
+
+TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
+  const int a[] = {2, 1, 4, 5, 3};
+  Streamlike<int> s(std::begin(a), std::end(a));
+  Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
+  EXPECT_THAT(s, WhenSorted(vector_match));
+  EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
+}
+
+TEST(IsSupersetOfTest, WorksForNativeArray) {
+  const int subset[] = {1, 4};
+  const int superset[] = {1, 2, 4};
+  const int disjoint[] = {1, 0, 3};
+  EXPECT_THAT(subset, IsSupersetOf(subset));
+  EXPECT_THAT(subset, Not(IsSupersetOf(superset)));
+  EXPECT_THAT(superset, IsSupersetOf(subset));
+  EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));
+  EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));
+}
+
+TEST(IsSupersetOfTest, WorksWithDuplicates) {
+  const int not_enough[] = {1, 2};
+  const int enough[] = {1, 1, 2};
+  const int expected[] = {1, 1};
+  EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));
+  EXPECT_THAT(enough, IsSupersetOf(expected));
+}
+
+TEST(IsSupersetOfTest, WorksForEmpty) {
+  vector<int> numbers;
+  vector<int> expected;
+  EXPECT_THAT(numbers, IsSupersetOf(expected));
+  expected.push_back(1);
+  EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
+  expected.clear();
+  numbers.push_back(1);
+  numbers.push_back(2);
+  EXPECT_THAT(numbers, IsSupersetOf(expected));
+  expected.push_back(1);
+  EXPECT_THAT(numbers, IsSupersetOf(expected));
+  expected.push_back(2);
+  EXPECT_THAT(numbers, IsSupersetOf(expected));
+  expected.push_back(3);
+  EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
+}
+
+TEST(IsSupersetOfTest, WorksForStreamlike) {
+  const int a[5] = {1, 2, 3, 4, 5};
+  Streamlike<int> s(std::begin(a), std::end(a));
+
+  vector<int> expected;
+  expected.push_back(1);
+  expected.push_back(2);
+  expected.push_back(5);
+  EXPECT_THAT(s, IsSupersetOf(expected));
+
+  expected.push_back(0);
+  EXPECT_THAT(s, Not(IsSupersetOf(expected)));
+}
+
+TEST(IsSupersetOfTest, TakesStlContainer) {
+  const int actual[] = {3, 1, 2};
+
+  ::std::list<int> expected;
+  expected.push_back(1);
+  expected.push_back(3);
+  EXPECT_THAT(actual, IsSupersetOf(expected));
+
+  expected.push_back(4);
+  EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
+}
+
+TEST(IsSupersetOfTest, Describe) {
+  typedef std::vector<int> IntVec;
+  IntVec expected;
+  expected.push_back(111);
+  expected.push_back(222);
+  expected.push_back(333);
+  EXPECT_THAT(
+      Describe<IntVec>(IsSupersetOf(expected)),
+      Eq("a surjection from elements to requirements exists such that:\n"
+         " - an element is equal to 111\n"
+         " - an element is equal to 222\n"
+         " - an element is equal to 333"));
+}
+
+TEST(IsSupersetOfTest, DescribeNegation) {
+  typedef std::vector<int> IntVec;
+  IntVec expected;
+  expected.push_back(111);
+  expected.push_back(222);
+  expected.push_back(333);
+  EXPECT_THAT(
+      DescribeNegation<IntVec>(IsSupersetOf(expected)),
+      Eq("no surjection from elements to requirements exists such that:\n"
+         " - an element is equal to 111\n"
+         " - an element is equal to 222\n"
+         " - an element is equal to 333"));
+}
+
+TEST(IsSupersetOfTest, MatchAndExplain) {
+  std::vector<int> v;
+  v.push_back(2);
+  v.push_back(3);
+  std::vector<int> expected;
+  expected.push_back(1);
+  expected.push_back(2);
+  StringMatchResultListener listener;
+  ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
+      << listener.str();
+  EXPECT_THAT(listener.str(),
+              Eq("where the following matchers don't match any elements:\n"
+                 "matcher #0: is equal to 1"));
+
+  v.push_back(1);
+  listener.Clear();
+  ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
+      << listener.str();
+  EXPECT_THAT(listener.str(), Eq("where:\n"
+                                 " - element #0 is matched by matcher #1,\n"
+                                 " - element #2 is matched by matcher #0"));
+}
+
+TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
+  const int numbers[] = {1, 3, 6, 2, 4, 5};
+  EXPECT_THAT(numbers, IsSupersetOf({1, 2}));
+  EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));
+}
+
+TEST(IsSupersetOfTest, WorksWithMoveOnly) {
+  ContainerHelper helper;
+  EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));
+  helper.Call(MakeUniquePtrs({1, 2}));
+  EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));
+  helper.Call(MakeUniquePtrs({2}));
+}
+
+TEST(IsSubsetOfTest, WorksForNativeArray) {
+  const int subset[] = {1, 4};
+  const int superset[] = {1, 2, 4};
+  const int disjoint[] = {1, 0, 3};
+  EXPECT_THAT(subset, IsSubsetOf(subset));
+  EXPECT_THAT(subset, IsSubsetOf(superset));
+  EXPECT_THAT(superset, Not(IsSubsetOf(subset)));
+  EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));
+  EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));
+}
+
+TEST(IsSubsetOfTest, WorksWithDuplicates) {
+  const int not_enough[] = {1, 2};
+  const int enough[] = {1, 1, 2};
+  const int actual[] = {1, 1};
+  EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));
+  EXPECT_THAT(actual, IsSubsetOf(enough));
+}
+
+TEST(IsSubsetOfTest, WorksForEmpty) {
+  vector<int> numbers;
+  vector<int> expected;
+  EXPECT_THAT(numbers, IsSubsetOf(expected));
+  expected.push_back(1);
+  EXPECT_THAT(numbers, IsSubsetOf(expected));
+  expected.clear();
+  numbers.push_back(1);
+  numbers.push_back(2);
+  EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
+  expected.push_back(1);
+  EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
+  expected.push_back(2);
+  EXPECT_THAT(numbers, IsSubsetOf(expected));
+  expected.push_back(3);
+  EXPECT_THAT(numbers, IsSubsetOf(expected));
+}
+
+TEST(IsSubsetOfTest, WorksForStreamlike) {
+  const int a[5] = {1, 2};
+  Streamlike<int> s(std::begin(a), std::end(a));
+
+  vector<int> expected;
+  expected.push_back(1);
+  EXPECT_THAT(s, Not(IsSubsetOf(expected)));
+  expected.push_back(2);
+  expected.push_back(5);
+  EXPECT_THAT(s, IsSubsetOf(expected));
+}
+
+TEST(IsSubsetOfTest, TakesStlContainer) {
+  const int actual[] = {3, 1, 2};
+
+  ::std::list<int> expected;
+  expected.push_back(1);
+  expected.push_back(3);
+  EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
+
+  expected.push_back(2);
+  expected.push_back(4);
+  EXPECT_THAT(actual, IsSubsetOf(expected));
+}
+
+TEST(IsSubsetOfTest, Describe) {
+  typedef std::vector<int> IntVec;
+  IntVec expected;
+  expected.push_back(111);
+  expected.push_back(222);
+  expected.push_back(333);
+
+  EXPECT_THAT(
+      Describe<IntVec>(IsSubsetOf(expected)),
+      Eq("an injection from elements to requirements exists such that:\n"
+         " - an element is equal to 111\n"
+         " - an element is equal to 222\n"
+         " - an element is equal to 333"));
+}
+
+TEST(IsSubsetOfTest, DescribeNegation) {
+  typedef std::vector<int> IntVec;
+  IntVec expected;
+  expected.push_back(111);
+  expected.push_back(222);
+  expected.push_back(333);
+  EXPECT_THAT(
+      DescribeNegation<IntVec>(IsSubsetOf(expected)),
+      Eq("no injection from elements to requirements exists such that:\n"
+         " - an element is equal to 111\n"
+         " - an element is equal to 222\n"
+         " - an element is equal to 333"));
+}
+
+TEST(IsSubsetOfTest, MatchAndExplain) {
+  std::vector<int> v;
+  v.push_back(2);
+  v.push_back(3);
+  std::vector<int> expected;
+  expected.push_back(1);
+  expected.push_back(2);
+  StringMatchResultListener listener;
+  ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
+      << listener.str();
+  EXPECT_THAT(listener.str(),
+              Eq("where the following elements don't match any matchers:\n"
+                 "element #1: 3"));
+
+  expected.push_back(3);
+  listener.Clear();
+  ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
+      << listener.str();
+  EXPECT_THAT(listener.str(), Eq("where:\n"
+                                 " - element #0 is matched by matcher #1,\n"
+                                 " - element #1 is matched by matcher #2"));
+}
+
+TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
+  const int numbers[] = {1, 2, 3};
+  EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));
+  EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));
+}
+
+TEST(IsSubsetOfTest, WorksWithMoveOnly) {
+  ContainerHelper helper;
+  EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));
+  helper.Call(MakeUniquePtrs({1}));
+  EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));
+  helper.Call(MakeUniquePtrs({2}));
+}
+
+// Tests using ElementsAre() and ElementsAreArray() with stream-like
+// "containers".
+
+TEST(ElemensAreStreamTest, WorksForStreamlike) {
+  const int a[5] = {1, 2, 3, 4, 5};
+  Streamlike<int> s(std::begin(a), std::end(a));
+  EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
+  EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
+}
+
+TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
+  const int a[5] = {1, 2, 3, 4, 5};
+  Streamlike<int> s(std::begin(a), std::end(a));
+
+  vector<int> expected;
+  expected.push_back(1);
+  expected.push_back(2);
+  expected.push_back(3);
+  expected.push_back(4);
+  expected.push_back(5);
+  EXPECT_THAT(s, ElementsAreArray(expected));
+
+  expected[3] = 0;
+  EXPECT_THAT(s, Not(ElementsAreArray(expected)));
+}
+
+TEST(ElementsAreTest, WorksWithUncopyable) {
+  Uncopyable objs[2];
+  objs[0].set_value(-3);
+  objs[1].set_value(1);
+  EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
+}
+
+TEST(ElementsAreTest, WorksWithMoveOnly) {
+  ContainerHelper helper;
+  EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));
+  helper.Call(MakeUniquePtrs({1, 2}));
+
+  EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));
+  helper.Call(MakeUniquePtrs({3, 4}));
+}
+
+TEST(ElementsAreTest, TakesStlContainer) {
+  const int actual[] = {3, 1, 2};
+
+  ::std::list<int> expected;
+  expected.push_back(3);
+  expected.push_back(1);
+  expected.push_back(2);
+  EXPECT_THAT(actual, ElementsAreArray(expected));
+
+  expected.push_back(4);
+  EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
+}
+
+// Tests for UnorderedElementsAreArray()
+
+TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
+  const int a[] = {0, 1, 2, 3, 4};
+  std::vector<int> s(std::begin(a), std::end(a));
+  do {
+    StringMatchResultListener listener;
+    EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), s, &listener))
+        << listener.str();
+  } while (std::next_permutation(s.begin(), s.end()));
+}
+
+TEST(UnorderedElementsAreArrayTest, VectorBool) {
+  const bool a[] = {0, 1, 0, 1, 1};
+  const bool b[] = {1, 0, 1, 1, 0};
+  std::vector<bool> expected(std::begin(a), std::end(a));
+  std::vector<bool> actual(std::begin(b), std::end(b));
+  StringMatchResultListener listener;
+  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected), actual,
+                                 &listener))
+      << listener.str();
+}
+
+TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
+  // Streamlike 'container' provides only minimal iterator support.
+  // Its iterators are tagged with input_iterator_tag, and it has no
+  // size() or empty() methods.
+  const int a[5] = {2, 1, 4, 5, 3};
+  Streamlike<int> s(std::begin(a), std::end(a));
+
+  ::std::vector<int> expected;
+  expected.push_back(1);
+  expected.push_back(2);
+  expected.push_back(3);
+  expected.push_back(4);
+  expected.push_back(5);
+  EXPECT_THAT(s, UnorderedElementsAreArray(expected));
+
+  expected.push_back(6);
+  EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
+}
+
+TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
+  const int actual[] = {3, 1, 2};
+
+  ::std::list<int> expected;
+  expected.push_back(1);
+  expected.push_back(2);
+  expected.push_back(3);
+  EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
+
+  expected.push_back(4);
+  EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
+}
+
+TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
+  const int a[5] = {2, 1, 4, 5, 3};
+  EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
+  EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
+}
+
+TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
+  const std::string a[5] = {"a", "b", "c", "d", "e"};
+  EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
+  EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
+}
+
+TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
+  const int a[5] = {2, 1, 4, 5, 3};
+  EXPECT_THAT(a,
+              UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
+  EXPECT_THAT(
+      a, Not(UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
+}
+
+TEST(UnorderedElementsAreArrayTest,
+     TakesInitializerListOfDifferentTypedMatchers) {
+  const int a[5] = {2, 1, 4, 5, 3};
+  // The compiler cannot infer the type of the initializer list if its
+  // elements have different types.  We must explicitly specify the
+  // unified element type in this case.
+  EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int>>(
+                     {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
+  EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int>>(
+                     {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
+}
+
+TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
+  ContainerHelper helper;
+  EXPECT_CALL(helper,
+              Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
+  helper.Call(MakeUniquePtrs({2, 1}));
+}
+
+class UnorderedElementsAreTest : public testing::Test {
+ protected:
+  typedef std::vector<int> IntVec;
+};
+
+TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
+  Uncopyable objs[2];
+  objs[0].set_value(-3);
+  objs[1].set_value(1);
+  EXPECT_THAT(objs,
+              UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
+}
+
+TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
+  const int a[] = {1, 2, 3};
+  std::vector<int> s(std::begin(a), std::end(a));
+  do {
+    StringMatchResultListener listener;
+    EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), s, &listener))
+        << listener.str();
+  } while (std::next_permutation(s.begin(), s.end()));
+}
+
+TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
+  const int a[] = {1, 2, 3};
+  std::vector<int> s(std::begin(a), std::end(a));
+  std::vector<Matcher<int>> mv;
+  mv.push_back(1);
+  mv.push_back(2);
+  mv.push_back(2);
+  // The element with value '3' matches nothing: fail fast.
+  StringMatchResultListener listener;
+  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
+      << listener.str();
+}
+
+TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
+  // Streamlike 'container' provides only minimal iterator support.
+  // Its iterators are tagged with input_iterator_tag, and it has no
+  // size() or empty() methods.
+  const int a[5] = {2, 1, 4, 5, 3};
+  Streamlike<int> s(std::begin(a), std::end(a));
+
+  EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
+  EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
+}
+
+TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
+  ContainerHelper helper;
+  EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
+  helper.Call(MakeUniquePtrs({2, 1}));
+}
+
+// One naive implementation of the matcher runs in O(N!) time, which is too
+// slow for many real-world inputs. This test shows that our matcher can match
+// 100 inputs very quickly (a few milliseconds).  An O(100!) is 10^158
+// iterations and obviously effectively incomputable.
+// [ RUN      ] UnorderedElementsAreTest.Performance
+// [       OK ] UnorderedElementsAreTest.Performance (4 ms)
+TEST_F(UnorderedElementsAreTest, Performance) {
+  std::vector<int> s;
+  std::vector<Matcher<int>> mv;
+  for (int i = 0; i < 100; ++i) {
+    s.push_back(i);
+    mv.push_back(_);
+  }
+  mv[50] = Eq(0);
+  StringMatchResultListener listener;
+  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
+      << listener.str();
+}
+
+// Another variant of 'Performance' with similar expectations.
+// [ RUN      ] UnorderedElementsAreTest.PerformanceHalfStrict
+// [       OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
+TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
+  std::vector<int> s;
+  std::vector<Matcher<int>> mv;
+  for (int i = 0; i < 100; ++i) {
+    s.push_back(i);
+    if (i & 1) {
+      mv.push_back(_);
+    } else {
+      mv.push_back(i);
+    }
+  }
+  StringMatchResultListener listener;
+  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))
+      << listener.str();
+}
+
+TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
+  std::vector<int> v;
+  v.push_back(4);
+  StringMatchResultListener listener;
+  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))
+      << listener.str();
+  EXPECT_THAT(listener.str(), Eq("which has 1 element"));
+}
+
+TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
+  std::vector<int> v;
+  StringMatchResultListener listener;
+  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))
+      << listener.str();
+  EXPECT_THAT(listener.str(), Eq(""));
+}
+
+TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
+  std::vector<int> v;
+  v.push_back(1);
+  v.push_back(1);
+  StringMatchResultListener listener;
+  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener))
+      << listener.str();
+  EXPECT_THAT(listener.str(),
+              Eq("where the following matchers don't match any elements:\n"
+                 "matcher #1: is equal to 2"));
+}
+
+TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
+  std::vector<int> v;
+  v.push_back(1);
+  v.push_back(2);
+  StringMatchResultListener listener;
+  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1), v, &listener))
+      << listener.str();
+  EXPECT_THAT(listener.str(),
+              Eq("where the following elements don't match any matchers:\n"
+                 "element #1: 2"));
+}
+
+TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
+  std::vector<int> v;
+  v.push_back(2);
+  v.push_back(3);
+  StringMatchResultListener listener;
+  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener))
+      << listener.str();
+  EXPECT_THAT(listener.str(),
+              Eq("where"
+                 " the following matchers don't match any elements:\n"
+                 "matcher #0: is equal to 1\n"
+                 "and"
+                 " where"
+                 " the following elements don't match any matchers:\n"
+                 "element #1: 3"));
+}
+
+// Test helper for formatting element, matcher index pairs in expectations.
+static std::string EMString(int element, int matcher) {
+  stringstream ss;
+  ss << "(element #" << element << ", matcher #" << matcher << ")";
+  return ss.str();
+}
+
+TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
+  // A situation where all elements and matchers have a match
+  // associated with them, but the max matching is not perfect.
+  std::vector<std::string> v;
+  v.push_back("a");
+  v.push_back("b");
+  v.push_back("c");
+  StringMatchResultListener listener;
+  EXPECT_FALSE(ExplainMatchResult(
+      UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
+      << listener.str();
+
+  std::string prefix =
+      "where no permutation of the elements can satisfy all matchers, "
+      "and the closest match is 2 of 3 matchers with the "
+      "pairings:\n";
+
+  // We have to be a bit loose here, because there are 4 valid max matches.
+  EXPECT_THAT(
+      listener.str(),
+      AnyOf(
+          prefix + "{\n  " + EMString(0, 0) + ",\n  " + EMString(1, 2) + "\n}",
+          prefix + "{\n  " + EMString(0, 1) + ",\n  " + EMString(1, 2) + "\n}",
+          prefix + "{\n  " + EMString(0, 0) + ",\n  " + EMString(2, 2) + "\n}",
+          prefix + "{\n  " + EMString(0, 1) + ",\n  " + EMString(2, 2) +
+              "\n}"));
+}
+
+TEST_F(UnorderedElementsAreTest, Describe) {
+  EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()), Eq("is empty"));
+  EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(345)),
+              Eq("has 1 element and that element is equal to 345"));
+  EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
+              Eq("has 3 elements and there exists some permutation "
+                 "of elements such that:\n"
+                 " - element #0 is equal to 111, and\n"
+                 " - element #1 is equal to 222, and\n"
+                 " - element #2 is equal to 333"));
+}
+
+TEST_F(UnorderedElementsAreTest, DescribeNegation) {
+  EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
+              Eq("isn't empty"));
+  EXPECT_THAT(
+      DescribeNegation<IntVec>(UnorderedElementsAre(345)),
+      Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
+  EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
+              Eq("doesn't have 3 elements, or there exists no permutation "
+                 "of elements such that:\n"
+                 " - element #0 is equal to 123, and\n"
+                 " - element #1 is equal to 234, and\n"
+                 " - element #2 is equal to 345"));
+}
+
+// Tests Each().
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(EachTest);
+
+TEST_P(EachTestP, ExplainsMatchResultCorrectly) {
+  set<int> a;  // empty
+
+  Matcher<set<int>> m = Each(2);
+  EXPECT_EQ("", Explain(m, a));
+
+  Matcher<const int(&)[1]> n = Each(1);  // NOLINT
+
+  const int b[1] = {1};
+  EXPECT_EQ("", Explain(n, b));
+
+  n = Each(3);
+  EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
+
+  a.insert(1);
+  a.insert(2);
+  a.insert(3);
+  m = Each(GreaterThan(0));
+  EXPECT_EQ("", Explain(m, a));
+
+  m = Each(GreaterThan(10));
+  EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
+            Explain(m, a));
+}
+
+TEST(EachTest, DescribesItselfCorrectly) {
+  Matcher<vector<int>> m = Each(1);
+  EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
+
+  Matcher<vector<int>> m2 = Not(m);
+  EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
+}
+
+TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
+  vector<int> some_vector;
+  EXPECT_THAT(some_vector, Each(1));
+  some_vector.push_back(3);
+  EXPECT_THAT(some_vector, Not(Each(1)));
+  EXPECT_THAT(some_vector, Each(3));
+  some_vector.push_back(1);
+  some_vector.push_back(2);
+  EXPECT_THAT(some_vector, Not(Each(3)));
+  EXPECT_THAT(some_vector, Each(Lt(3.5)));
+
+  vector<std::string> another_vector;
+  another_vector.push_back("fee");
+  EXPECT_THAT(another_vector, Each(std::string("fee")));
+  another_vector.push_back("fie");
+  another_vector.push_back("foe");
+  another_vector.push_back("fum");
+  EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
+}
+
+TEST(EachTest, MatchesMapWhenAllElementsMatch) {
+  map<const char*, int> my_map;
+  const char* bar = "a string";
+  my_map[bar] = 2;
+  EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
+
+  map<std::string, int> another_map;
+  EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
+  another_map["fee"] = 1;
+  EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
+  another_map["fie"] = 2;
+  another_map["foe"] = 3;
+  another_map["fum"] = 4;
+  EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
+  EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
+  EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
+}
+
+TEST(EachTest, AcceptsMatcher) {
+  const int a[] = {1, 2, 3};
+  EXPECT_THAT(a, Each(Gt(0)));
+  EXPECT_THAT(a, Not(Each(Gt(1))));
+}
+
+TEST(EachTest, WorksForNativeArrayAsTuple) {
+  const int a[] = {1, 2};
+  const int* const pointer = a;
+  EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));
+  EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));
+}
+
+TEST(EachTest, WorksWithMoveOnly) {
+  ContainerHelper helper;
+  EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));
+  helper.Call(MakeUniquePtrs({1, 2}));
+}
+
+// For testing Pointwise().
+class IsHalfOfMatcher {
+ public:
+  template <typename T1, typename T2>
+  bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,
+                       MatchResultListener* listener) const {
+    if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {
+      *listener << "where the second is " << std::get<1>(a_pair);
+      return true;
+    } else {
+      *listener << "where the second/2 is " << std::get<1>(a_pair) / 2;
+      return false;
+    }
+  }
+
+  void DescribeTo(ostream* os) const {
+    *os << "are a pair where the first is half of the second";
+  }
+
+  void DescribeNegationTo(ostream* os) const {
+    *os << "are a pair where the first isn't half of the second";
+  }
+};
+
+PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
+  return MakePolymorphicMatcher(IsHalfOfMatcher());
+}
+
+TEST(PointwiseTest, DescribesSelf) {
+  vector<int> rhs;
+  rhs.push_back(1);
+  rhs.push_back(2);
+  rhs.push_back(3);
+  const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
+  EXPECT_EQ(
+      "contains 3 values, where each value and its corresponding value "
+      "in { 1, 2, 3 } are a pair where the first is half of the second",
+      Describe(m));
+  EXPECT_EQ(
+      "doesn't contain exactly 3 values, or contains a value x at some "
+      "index i where x and the i-th value of { 1, 2, 3 } are a pair "
+      "where the first isn't half of the second",
+      DescribeNegation(m));
+}
+
+TEST(PointwiseTest, MakesCopyOfRhs) {
+  list<signed char> rhs;
+  rhs.push_back(2);
+  rhs.push_back(4);
+
+  int lhs[] = {1, 2};
+  const Matcher<const int(&)[2]> m = Pointwise(IsHalfOf(), rhs);
+  EXPECT_THAT(lhs, m);
+
+  // Changing rhs now shouldn't affect m, which made a copy of rhs.
+  rhs.push_back(6);
+  EXPECT_THAT(lhs, m);
+}
+
+TEST(PointwiseTest, WorksForLhsNativeArray) {
+  const int lhs[] = {1, 2, 3};
+  vector<int> rhs;
+  rhs.push_back(2);
+  rhs.push_back(4);
+  rhs.push_back(6);
+  EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
+  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
+}
+
+TEST(PointwiseTest, WorksForRhsNativeArray) {
+  const int rhs[] = {1, 2, 3};
+  vector<int> lhs;
+  lhs.push_back(2);
+  lhs.push_back(4);
+  lhs.push_back(6);
+  EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
+  EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
+}
+
+// Test is effective only with sanitizers.
+TEST(PointwiseTest, WorksForVectorOfBool) {
+  vector<bool> rhs(3, false);
+  rhs[1] = true;
+  vector<bool> lhs = rhs;
+  EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
+  rhs[0] = true;
+  EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
+}
+
+TEST(PointwiseTest, WorksForRhsInitializerList) {
+  const vector<int> lhs{2, 4, 6};
+  EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
+  EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
+}
+
+TEST(PointwiseTest, RejectsWrongSize) {
+  const double lhs[2] = {1, 2};
+  const int rhs[1] = {0};
+  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
+  EXPECT_EQ("which contains 2 values", Explain(Pointwise(Gt(), rhs), lhs));
+
+  const int rhs2[3] = {0, 1, 2};
+  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
+}
+
+TEST(PointwiseTest, RejectsWrongContent) {
+  const double lhs[3] = {1, 2, 3};
+  const int rhs[3] = {2, 6, 4};
+  EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
+  EXPECT_EQ(
+      "where the value pair (2, 6) at index #1 don't match, "
+      "where the second/2 is 3",
+      Explain(Pointwise(IsHalfOf(), rhs), lhs));
+}
+
+TEST(PointwiseTest, AcceptsCorrectContent) {
+  const double lhs[3] = {1, 2, 3};
+  const int rhs[3] = {2, 4, 6};
+  EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
+  EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
+}
+
+TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
+  const double lhs[3] = {1, 2, 3};
+  const int rhs[3] = {2, 4, 6};
+  const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
+  EXPECT_THAT(lhs, Pointwise(m1, rhs));
+  EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
+
+  // This type works as a std::tuple<const double&, const int&> can be
+  // implicitly cast to std::tuple<double, int>.
+  const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
+  EXPECT_THAT(lhs, Pointwise(m2, rhs));
+  EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
+}
+
+MATCHER(PointeeEquals, "Points to an equal value") {
+  return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
+                            ::testing::get<0>(arg), result_listener);
+}
+
+TEST(PointwiseTest, WorksWithMoveOnly) {
+  ContainerHelper helper;
+  EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
+  helper.Call(MakeUniquePtrs({1, 2}));
+}
+
+TEST(UnorderedPointwiseTest, DescribesSelf) {
+  vector<int> rhs;
+  rhs.push_back(1);
+  rhs.push_back(2);
+  rhs.push_back(3);
+  const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
+  EXPECT_EQ(
+      "has 3 elements and there exists some permutation of elements such "
+      "that:\n"
+      " - element #0 and 1 are a pair where the first is half of the second, "
+      "and\n"
+      " - element #1 and 2 are a pair where the first is half of the second, "
+      "and\n"
+      " - element #2 and 3 are a pair where the first is half of the second",
+      Describe(m));
+  EXPECT_EQ(
+      "doesn't have 3 elements, or there exists no permutation of elements "
+      "such that:\n"
+      " - element #0 and 1 are a pair where the first is half of the second, "
+      "and\n"
+      " - element #1 and 2 are a pair where the first is half of the second, "
+      "and\n"
+      " - element #2 and 3 are a pair where the first is half of the second",
+      DescribeNegation(m));
+}
+
+TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
+  list<signed char> rhs;
+  rhs.push_back(2);
+  rhs.push_back(4);
+
+  int lhs[] = {2, 1};
+  const Matcher<const int(&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
+  EXPECT_THAT(lhs, m);
+
+  // Changing rhs now shouldn't affect m, which made a copy of rhs.
+  rhs.push_back(6);
+  EXPECT_THAT(lhs, m);
+}
+
+TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
+  const int lhs[] = {1, 2, 3};
+  vector<int> rhs;
+  rhs.push_back(4);
+  rhs.push_back(6);
+  rhs.push_back(2);
+  EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
+  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
+}
+
+TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
+  const int rhs[] = {1, 2, 3};
+  vector<int> lhs;
+  lhs.push_back(4);
+  lhs.push_back(2);
+  lhs.push_back(6);
+  EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
+  EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
+}
+
+TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
+  const vector<int> lhs{2, 4, 6};
+  EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
+  EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
+}
+
+TEST(UnorderedPointwiseTest, RejectsWrongSize) {
+  const double lhs[2] = {1, 2};
+  const int rhs[1] = {0};
+  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
+  EXPECT_EQ("which has 2 elements",
+            Explain(UnorderedPointwise(Gt(), rhs), lhs));
+
+  const int rhs2[3] = {0, 1, 2};
+  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
+}
+
+TEST(UnorderedPointwiseTest, RejectsWrongContent) {
+  const double lhs[3] = {1, 2, 3};
+  const int rhs[3] = {2, 6, 6};
+  EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
+  EXPECT_EQ(
+      "where the following elements don't match any matchers:\n"
+      "element #1: 2",
+      Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
+}
+
+TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
+  const double lhs[3] = {1, 2, 3};
+  const int rhs[3] = {2, 4, 6};
+  EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
+}
+
+TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
+  const double lhs[3] = {1, 2, 3};
+  const int rhs[3] = {6, 4, 2};
+  EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
+}
+
+TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
+  const double lhs[3] = {1, 2, 3};
+  const int rhs[3] = {4, 6, 2};
+  const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
+  EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
+
+  // This type works as a std::tuple<const double&, const int&> can be
+  // implicitly cast to std::tuple<double, int>.
+  const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
+  EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
+}
+
+TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
+  ContainerHelper helper;
+  EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
+                                              std::vector<int>{1, 2})));
+  helper.Call(MakeUniquePtrs({2, 1}));
+}
+
+TEST(PointeeTest, WorksOnMoveOnlyType) {
+  std::unique_ptr<int> p(new int(3));
+  EXPECT_THAT(p, Pointee(Eq(3)));
+  EXPECT_THAT(p, Not(Pointee(Eq(2))));
+}
+
+class PredicateFormatterFromMatcherTest : public ::testing::Test {
+ protected:
+  enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
+
+  // A matcher that can return different results when used multiple times on the
+  // same input. No real matcher should do this; but this lets us test that we
+  // detect such behavior and fail appropriately.
+  class MockMatcher : public MatcherInterface<Behavior> {
+   public:
+    bool MatchAndExplain(Behavior behavior,
+                         MatchResultListener* listener) const override {
+      *listener << "[MatchAndExplain]";
+      switch (behavior) {
+        case kInitialSuccess:
+          // The first call to MatchAndExplain should use a "not interested"
+          // listener; so this is expected to return |true|. There should be no
+          // subsequent calls.
+          return !listener->IsInterested();
+
+        case kAlwaysFail:
+          return false;
+
+        case kFlaky:
+          // The first call to MatchAndExplain should use a "not interested"
+          // listener; so this will return |false|. Subsequent calls should have
+          // an "interested" listener; so this will return |true|, thus
+          // simulating a flaky matcher.
+          return listener->IsInterested();
+      }
+
+      GTEST_LOG_(FATAL) << "This should never be reached";
+      return false;
+    }
+
+    void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }
+
+    void DescribeNegationTo(ostream* os) const override {
+      *os << "[DescribeNegationTo]";
+    }
+  };
+
+  AssertionResult RunPredicateFormatter(Behavior behavior) {
+    auto matcher = MakeMatcher(new MockMatcher);
+    PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(
+        matcher);
+    return predicate_formatter("dummy-name", behavior);
+  }
+};
+
+TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
+  AssertionResult result = RunPredicateFormatter(kInitialSuccess);
+  EXPECT_TRUE(result);  // Implicit cast to bool.
+  std::string expect;
+  EXPECT_EQ(expect, result.message());
+}
+
+TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
+  AssertionResult result = RunPredicateFormatter(kAlwaysFail);
+  EXPECT_FALSE(result);  // Implicit cast to bool.
+  std::string expect =
+      "Value of: dummy-name\nExpected: [DescribeTo]\n"
+      "  Actual: 1" +
+      OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
+  EXPECT_EQ(expect, result.message());
+}
+
+TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
+  AssertionResult result = RunPredicateFormatter(kFlaky);
+  EXPECT_FALSE(result);  // Implicit cast to bool.
+  std::string expect =
+      "Value of: dummy-name\nExpected: [DescribeTo]\n"
+      "  The matcher failed on the initial attempt; but passed when rerun to "
+      "generate the explanation.\n"
+      "  Actual: 2" +
+      OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
+  EXPECT_EQ(expect, result.message());
+}
+
+// Tests for ElementsAre().
+
+TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
+  Matcher<const vector<int>&> m = ElementsAre();
+  EXPECT_EQ("is empty", Describe(m));
+}
+
+TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
+  Matcher<vector<int>> m = ElementsAre(Gt(5));
+  EXPECT_EQ("has 1 element that is > 5", Describe(m));
+}
+
+TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
+  Matcher<list<std::string>> m = ElementsAre(StrEq("one"), "two");
+  EXPECT_EQ(
+      "has 2 elements where\n"
+      "element #0 is equal to \"one\",\n"
+      "element #1 is equal to \"two\"",
+      Describe(m));
+}
+
+TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
+  Matcher<vector<int>> m = ElementsAre();
+  EXPECT_EQ("isn't empty", DescribeNegation(m));
+}
+
+TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElement) {
+  Matcher<const list<int>&> m = ElementsAre(Gt(5));
+  EXPECT_EQ(
+      "doesn't have 1 element, or\n"
+      "element #0 isn't > 5",
+      DescribeNegation(m));
+}
+
+TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
+  Matcher<const list<std::string>&> m = ElementsAre("one", "two");
+  EXPECT_EQ(
+      "doesn't have 2 elements, or\n"
+      "element #0 isn't equal to \"one\", or\n"
+      "element #1 isn't equal to \"two\"",
+      DescribeNegation(m));
+}
+
+TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
+  Matcher<const list<int>&> m = ElementsAre(1, Ne(2));
+
+  list<int> test_list;
+  test_list.push_back(1);
+  test_list.push_back(3);
+  EXPECT_EQ("", Explain(m, test_list));  // No need to explain anything.
+}
+
+TEST_P(ElementsAreTestP, ExplainsNonTrivialMatch) {
+  Matcher<const vector<int>&> m =
+      ElementsAre(GreaterThan(1), 0, GreaterThan(2));
+
+  const int a[] = {10, 0, 100};
+  vector<int> test_vector(std::begin(a), std::end(a));
+  EXPECT_EQ(
+      "whose element #0 matches, which is 9 more than 1,\n"
+      "and whose element #2 matches, which is 98 more than 2",
+      Explain(m, test_vector));
+}
+
+TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
+  Matcher<const list<int>&> m = ElementsAre(1, 3);
+
+  list<int> test_list;
+  // No need to explain when the container is empty.
+  EXPECT_EQ("", Explain(m, test_list));
+
+  test_list.push_back(1);
+  EXPECT_EQ("which has 1 element", Explain(m, test_list));
+}
+
+TEST_P(ElementsAreTestP, CanExplainMismatchRightSize) {
+  Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5));
+
+  vector<int> v;
+  v.push_back(2);
+  v.push_back(1);
+  EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
+
+  v[0] = 1;
+  EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
+            Explain(m, v));
+}
+
+TEST(ElementsAreTest, MatchesOneElementVector) {
+  vector<std::string> test_vector;
+  test_vector.push_back("test string");
+
+  EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
+}
+
+TEST(ElementsAreTest, MatchesOneElementList) {
+  list<std::string> test_list;
+  test_list.push_back("test string");
+
+  EXPECT_THAT(test_list, ElementsAre("test string"));
+}
+
+TEST(ElementsAreTest, MatchesThreeElementVector) {
+  vector<std::string> test_vector;
+  test_vector.push_back("one");
+  test_vector.push_back("two");
+  test_vector.push_back("three");
+
+  EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
+}
+
+TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
+  vector<int> test_vector;
+  test_vector.push_back(4);
+
+  EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
+}
+
+TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
+  vector<int> test_vector;
+  test_vector.push_back(4);
+
+  EXPECT_THAT(test_vector, ElementsAre(_));
+}
+
+TEST(ElementsAreTest, MatchesOneElementValue) {
+  vector<int> test_vector;
+  test_vector.push_back(4);
+
+  EXPECT_THAT(test_vector, ElementsAre(4));
+}
+
+TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
+  vector<int> test_vector;
+  test_vector.push_back(1);
+  test_vector.push_back(2);
+  test_vector.push_back(3);
+
+  EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
+}
+
+TEST(ElementsAreTest, MatchesTenElementVector) {
+  const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
+  vector<int> test_vector(std::begin(a), std::end(a));
+
+  EXPECT_THAT(test_vector,
+              // The element list can contain values and/or matchers
+              // of different types.
+              ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
+}
+
+TEST(ElementsAreTest, DoesNotMatchWrongSize) {
+  vector<std::string> test_vector;
+  test_vector.push_back("test string");
+  test_vector.push_back("test string");
+
+  Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
+  EXPECT_FALSE(m.Matches(test_vector));
+}
+
+TEST(ElementsAreTest, DoesNotMatchWrongValue) {
+  vector<std::string> test_vector;
+  test_vector.push_back("other string");
+
+  Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
+  EXPECT_FALSE(m.Matches(test_vector));
+}
+
+TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
+  vector<std::string> test_vector;
+  test_vector.push_back("one");
+  test_vector.push_back("three");
+  test_vector.push_back("two");
+
+  Matcher<vector<std::string>> m =
+      ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
+  EXPECT_FALSE(m.Matches(test_vector));
+}
+
+TEST(ElementsAreTest, WorksForNestedContainer) {
+  constexpr std::array<const char*, 2> strings = {{"Hi", "world"}};
+
+  vector<list<char>> nested;
+  for (const auto& s : strings) {
+    nested.emplace_back(s, s + strlen(s));
+  }
+
+  EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
+                                  ElementsAre('w', 'o', _, _, 'd')));
+  EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
+                                      ElementsAre('w', 'o', _, _, 'd'))));
+}
+
+TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
+  int a[] = {0, 1, 2};
+  vector<int> v(std::begin(a), std::end(a));
+
+  EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
+  EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
+}
+
+TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
+  int a[] = {0, 1, 2};
+  vector<int> v(std::begin(a), std::end(a));
+
+  EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
+  EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
+}
+
+TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
+  int array[] = {0, 1, 2};
+  EXPECT_THAT(array, ElementsAre(0, 1, _));
+  EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
+  EXPECT_THAT(array, Not(ElementsAre(0, _)));
+}
+
+class NativeArrayPassedAsPointerAndSize {
+ public:
+  NativeArrayPassedAsPointerAndSize() {}
+
+  MOCK_METHOD(void, Helper, (int* array, int size));
+
+ private:
+  NativeArrayPassedAsPointerAndSize(const NativeArrayPassedAsPointerAndSize&) =
+      delete;
+  NativeArrayPassedAsPointerAndSize& operator=(
+      const NativeArrayPassedAsPointerAndSize&) = delete;
+};
+
+TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
+  int array[] = {0, 1};
+  ::std::tuple<int*, size_t> array_as_tuple(array, 2);
+  EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
+  EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
+
+  NativeArrayPassedAsPointerAndSize helper;
+  EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));
+  helper.Helper(array, 2);
+}
+
+TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
+  const char a2[][3] = {"hi", "lo"};
+  EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
+                              ElementsAre('l', 'o', '\0')));
+  EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
+  EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
+                              ElementsAre('l', 'o', '\0')));
+}
+
+TEST(ElementsAreTest, AcceptsStringLiteral) {
+  std::string array[] = {"hi", "one", "two"};
+  EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
+  EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
+}
+
+// Declared here with the size unknown.  Defined AFTER the following test.
+extern const char kHi[];
+
+TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
+  // The size of kHi is not known in this test, but ElementsAre() should
+  // still accept it.
+
+  std::string array1[] = {"hi"};
+  EXPECT_THAT(array1, ElementsAre(kHi));
+
+  std::string array2[] = {"ho"};
+  EXPECT_THAT(array2, Not(ElementsAre(kHi)));
+}
+
+const char kHi[] = "hi";
+
+TEST(ElementsAreTest, MakesCopyOfArguments) {
+  int x = 1;
+  int y = 2;
+  // This should make a copy of x and y.
+  ::testing::internal::ElementsAreMatcher<std::tuple<int, int>>
+      polymorphic_matcher = ElementsAre(x, y);
+  // Changing x and y now shouldn't affect the meaning of the above matcher.
+  x = y = 0;
+  const int array1[] = {1, 2};
+  EXPECT_THAT(array1, polymorphic_matcher);
+  const int array2[] = {0, 0};
+  EXPECT_THAT(array2, Not(polymorphic_matcher));
+}
+
+// Tests for ElementsAreArray().  Since ElementsAreArray() shares most
+// of the implementation with ElementsAre(), we don't test it as
+// thoroughly here.
+
+TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
+  const int a[] = {1, 2, 3};
+
+  vector<int> test_vector(std::begin(a), std::end(a));
+  EXPECT_THAT(test_vector, ElementsAreArray(a));
+
+  test_vector[2] = 0;
+  EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
+}
+
+TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
+  std::array<const char*, 3> a = {{"one", "two", "three"}};
+
+  vector<std::string> test_vector(std::begin(a), std::end(a));
+  EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));
+
+  const char** p = a.data();
+  test_vector[0] = "1";
+  EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));
+}
+
+TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
+  const char* a[] = {"one", "two", "three"};
+
+  vector<std::string> test_vector(std::begin(a), std::end(a));
+  EXPECT_THAT(test_vector, ElementsAreArray(a));
+
+  test_vector[0] = "1";
+  EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
+}
+
+TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
+  const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
+                                                StrEq("three")};
+
+  vector<std::string> test_vector;
+  test_vector.push_back("one");
+  test_vector.push_back("two");
+  test_vector.push_back("three");
+  EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
+
+  test_vector.push_back("three");
+  EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
+}
+
+TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
+  const int a[] = {1, 2, 3};
+  vector<int> test_vector(std::begin(a), std::end(a));
+  const vector<int> expected(std::begin(a), std::end(a));
+  EXPECT_THAT(test_vector, ElementsAreArray(expected));
+  test_vector.push_back(4);
+  EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
+}
+
+TEST(ElementsAreArrayTest, TakesInitializerList) {
+  const int a[5] = {1, 2, 3, 4, 5};
+  EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5}));
+  EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4})));
+  EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6})));
+}
+
+TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
+  const std::string a[5] = {"a", "b", "c", "d", "e"};
+  EXPECT_THAT(a, ElementsAreArray({"a", "b", "c", "d", "e"}));
+  EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "e", "d"})));
+  EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "d", "ef"})));
+}
+
+TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
+  const int a[5] = {1, 2, 3, 4, 5};
+  EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
+  EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
+}
+
+TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {
+  const int a[5] = {1, 2, 3, 4, 5};
+  // The compiler cannot infer the type of the initializer list if its
+  // elements have different types.  We must explicitly specify the
+  // unified element type in this case.
+  EXPECT_THAT(
+      a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
+  EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>(
+                     {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
+}
+
+TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
+  const int a[] = {1, 2, 3};
+  const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)};
+  vector<int> test_vector(std::begin(a), std::end(a));
+  const vector<Matcher<int>> expected(std::begin(kMatchers),
+                                      std::end(kMatchers));
+  EXPECT_THAT(test_vector, ElementsAreArray(expected));
+  test_vector.push_back(4);
+  EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
+}
+
+TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
+  const int a[] = {1, 2, 3};
+  const vector<int> test_vector(std::begin(a), std::end(a));
+  const vector<int> expected(std::begin(a), std::end(a));
+  EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
+  // Pointers are iterators, too.
+  EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));
+  // The empty range of NULL pointers should also be okay.
+  int* const null_int = nullptr;
+  EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
+  EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
+}
+
+// Since ElementsAre() and ElementsAreArray() share much of the
+// implementation, we only do a test for native arrays here.
+TEST(ElementsAreArrayTest, WorksWithNativeArray) {
+  ::std::string a[] = {"hi", "ho"};
+  ::std::string b[] = {"hi", "ho"};
+
+  EXPECT_THAT(a, ElementsAreArray(b));
+  EXPECT_THAT(a, ElementsAreArray(b, 2));
+  EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
+}
+
+TEST(ElementsAreArrayTest, SourceLifeSpan) {
+  const int a[] = {1, 2, 3};
+  vector<int> test_vector(std::begin(a), std::end(a));
+  vector<int> expect(std::begin(a), std::end(a));
+  ElementsAreArrayMatcher<int> matcher_maker =
+      ElementsAreArray(expect.begin(), expect.end());
+  EXPECT_THAT(test_vector, matcher_maker);
+  // Changing in place the values that initialized matcher_maker should not
+  // affect matcher_maker anymore. It should have made its own copy of them.
+  for (int& i : expect) {
+    i += 10;
+  }
+  EXPECT_THAT(test_vector, matcher_maker);
+  test_vector.push_back(3);
+  EXPECT_THAT(test_vector, Not(matcher_maker));
+}
+
+// Tests Contains().
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(ContainsTest);
+
+TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
+  list<int> some_list;
+  some_list.push_back(3);
+  some_list.push_back(1);
+  some_list.push_back(2);
+  some_list.push_back(3);
+  EXPECT_THAT(some_list, Contains(1));
+  EXPECT_THAT(some_list, Contains(Gt(2.5)));
+  EXPECT_THAT(some_list, Contains(Eq(2.0f)));
+
+  list<std::string> another_list;
+  another_list.push_back("fee");
+  another_list.push_back("fie");
+  another_list.push_back("foe");
+  another_list.push_back("fum");
+  EXPECT_THAT(another_list, Contains(std::string("fee")));
+}
+
+TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
+  list<int> some_list;
+  some_list.push_back(3);
+  some_list.push_back(1);
+  EXPECT_THAT(some_list, Not(Contains(4)));
+}
+
+TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
+  set<int> some_set;
+  some_set.insert(3);
+  some_set.insert(1);
+  some_set.insert(2);
+  EXPECT_THAT(some_set, Contains(Eq(1.0)));
+  EXPECT_THAT(some_set, Contains(Eq(3.0f)));
+  EXPECT_THAT(some_set, Contains(2));
+
+  set<std::string> another_set;
+  another_set.insert("fee");
+  another_set.insert("fie");
+  another_set.insert("foe");
+  another_set.insert("fum");
+  EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
+}
+
+TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
+  set<int> some_set;
+  some_set.insert(3);
+  some_set.insert(1);
+  EXPECT_THAT(some_set, Not(Contains(4)));
+
+  set<std::string> c_string_set;
+  c_string_set.insert("hello");
+  EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye"))));
+}
+
+TEST_P(ContainsTestP, ExplainsMatchResultCorrectly) {
+  const int a[2] = {1, 2};
+  Matcher<const int(&)[2]> m = Contains(2);
+  EXPECT_EQ("whose element #1 matches", Explain(m, a));
+
+  m = Contains(3);
+  EXPECT_EQ("", Explain(m, a));
+
+  m = Contains(GreaterThan(0));
+  EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
+
+  m = Contains(GreaterThan(10));
+  EXPECT_EQ("", Explain(m, a));
+}
+
+TEST(ContainsTest, DescribesItselfCorrectly) {
+  Matcher<vector<int>> m = Contains(1);
+  EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
+
+  Matcher<vector<int>> m2 = Not(m);
+  EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
+}
+
+TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
+  map<std::string, int> my_map;
+  const char* bar = "a string";
+  my_map[bar] = 2;
+  EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
+
+  map<std::string, int> another_map;
+  another_map["fee"] = 1;
+  another_map["fie"] = 2;
+  another_map["foe"] = 3;
+  another_map["fum"] = 4;
+  EXPECT_THAT(another_map,
+              Contains(pair<const std::string, int>(std::string("fee"), 1)));
+  EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
+}
+
+TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
+  map<int, int> some_map;
+  some_map[1] = 11;
+  some_map[2] = 22;
+  EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
+}
+
+TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
+  const char* string_array[] = {"fee", "fie", "foe", "fum"};
+  EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
+}
+
+TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
+  int int_array[] = {1, 2, 3, 4};
+  EXPECT_THAT(int_array, Not(Contains(5)));
+}
+
+TEST(ContainsTest, AcceptsMatcher) {
+  const int a[] = {1, 2, 3};
+  EXPECT_THAT(a, Contains(Gt(2)));
+  EXPECT_THAT(a, Not(Contains(Gt(4))));
+}
+
+TEST(ContainsTest, WorksForNativeArrayAsTuple) {
+  const int a[] = {1, 2};
+  const int* const pointer = a;
+  EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));
+  EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));
+}
+
+TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
+  int a[][3] = {{1, 2, 3}, {4, 5, 6}};
+  EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
+  EXPECT_THAT(a, Contains(Contains(5)));
+  EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
+  EXPECT_THAT(a, Contains(Not(Contains(5))));
+}
+
+}  // namespace
+}  // namespace gmock_matchers_test
+}  // namespace testing
+
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
diff --git a/googlemock/test/gmock-matchers-misc_test.cc b/googlemock/test/gmock-matchers-misc_test.cc
new file mode 100644 (file)
index 0000000..c68431c
--- /dev/null
@@ -0,0 +1,1805 @@
+// Copyright 2007, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Google Mock - a framework for writing C++ mock classes.
+//
+// This file tests some commonly used argument matchers.
+
+// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
+// possible loss of data and C4100, unreferenced local parameter
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4244)
+#pragma warning(disable : 4100)
+#endif
+
+#include "test/gmock-matchers_test.h"
+
+namespace testing {
+namespace gmock_matchers_test {
+namespace {
+
+TEST(AddressTest, NonConst) {
+  int n = 1;
+  const Matcher<int> m = Address(Eq(&n));
+
+  EXPECT_TRUE(m.Matches(n));
+
+  int other = 5;
+
+  EXPECT_FALSE(m.Matches(other));
+
+  int& n_ref = n;
+
+  EXPECT_TRUE(m.Matches(n_ref));
+}
+
+TEST(AddressTest, Const) {
+  const int n = 1;
+  const Matcher<int> m = Address(Eq(&n));
+
+  EXPECT_TRUE(m.Matches(n));
+
+  int other = 5;
+
+  EXPECT_FALSE(m.Matches(other));
+}
+
+TEST(AddressTest, MatcherDoesntCopy) {
+  std::unique_ptr<int> n(new int(1));
+  const Matcher<std::unique_ptr<int>> m = Address(Eq(&n));
+
+  EXPECT_TRUE(m.Matches(n));
+}
+
+TEST(AddressTest, Describe) {
+  Matcher<int> matcher = Address(_);
+  EXPECT_EQ("has address that is anything", Describe(matcher));
+  EXPECT_EQ("does not have address that is anything",
+            DescribeNegation(matcher));
+}
+
+// The following two tests verify that values without a public copy
+// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
+// with the help of ByRef().
+
+class NotCopyable {
+ public:
+  explicit NotCopyable(int a_value) : value_(a_value) {}
+
+  int value() const { return value_; }
+
+  bool operator==(const NotCopyable& rhs) const {
+    return value() == rhs.value();
+  }
+
+  bool operator>=(const NotCopyable& rhs) const {
+    return value() >= rhs.value();
+  }
+
+ private:
+  int value_;
+
+  NotCopyable(const NotCopyable&) = delete;
+  NotCopyable& operator=(const NotCopyable&) = delete;
+};
+
+TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
+  const NotCopyable const_value1(1);
+  const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
+
+  const NotCopyable n1(1), n2(2);
+  EXPECT_TRUE(m.Matches(n1));
+  EXPECT_FALSE(m.Matches(n2));
+}
+
+TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
+  NotCopyable value2(2);
+  const Matcher<NotCopyable&> m = Ge(ByRef(value2));
+
+  NotCopyable n1(1), n2(2);
+  EXPECT_FALSE(m.Matches(n1));
+  EXPECT_TRUE(m.Matches(n2));
+}
+
+TEST(IsEmptyTest, ImplementsIsEmpty) {
+  vector<int> container;
+  EXPECT_THAT(container, IsEmpty());
+  container.push_back(0);
+  EXPECT_THAT(container, Not(IsEmpty()));
+  container.push_back(1);
+  EXPECT_THAT(container, Not(IsEmpty()));
+}
+
+TEST(IsEmptyTest, WorksWithString) {
+  std::string text;
+  EXPECT_THAT(text, IsEmpty());
+  text = "foo";
+  EXPECT_THAT(text, Not(IsEmpty()));
+  text = std::string("\0", 1);
+  EXPECT_THAT(text, Not(IsEmpty()));
+}
+
+TEST(IsEmptyTest, CanDescribeSelf) {
+  Matcher<vector<int>> m = IsEmpty();
+  EXPECT_EQ("is empty", Describe(m));
+  EXPECT_EQ("isn't empty", DescribeNegation(m));
+}
+
+TEST(IsEmptyTest, ExplainsResult) {
+  Matcher<vector<int>> m = IsEmpty();
+  vector<int> container;
+  EXPECT_EQ("", Explain(m, container));
+  container.push_back(0);
+  EXPECT_EQ("whose size is 1", Explain(m, container));
+}
+
+TEST(IsEmptyTest, WorksWithMoveOnly) {
+  ContainerHelper helper;
+  EXPECT_CALL(helper, Call(IsEmpty()));
+  helper.Call({});
+}
+
+TEST(IsTrueTest, IsTrueIsFalse) {
+  EXPECT_THAT(true, IsTrue());
+  EXPECT_THAT(false, IsFalse());
+  EXPECT_THAT(true, Not(IsFalse()));
+  EXPECT_THAT(false, Not(IsTrue()));
+  EXPECT_THAT(0, Not(IsTrue()));
+  EXPECT_THAT(0, IsFalse());
+  EXPECT_THAT(nullptr, Not(IsTrue()));
+  EXPECT_THAT(nullptr, IsFalse());
+  EXPECT_THAT(-1, IsTrue());
+  EXPECT_THAT(-1, Not(IsFalse()));
+  EXPECT_THAT(1, IsTrue());
+  EXPECT_THAT(1, Not(IsFalse()));
+  EXPECT_THAT(2, IsTrue());
+  EXPECT_THAT(2, Not(IsFalse()));
+  int a = 42;
+  EXPECT_THAT(a, IsTrue());
+  EXPECT_THAT(a, Not(IsFalse()));
+  EXPECT_THAT(&a, IsTrue());
+  EXPECT_THAT(&a, Not(IsFalse()));
+  EXPECT_THAT(false, Not(IsTrue()));
+  EXPECT_THAT(true, Not(IsFalse()));
+  EXPECT_THAT(std::true_type(), IsTrue());
+  EXPECT_THAT(std::true_type(), Not(IsFalse()));
+  EXPECT_THAT(std::false_type(), IsFalse());
+  EXPECT_THAT(std::false_type(), Not(IsTrue()));
+  EXPECT_THAT(nullptr, Not(IsTrue()));
+  EXPECT_THAT(nullptr, IsFalse());
+  std::unique_ptr<int> null_unique;
+  std::unique_ptr<int> nonnull_unique(new int(0));
+  EXPECT_THAT(null_unique, Not(IsTrue()));
+  EXPECT_THAT(null_unique, IsFalse());
+  EXPECT_THAT(nonnull_unique, IsTrue());
+  EXPECT_THAT(nonnull_unique, Not(IsFalse()));
+}
+
+#if GTEST_HAS_TYPED_TEST
+// Tests ContainerEq with different container types, and
+// different element types.
+
+template <typename T>
+class ContainerEqTest : public testing::Test {};
+
+typedef testing::Types<set<int>, vector<size_t>, multiset<size_t>, list<int>>
+    ContainerEqTestTypes;
+
+TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes);
+
+// Tests that the filled container is equal to itself.
+TYPED_TEST(ContainerEqTest, EqualsSelf) {
+  static const int vals[] = {1, 1, 2, 3, 5, 8};
+  TypeParam my_set(vals, vals + 6);
+  const Matcher<TypeParam> m = ContainerEq(my_set);
+  EXPECT_TRUE(m.Matches(my_set));
+  EXPECT_EQ("", Explain(m, my_set));
+}
+
+// Tests that missing values are reported.
+TYPED_TEST(ContainerEqTest, ValueMissing) {
+  static const int vals[] = {1, 1, 2, 3, 5, 8};
+  static const int test_vals[] = {2, 1, 8, 5};
+  TypeParam my_set(vals, vals + 6);
+  TypeParam test_set(test_vals, test_vals + 4);
+  const Matcher<TypeParam> m = ContainerEq(my_set);
+  EXPECT_FALSE(m.Matches(test_set));
+  EXPECT_EQ("which doesn't have these expected elements: 3",
+            Explain(m, test_set));
+}
+
+// Tests that added values are reported.
+TYPED_TEST(ContainerEqTest, ValueAdded) {
+  static const int vals[] = {1, 1, 2, 3, 5, 8};
+  static const int test_vals[] = {1, 2, 3, 5, 8, 46};
+  TypeParam my_set(vals, vals + 6);
+  TypeParam test_set(test_vals, test_vals + 6);
+  const Matcher<const TypeParam&> m = ContainerEq(my_set);
+  EXPECT_FALSE(m.Matches(test_set));
+  EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
+}
+
+// Tests that added and missing values are reported together.
+TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
+  static const int vals[] = {1, 1, 2, 3, 5, 8};
+  static const int test_vals[] = {1, 2, 3, 8, 46};
+  TypeParam my_set(vals, vals + 6);
+  TypeParam test_set(test_vals, test_vals + 5);
+  const Matcher<TypeParam> m = ContainerEq(my_set);
+  EXPECT_FALSE(m.Matches(test_set));
+  EXPECT_EQ(
+      "which has these unexpected elements: 46,\n"
+      "and doesn't have these expected elements: 5",
+      Explain(m, test_set));
+}
+
+// Tests duplicated value -- expect no explanation.
+TYPED_TEST(ContainerEqTest, DuplicateDifference) {
+  static const int vals[] = {1, 1, 2, 3, 5, 8};
+  static const int test_vals[] = {1, 2, 3, 5, 8};
+  TypeParam my_set(vals, vals + 6);
+  TypeParam test_set(test_vals, test_vals + 5);
+  const Matcher<const TypeParam&> m = ContainerEq(my_set);
+  // Depending on the container, match may be true or false
+  // But in any case there should be no explanation.
+  EXPECT_EQ("", Explain(m, test_set));
+}
+#endif  // GTEST_HAS_TYPED_TEST
+
+// Tests that multiple missing values are reported.
+// Using just vector here, so order is predictable.
+TEST(ContainerEqExtraTest, MultipleValuesMissing) {
+  static const int vals[] = {1, 1, 2, 3, 5, 8};
+  static const int test_vals[] = {2, 1, 5};
+  vector<int> my_set(vals, vals + 6);
+  vector<int> test_set(test_vals, test_vals + 3);
+  const Matcher<vector<int>> m = ContainerEq(my_set);
+  EXPECT_FALSE(m.Matches(test_set));
+  EXPECT_EQ("which doesn't have these expected elements: 3, 8",
+            Explain(m, test_set));
+}
+
+// Tests that added values are reported.
+// Using just vector here, so order is predictable.
+TEST(ContainerEqExtraTest, MultipleValuesAdded) {
+  static const int vals[] = {1, 1, 2, 3, 5, 8};
+  static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
+  list<size_t> my_set(vals, vals + 6);
+  list<size_t> test_set(test_vals, test_vals + 7);
+  const Matcher<const list<size_t>&> m = ContainerEq(my_set);
+  EXPECT_FALSE(m.Matches(test_set));
+  EXPECT_EQ("which has these unexpected elements: 92, 46",
+            Explain(m, test_set));
+}
+
+// Tests that added and missing values are reported together.
+TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
+  static const int vals[] = {1, 1, 2, 3, 5, 8};
+  static const int test_vals[] = {1, 2, 3, 92, 46};
+  list<size_t> my_set(vals, vals + 6);
+  list<size_t> test_set(test_vals, test_vals + 5);
+  const Matcher<const list<size_t>> m = ContainerEq(my_set);
+  EXPECT_FALSE(m.Matches(test_set));
+  EXPECT_EQ(
+      "which has these unexpected elements: 92, 46,\n"
+      "and doesn't have these expected elements: 5, 8",
+      Explain(m, test_set));
+}
+
+// Tests to see that duplicate elements are detected,
+// but (as above) not reported in the explanation.
+TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
+  static const int vals[] = {1, 1, 2, 3, 5, 8};
+  static const int test_vals[] = {1, 2, 3, 5, 8};
+  vector<int> my_set(vals, vals + 6);
+  vector<int> test_set(test_vals, test_vals + 5);
+  const Matcher<vector<int>> m = ContainerEq(my_set);
+  EXPECT_TRUE(m.Matches(my_set));
+  EXPECT_FALSE(m.Matches(test_set));
+  // There is nothing to report when both sets contain all the same values.
+  EXPECT_EQ("", Explain(m, test_set));
+}
+
+// Tests that ContainerEq works for non-trivial associative containers,
+// like maps.
+TEST(ContainerEqExtraTest, WorksForMaps) {
+  map<int, std::string> my_map;
+  my_map[0] = "a";
+  my_map[1] = "b";
+
+  map<int, std::string> test_map;
+  test_map[0] = "aa";
+  test_map[1] = "b";
+
+  const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
+  EXPECT_TRUE(m.Matches(my_map));
+  EXPECT_FALSE(m.Matches(test_map));
+
+  EXPECT_EQ(
+      "which has these unexpected elements: (0, \"aa\"),\n"
+      "and doesn't have these expected elements: (0, \"a\")",
+      Explain(m, test_map));
+}
+
+TEST(ContainerEqExtraTest, WorksForNativeArray) {
+  int a1[] = {1, 2, 3};
+  int a2[] = {1, 2, 3};
+  int b[] = {1, 2, 4};
+
+  EXPECT_THAT(a1, ContainerEq(a2));
+  EXPECT_THAT(a1, Not(ContainerEq(b)));
+}
+
+TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
+  const char a1[][3] = {"hi", "lo"};
+  const char a2[][3] = {"hi", "lo"};
+  const char b[][3] = {"lo", "hi"};
+
+  // Tests using ContainerEq() in the first dimension.
+  EXPECT_THAT(a1, ContainerEq(a2));
+  EXPECT_THAT(a1, Not(ContainerEq(b)));
+
+  // Tests using ContainerEq() in the second dimension.
+  EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
+  EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
+}
+
+TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
+  const int a1[] = {1, 2, 3};
+  const int a2[] = {1, 2, 3};
+  const int b[] = {1, 2, 3, 4};
+
+  const int* const p1 = a1;
+  EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2));
+  EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b)));
+
+  const int c[] = {1, 3, 2};
+  EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c)));
+}
+
+TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
+  std::string a1[][3] = {{"hi", "hello", "ciao"}, {"bye", "see you", "ciao"}};
+
+  std::string a2[][3] = {{"hi", "hello", "ciao"}, {"bye", "see you", "ciao"}};
+
+  const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
+  EXPECT_THAT(a1, m);
+
+  a2[0][0] = "ha";
+  EXPECT_THAT(a1, m);
+}
+
+namespace {
+
+// Used as a check on the more complex max flow method used in the
+// real testing::internal::FindMaxBipartiteMatching. This method is
+// compatible but runs in worst-case factorial time, so we only
+// use it in testing for small problem sizes.
+template <typename Graph>
+class BacktrackingMaxBPMState {
+ public:
+  // Does not take ownership of 'g'.
+  explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) {}
+
+  ElementMatcherPairs Compute() {
+    if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
+      return best_so_far_;
+    }
+    lhs_used_.assign(graph_->LhsSize(), kUnused);
+    rhs_used_.assign(graph_->RhsSize(), kUnused);
+    for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
+      matches_.clear();
+      RecurseInto(irhs);
+      if (best_so_far_.size() == graph_->RhsSize()) break;
+    }
+    return best_so_far_;
+  }
+
+ private:
+  static const size_t kUnused = static_cast<size_t>(-1);
+
+  void PushMatch(size_t lhs, size_t rhs) {
+    matches_.push_back(ElementMatcherPair(lhs, rhs));
+    lhs_used_[lhs] = rhs;
+    rhs_used_[rhs] = lhs;
+    if (matches_.size() > best_so_far_.size()) {
+      best_so_far_ = matches_;
+    }
+  }
+
+  void PopMatch() {
+    const ElementMatcherPair& back = matches_.back();
+    lhs_used_[back.first] = kUnused;
+    rhs_used_[back.second] = kUnused;
+    matches_.pop_back();
+  }
+
+  bool RecurseInto(size_t irhs) {
+    if (rhs_used_[irhs] != kUnused) {
+      return true;
+    }
+    for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
+      if (lhs_used_[ilhs] != kUnused) {
+        continue;
+      }
+      if (!graph_->HasEdge(ilhs, irhs)) {
+        continue;
+      }
+      PushMatch(ilhs, irhs);
+      if (best_so_far_.size() == graph_->RhsSize()) {
+        return false;
+      }
+      for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
+        if (!RecurseInto(mi)) return false;
+      }
+      PopMatch();
+    }
+    return true;
+  }
+
+  const Graph* graph_;  // not owned
+  std::vector<size_t> lhs_used_;
+  std::vector<size_t> rhs_used_;
+  ElementMatcherPairs matches_;
+  ElementMatcherPairs best_so_far_;
+};
+
+template <typename Graph>
+const size_t BacktrackingMaxBPMState<Graph>::kUnused;
+
+}  // namespace
+
+// Implement a simple backtracking algorithm to determine if it is possible
+// to find one element per matcher, without reusing elements.
+template <typename Graph>
+ElementMatcherPairs FindBacktrackingMaxBPM(const Graph& g) {
+  return BacktrackingMaxBPMState<Graph>(&g).Compute();
+}
+
+class BacktrackingBPMTest : public ::testing::Test {};
+
+// Tests the MaxBipartiteMatching algorithm with square matrices.
+// The single int param is the # of nodes on each of the left and right sides.
+class BipartiteTest : public ::testing::TestWithParam<size_t> {};
+
+// Verify all match graphs up to some moderate number of edges.
+TEST_P(BipartiteTest, Exhaustive) {
+  size_t nodes = GetParam();
+  MatchMatrix graph(nodes, nodes);
+  do {
+    ElementMatcherPairs matches = internal::FindMaxBipartiteMatching(graph);
+    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
+        << "graph: " << graph.DebugString();
+    // Check that all elements of matches are in the graph.
+    // Check that elements of first and second are unique.
+    std::vector<bool> seen_element(graph.LhsSize());
+    std::vector<bool> seen_matcher(graph.RhsSize());
+    SCOPED_TRACE(PrintToString(matches));
+    for (size_t i = 0; i < matches.size(); ++i) {
+      size_t ilhs = matches[i].first;
+      size_t irhs = matches[i].second;
+      EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
+      EXPECT_FALSE(seen_element[ilhs]);
+      EXPECT_FALSE(seen_matcher[irhs]);
+      seen_element[ilhs] = true;
+      seen_matcher[irhs] = true;
+    }
+  } while (graph.NextGraph());
+}
+
+INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest,
+                         ::testing::Range(size_t{0}, size_t{5}));
+
+// Parameterized by a pair interpreted as (LhsSize, RhsSize).
+class BipartiteNonSquareTest
+    : public ::testing::TestWithParam<std::pair<size_t, size_t>> {};
+
+TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
+  //   .......
+  // 0:-----\ :
+  // 1:---\ | :
+  // 2:---\ | :
+  // 3:-\ | | :
+  //  :.......:
+  //    0 1 2
+  MatchMatrix g(4, 3);
+  constexpr std::array<std::array<size_t, 2>, 4> kEdges = {
+      {{{0, 2}}, {{1, 1}}, {{2, 1}}, {{3, 0}}}};
+  for (size_t i = 0; i < kEdges.size(); ++i) {
+    g.SetEdge(kEdges[i][0], kEdges[i][1], true);
+  }
+  EXPECT_THAT(FindBacktrackingMaxBPM(g),
+              ElementsAre(Pair(3, 0), Pair(AnyOf(1, 2), 1), Pair(0, 2)))
+      << g.DebugString();
+}
+
+// Verify a few nonsquare matrices.
+TEST_P(BipartiteNonSquareTest, Exhaustive) {
+  size_t nlhs = GetParam().first;
+  size_t nrhs = GetParam().second;
+  MatchMatrix graph(nlhs, nrhs);
+  do {
+    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
+              internal::FindMaxBipartiteMatching(graph).size())
+        << "graph: " << graph.DebugString()
+        << "\nbacktracking: " << PrintToString(FindBacktrackingMaxBPM(graph))
+        << "\nmax flow: "
+        << PrintToString(internal::FindMaxBipartiteMatching(graph));
+  } while (graph.NextGraph());
+}
+
+INSTANTIATE_TEST_SUITE_P(
+    AllGraphs, BipartiteNonSquareTest,
+    testing::Values(std::make_pair(1, 2), std::make_pair(2, 1),
+                    std::make_pair(3, 2), std::make_pair(2, 3),
+                    std::make_pair(4, 1), std::make_pair(1, 4),
+                    std::make_pair(4, 3), std::make_pair(3, 4)));
+
+class BipartiteRandomTest
+    : public ::testing::TestWithParam<std::pair<int, int>> {};
+
+// Verifies a large sample of larger graphs.
+TEST_P(BipartiteRandomTest, LargerNets) {
+  int nodes = GetParam().first;
+  int iters = GetParam().second;
+  MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes));
+
+  auto seed = static_cast<uint32_t>(GTEST_FLAG_GET(random_seed));
+  if (seed == 0) {
+    seed = static_cast<uint32_t>(time(nullptr));
+  }
+
+  for (; iters > 0; --iters, ++seed) {
+    srand(static_cast<unsigned int>(seed));
+    graph.Randomize();
+    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
+              internal::FindMaxBipartiteMatching(graph).size())
+        << " graph: " << graph.DebugString()
+        << "\nTo reproduce the failure, rerun the test with the flag"
+           " --"
+        << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
+  }
+}
+
+// Test argument is a std::pair<int, int> representing (nodes, iters).
+INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest,
+                         testing::Values(std::make_pair(5, 10000),
+                                         std::make_pair(6, 5000),
+                                         std::make_pair(7, 2000),
+                                         std::make_pair(8, 500),
+                                         std::make_pair(9, 100)));
+
+// Tests IsReadableTypeName().
+
+TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
+  EXPECT_TRUE(IsReadableTypeName("int"));
+  EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
+  EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
+  EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
+}
+
+TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
+  EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
+  EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
+  EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
+}
+
+TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
+  EXPECT_FALSE(
+      IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
+  EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
+}
+
+TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
+  EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
+}
+
+// Tests FormatMatcherDescription().
+
+TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
+  EXPECT_EQ("is even",
+            FormatMatcherDescription(false, "IsEven", {}, Strings()));
+  EXPECT_EQ("not (is even)",
+            FormatMatcherDescription(true, "IsEven", {}, Strings()));
+
+  EXPECT_EQ("equals (a: 5)",
+            FormatMatcherDescription(false, "Equals", {"a"}, {"5"}));
+
+  EXPECT_EQ(
+      "is in range (a: 5, b: 8)",
+      FormatMatcherDescription(false, "IsInRange", {"a", "b"}, {"5", "8"}));
+}
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(MatcherTupleTest);
+
+TEST_P(MatcherTupleTestP, ExplainsMatchFailure) {
+  stringstream ss1;
+  ExplainMatchFailureTupleTo(
+      std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
+      std::make_tuple('a', 10), &ss1);
+  EXPECT_EQ("", ss1.str());  // Successful match.
+
+  stringstream ss2;
+  ExplainMatchFailureTupleTo(
+      std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
+      std::make_tuple(2, 'b'), &ss2);
+  EXPECT_EQ(
+      "  Expected arg #0: is > 5\n"
+      "           Actual: 2, which is 3 less than 5\n"
+      "  Expected arg #1: is equal to 'a' (97, 0x61)\n"
+      "           Actual: 'b' (98, 0x62)\n",
+      ss2.str());  // Failed match where both arguments need explanation.
+
+  stringstream ss3;
+  ExplainMatchFailureTupleTo(
+      std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
+      std::make_tuple(2, 'a'), &ss3);
+  EXPECT_EQ(
+      "  Expected arg #0: is > 5\n"
+      "           Actual: 2, which is 3 less than 5\n",
+      ss3.str());  // Failed match where only one argument needs
+                   // explanation.
+}
+
+// Sample optional type implementation with minimal requirements for use with
+// Optional matcher.
+template <typename T>
+class SampleOptional {
+ public:
+  using value_type = T;
+  explicit SampleOptional(T value)
+      : value_(std::move(value)), has_value_(true) {}
+  SampleOptional() : value_(), has_value_(false) {}
+  operator bool() const { return has_value_; }
+  const T& operator*() const { return value_; }
+
+ private:
+  T value_;
+  bool has_value_;
+};
+
+TEST(OptionalTest, DescribesSelf) {
+  const Matcher<SampleOptional<int>> m = Optional(Eq(1));
+  EXPECT_EQ("value is equal to 1", Describe(m));
+}
+
+TEST(OptionalTest, ExplainsSelf) {
+  const Matcher<SampleOptional<int>> m = Optional(Eq(1));
+  EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional<int>(1)));
+  EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional<int>(2)));
+}
+
+TEST(OptionalTest, MatchesNonEmptyOptional) {
+  const Matcher<SampleOptional<int>> m1 = Optional(1);
+  const Matcher<SampleOptional<int>> m2 = Optional(Eq(2));
+  const Matcher<SampleOptional<int>> m3 = Optional(Lt(3));
+  SampleOptional<int> opt(1);
+  EXPECT_TRUE(m1.Matches(opt));
+  EXPECT_FALSE(m2.Matches(opt));
+  EXPECT_TRUE(m3.Matches(opt));
+}
+
+TEST(OptionalTest, DoesNotMatchNullopt) {
+  const Matcher<SampleOptional<int>> m = Optional(1);
+  SampleOptional<int> empty;
+  EXPECT_FALSE(m.Matches(empty));
+}
+
+TEST(OptionalTest, WorksWithMoveOnly) {
+  Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr));
+  EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr)));
+}
+
+class SampleVariantIntString {
+ public:
+  SampleVariantIntString(int i) : i_(i), has_int_(true) {}
+  SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}
+
+  template <typename T>
+  friend bool holds_alternative(const SampleVariantIntString& value) {
+    return value.has_int_ == std::is_same<T, int>::value;
+  }
+
+  template <typename T>
+  friend const T& get(const SampleVariantIntString& value) {
+    return value.get_impl(static_cast<T*>(nullptr));
+  }
+
+ private:
+  const int& get_impl(int*) const { return i_; }
+  const std::string& get_impl(std::string*) const { return s_; }
+
+  int i_;
+  std::string s_;
+  bool has_int_;
+};
+
+TEST(VariantTest, DescribesSelf) {
+  const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
+  EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "
+                                         "'.*' and the value is equal to 1"));
+}
+
+TEST(VariantTest, ExplainsSelf) {
+  const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
+  EXPECT_THAT(Explain(m, SampleVariantIntString(1)),
+              ContainsRegex("whose value 1"));
+  EXPECT_THAT(Explain(m, SampleVariantIntString("A")),
+              HasSubstr("whose value is not of type '"));
+  EXPECT_THAT(Explain(m, SampleVariantIntString(2)),
+              "whose value 2 doesn't match");
+}
+
+TEST(VariantTest, FullMatch) {
+  Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
+  EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));
+
+  m = VariantWith<std::string>(Eq("1"));
+  EXPECT_TRUE(m.Matches(SampleVariantIntString("1")));
+}
+
+TEST(VariantTest, TypeDoesNotMatch) {
+  Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
+  EXPECT_FALSE(m.Matches(SampleVariantIntString("1")));
+
+  m = VariantWith<std::string>(Eq("1"));
+  EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));
+}
+
+TEST(VariantTest, InnerDoesNotMatch) {
+  Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
+  EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));
+
+  m = VariantWith<std::string>(Eq("1"));
+  EXPECT_FALSE(m.Matches(SampleVariantIntString("2")));
+}
+
+class SampleAnyType {
+ public:
+  explicit SampleAnyType(int i) : index_(0), i_(i) {}
+  explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}
+
+  template <typename T>
+  friend const T* any_cast(const SampleAnyType* any) {
+    return any->get_impl(static_cast<T*>(nullptr));
+  }
+
+ private:
+  int index_;
+  int i_;
+  std::string s_;
+
+  const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; }
+  const std::string* get_impl(std::string*) const {
+    return index_ == 1 ? &s_ : nullptr;
+  }
+};
+
+TEST(AnyWithTest, FullMatch) {
+  Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));
+  EXPECT_TRUE(m.Matches(SampleAnyType(1)));
+}
+
+TEST(AnyWithTest, TestBadCastType) {
+  Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail"));
+  EXPECT_FALSE(m.Matches(SampleAnyType(1)));
+}
+
+TEST(AnyWithTest, TestUseInContainers) {
+  std::vector<SampleAnyType> a;
+  a.emplace_back(1);
+  a.emplace_back(2);
+  a.emplace_back(3);
+  EXPECT_THAT(
+      a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)}));
+
+  std::vector<SampleAnyType> b;
+  b.emplace_back("hello");
+  b.emplace_back("merhaba");
+  b.emplace_back("salut");
+  EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"),
+                                   AnyWith<std::string>("merhaba"),
+                                   AnyWith<std::string>("salut")}));
+}
+TEST(AnyWithTest, TestCompare) {
+  EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));
+}
+
+TEST(AnyWithTest, DescribesSelf) {
+  const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
+  EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type "
+                                         "'.*' and the value is equal to 1"));
+}
+
+TEST(AnyWithTest, ExplainsSelf) {
+  const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
+
+  EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1"));
+  EXPECT_THAT(Explain(m, SampleAnyType("A")),
+              HasSubstr("whose value is not of type '"));
+  EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match");
+}
+
+// Tests Args<k0, ..., kn>(m).
+
+TEST(ArgsTest, AcceptsZeroTemplateArg) {
+  const std::tuple<int, bool> t(5, true);
+  EXPECT_THAT(t, Args<>(Eq(std::tuple<>())));
+  EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>()))));
+}
+
+TEST(ArgsTest, AcceptsOneTemplateArg) {
+  const std::tuple<int, bool> t(5, true);
+  EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5))));
+  EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true))));
+  EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false)))));
+}
+
+TEST(ArgsTest, AcceptsTwoTemplateArgs) {
+  const std::tuple<short, int, long> t(4, 5, 6L);  // NOLINT
+
+  EXPECT_THAT(t, (Args<0, 1>(Lt())));
+  EXPECT_THAT(t, (Args<1, 2>(Lt())));
+  EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
+}
+
+TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
+  const std::tuple<short, int, long> t(4, 5, 6L);  // NOLINT
+  EXPECT_THAT(t, (Args<0, 0>(Eq())));
+  EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
+}
+
+TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
+  const std::tuple<short, int, long> t(4, 5, 6L);  // NOLINT
+  EXPECT_THAT(t, (Args<2, 0>(Gt())));
+  EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
+}
+
+MATCHER(SumIsZero, "") {
+  return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0;
+}
+
+TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
+  EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));
+  EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));
+}
+
+TEST(ArgsTest, CanBeNested) {
+  const std::tuple<short, int, long, int> t(4, 5, 6L, 6);  // NOLINT
+  EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
+  EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
+}
+
+TEST(ArgsTest, CanMatchTupleByValue) {
+  typedef std::tuple<char, int, int> Tuple3;
+  const Matcher<Tuple3> m = Args<1, 2>(Lt());
+  EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));
+  EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));
+}
+
+TEST(ArgsTest, CanMatchTupleByReference) {
+  typedef std::tuple<char, char, int> Tuple3;
+  const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
+  EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));
+  EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));
+}
+
+// Validates that arg is printed as str.
+MATCHER_P(PrintsAs, str, "") { return testing::PrintToString(arg) == str; }
+
+TEST(ArgsTest, AcceptsTenTemplateArgs) {
+  EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
+              (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
+                  PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
+  EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
+              Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
+                  PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
+}
+
+TEST(ArgsTest, DescirbesSelfCorrectly) {
+  const Matcher<std::tuple<int, bool, char>> m = Args<2, 0>(Lt());
+  EXPECT_EQ(
+      "are a tuple whose fields (#2, #0) are a pair where "
+      "the first < the second",
+      Describe(m));
+}
+
+TEST(ArgsTest, DescirbesNestedArgsCorrectly) {
+  const Matcher<const std::tuple<int, bool, char, int>&> m =
+      Args<0, 2, 3>(Args<2, 0>(Lt()));
+  EXPECT_EQ(
+      "are a tuple whose fields (#0, #2, #3) are a tuple "
+      "whose fields (#2, #0) are a pair where the first < the second",
+      Describe(m));
+}
+
+TEST(ArgsTest, DescribesNegationCorrectly) {
+  const Matcher<std::tuple<int, char>> m = Args<1, 0>(Gt());
+  EXPECT_EQ(
+      "are a tuple whose fields (#1, #0) aren't a pair "
+      "where the first > the second",
+      DescribeNegation(m));
+}
+
+TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {
+  const Matcher<std::tuple<bool, int, int>> m = Args<1, 2>(Eq());
+  EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
+            Explain(m, std::make_tuple(false, 42, 42)));
+  EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
+            Explain(m, std::make_tuple(false, 42, 43)));
+}
+
+// For testing Args<>'s explanation.
+class LessThanMatcher : public MatcherInterface<std::tuple<char, int>> {
+ public:
+  void DescribeTo(::std::ostream* /*os*/) const override {}
+
+  bool MatchAndExplain(std::tuple<char, int> value,
+                       MatchResultListener* listener) const override {
+    const int diff = std::get<0>(value) - std::get<1>(value);
+    if (diff > 0) {
+      *listener << "where the first value is " << diff
+                << " more than the second";
+    }
+    return diff < 0;
+  }
+};
+
+Matcher<std::tuple<char, int>> LessThan() {
+  return MakeMatcher(new LessThanMatcher);
+}
+
+TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {
+  const Matcher<std::tuple<char, int, int>> m = Args<0, 2>(LessThan());
+  EXPECT_EQ(
+      "whose fields (#0, #2) are ('a' (97, 0x61), 42), "
+      "where the first value is 55 more than the second",
+      Explain(m, std::make_tuple('a', 42, 42)));
+  EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
+            Explain(m, std::make_tuple('\0', 42, 43)));
+}
+
+// Tests for the MATCHER*() macro family.
+
+// Tests that a simple MATCHER() definition works.
+
+MATCHER(IsEven, "") { return (arg % 2) == 0; }
+
+TEST(MatcherMacroTest, Works) {
+  const Matcher<int> m = IsEven();
+  EXPECT_TRUE(m.Matches(6));
+  EXPECT_FALSE(m.Matches(7));
+
+  EXPECT_EQ("is even", Describe(m));
+  EXPECT_EQ("not (is even)", DescribeNegation(m));
+  EXPECT_EQ("", Explain(m, 6));
+  EXPECT_EQ("", Explain(m, 7));
+}
+
+// This also tests that the description string can reference 'negation'.
+MATCHER(IsEven2, negation ? "is odd" : "is even") {
+  if ((arg % 2) == 0) {
+    // Verifies that we can stream to result_listener, a listener
+    // supplied by the MATCHER macro implicitly.
+    *result_listener << "OK";
+    return true;
+  } else {
+    *result_listener << "% 2 == " << (arg % 2);
+    return false;
+  }
+}
+
+// This also tests that the description string can reference matcher
+// parameters.
+MATCHER_P2(EqSumOf, x, y,
+           std::string(negation ? "doesn't equal" : "equals") + " the sum of " +
+               PrintToString(x) + " and " + PrintToString(y)) {
+  if (arg == (x + y)) {
+    *result_listener << "OK";
+    return true;
+  } else {
+    // Verifies that we can stream to the underlying stream of
+    // result_listener.
+    if (result_listener->stream() != nullptr) {
+      *result_listener->stream() << "diff == " << (x + y - arg);
+    }
+    return false;
+  }
+}
+
+// Tests that the matcher description can reference 'negation' and the
+// matcher parameters.
+TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {
+  const Matcher<int> m1 = IsEven2();
+  EXPECT_EQ("is even", Describe(m1));
+  EXPECT_EQ("is odd", DescribeNegation(m1));
+
+  const Matcher<int> m2 = EqSumOf(5, 9);
+  EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));
+  EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));
+}
+
+// Tests explaining match result in a MATCHER* macro.
+TEST(MatcherMacroTest, CanExplainMatchResult) {
+  const Matcher<int> m1 = IsEven2();
+  EXPECT_EQ("OK", Explain(m1, 4));
+  EXPECT_EQ("% 2 == 1", Explain(m1, 5));
+
+  const Matcher<int> m2 = EqSumOf(1, 2);
+  EXPECT_EQ("OK", Explain(m2, 3));
+  EXPECT_EQ("diff == -1", Explain(m2, 4));
+}
+
+// Tests that the body of MATCHER() can reference the type of the
+// value being matched.
+
+MATCHER(IsEmptyString, "") {
+  StaticAssertTypeEq<::std::string, arg_type>();
+  return arg.empty();
+}
+
+MATCHER(IsEmptyStringByRef, "") {
+  StaticAssertTypeEq<const ::std::string&, arg_type>();
+  return arg.empty();
+}
+
+TEST(MatcherMacroTest, CanReferenceArgType) {
+  const Matcher<::std::string> m1 = IsEmptyString();
+  EXPECT_TRUE(m1.Matches(""));
+
+  const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();
+  EXPECT_TRUE(m2.Matches(""));
+}
+
+// Tests that MATCHER() can be used in a namespace.
+
+namespace matcher_test {
+MATCHER(IsOdd, "") { return (arg % 2) != 0; }
+}  // namespace matcher_test
+
+TEST(MatcherMacroTest, WorksInNamespace) {
+  Matcher<int> m = matcher_test::IsOdd();
+  EXPECT_FALSE(m.Matches(4));
+  EXPECT_TRUE(m.Matches(5));
+}
+
+// Tests that Value() can be used to compose matchers.
+MATCHER(IsPositiveOdd, "") {
+  return Value(arg, matcher_test::IsOdd()) && arg > 0;
+}
+
+TEST(MatcherMacroTest, CanBeComposedUsingValue) {
+  EXPECT_THAT(3, IsPositiveOdd());
+  EXPECT_THAT(4, Not(IsPositiveOdd()));
+  EXPECT_THAT(-1, Not(IsPositiveOdd()));
+}
+
+// Tests that a simple MATCHER_P() definition works.
+
+MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }
+
+TEST(MatcherPMacroTest, Works) {
+  const Matcher<int> m = IsGreaterThan32And(5);
+  EXPECT_TRUE(m.Matches(36));
+  EXPECT_FALSE(m.Matches(5));
+
+  EXPECT_EQ("is greater than 32 and (n: 5)", Describe(m));
+  EXPECT_EQ("not (is greater than 32 and (n: 5))", DescribeNegation(m));
+  EXPECT_EQ("", Explain(m, 36));
+  EXPECT_EQ("", Explain(m, 5));
+}
+
+// Tests that the description is calculated correctly from the matcher name.
+MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }
+
+TEST(MatcherPMacroTest, GeneratesCorrectDescription) {
+  const Matcher<int> m = _is_Greater_Than32and_(5);
+
+  EXPECT_EQ("is greater than 32 and (n: 5)", Describe(m));
+  EXPECT_EQ("not (is greater than 32 and (n: 5))", DescribeNegation(m));
+  EXPECT_EQ("", Explain(m, 36));
+  EXPECT_EQ("", Explain(m, 5));
+}
+
+// Tests that a MATCHER_P matcher can be explicitly instantiated with
+// a reference parameter type.
+
+class UncopyableFoo {
+ public:
+  explicit UncopyableFoo(char value) : value_(value) { (void)value_; }
+
+  UncopyableFoo(const UncopyableFoo&) = delete;
+  void operator=(const UncopyableFoo&) = delete;
+
+ private:
+  char value_;
+};
+
+MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }
+
+TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {
+  UncopyableFoo foo1('1'), foo2('2');
+  const Matcher<const UncopyableFoo&> m =
+      ReferencesUncopyable<const UncopyableFoo&>(foo1);
+
+  EXPECT_TRUE(m.Matches(foo1));
+  EXPECT_FALSE(m.Matches(foo2));
+
+  // We don't want the address of the parameter printed, as most
+  // likely it will just annoy the user.  If the address is
+  // interesting, the user should consider passing the parameter by
+  // pointer instead.
+  EXPECT_EQ("references uncopyable (variable: 1-byte object <31>)",
+            Describe(m));
+}
+
+// Tests that the body of MATCHER_Pn() can reference the parameter
+// types.
+
+MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {
+  StaticAssertTypeEq<int, foo_type>();
+  StaticAssertTypeEq<long, bar_type>();  // NOLINT
+  StaticAssertTypeEq<char, baz_type>();
+  return arg == 0;
+}
+
+TEST(MatcherPnMacroTest, CanReferenceParamTypes) {
+  EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));
+}
+
+// Tests that a MATCHER_Pn matcher can be explicitly instantiated with
+// reference parameter types.
+
+MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {
+  return &arg == &variable1 || &arg == &variable2;
+}
+
+TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {
+  UncopyableFoo foo1('1'), foo2('2'), foo3('3');
+  const Matcher<const UncopyableFoo&> const_m =
+      ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
+
+  EXPECT_TRUE(const_m.Matches(foo1));
+  EXPECT_TRUE(const_m.Matches(foo2));
+  EXPECT_FALSE(const_m.Matches(foo3));
+
+  const Matcher<UncopyableFoo&> m =
+      ReferencesAnyOf<UncopyableFoo&, UncopyableFoo&>(foo1, foo2);
+
+  EXPECT_TRUE(m.Matches(foo1));
+  EXPECT_TRUE(m.Matches(foo2));
+  EXPECT_FALSE(m.Matches(foo3));
+}
+
+TEST(MatcherPnMacroTest,
+     GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
+  UncopyableFoo foo1('1'), foo2('2');
+  const Matcher<const UncopyableFoo&> m =
+      ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
+
+  // We don't want the addresses of the parameters printed, as most
+  // likely they will just annoy the user.  If the addresses are
+  // interesting, the user should consider passing the parameters by
+  // pointers instead.
+  EXPECT_EQ(
+      "references any of (variable1: 1-byte object <31>, variable2: 1-byte "
+      "object <32>)",
+      Describe(m));
+}
+
+// Tests that a simple MATCHER_P2() definition works.
+
+MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }
+
+TEST(MatcherPnMacroTest, Works) {
+  const Matcher<const long&> m = IsNotInClosedRange(10, 20);  // NOLINT
+  EXPECT_TRUE(m.Matches(36L));
+  EXPECT_FALSE(m.Matches(15L));
+
+  EXPECT_EQ("is not in closed range (low: 10, hi: 20)", Describe(m));
+  EXPECT_EQ("not (is not in closed range (low: 10, hi: 20))",
+            DescribeNegation(m));
+  EXPECT_EQ("", Explain(m, 36L));
+  EXPECT_EQ("", Explain(m, 15L));
+}
+
+// Tests that MATCHER*() definitions can be overloaded on the number
+// of parameters; also tests MATCHER_Pn() where n >= 3.
+
+MATCHER(EqualsSumOf, "") { return arg == 0; }
+MATCHER_P(EqualsSumOf, a, "") { return arg == a; }
+MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }
+MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }
+MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }
+MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }
+MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {
+  return arg == a + b + c + d + e + f;
+}
+MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {
+  return arg == a + b + c + d + e + f + g;
+}
+MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {
+  return arg == a + b + c + d + e + f + g + h;
+}
+MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {
+  return arg == a + b + c + d + e + f + g + h + i;
+}
+MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {
+  return arg == a + b + c + d + e + f + g + h + i + j;
+}
+
+TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
+  EXPECT_THAT(0, EqualsSumOf());
+  EXPECT_THAT(1, EqualsSumOf(1));
+  EXPECT_THAT(12, EqualsSumOf(10, 2));
+  EXPECT_THAT(123, EqualsSumOf(100, 20, 3));
+  EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));
+  EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
+  EXPECT_THAT("abcdef",
+              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));
+  EXPECT_THAT("abcdefg",
+              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));
+  EXPECT_THAT("abcdefgh", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
+                                      'f', 'g', "h"));
+  EXPECT_THAT("abcdefghi", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
+                                       'f', 'g', "h", 'i'));
+  EXPECT_THAT("abcdefghij",
+              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', "h",
+                          'i', ::std::string("j")));
+
+  EXPECT_THAT(1, Not(EqualsSumOf()));
+  EXPECT_THAT(-1, Not(EqualsSumOf(1)));
+  EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));
+  EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));
+  EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
+  EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
+  EXPECT_THAT("abcdef ",
+              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));
+  EXPECT_THAT("abcdefg ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
+                                          "e", 'f', 'g')));
+  EXPECT_THAT("abcdefgh ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
+                                           "e", 'f', 'g', "h")));
+  EXPECT_THAT("abcdefghi ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
+                                            "e", 'f', 'g', "h", 'i')));
+  EXPECT_THAT("abcdefghij ",
+              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
+                              "h", 'i', ::std::string("j"))));
+}
+
+// Tests that a MATCHER_Pn() definition can be instantiated with any
+// compatible parameter types.
+TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {
+  EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));
+  EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));
+
+  EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));
+  EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));
+}
+
+// Tests that the matcher body can promote the parameter types.
+
+MATCHER_P2(EqConcat, prefix, suffix, "") {
+  // The following lines promote the two parameters to desired types.
+  std::string prefix_str(prefix);
+  char suffix_char = static_cast<char>(suffix);
+  return arg == prefix_str + suffix_char;
+}
+
+TEST(MatcherPnMacroTest, SimpleTypePromotion) {
+  Matcher<std::string> no_promo = EqConcat(std::string("foo"), 't');
+  Matcher<const std::string&> promo = EqConcat("foo", static_cast<int>('t'));
+  EXPECT_FALSE(no_promo.Matches("fool"));
+  EXPECT_FALSE(promo.Matches("fool"));
+  EXPECT_TRUE(no_promo.Matches("foot"));
+  EXPECT_TRUE(promo.Matches("foot"));
+}
+
+// Verifies the type of a MATCHER*.
+
+TEST(MatcherPnMacroTest, TypesAreCorrect) {
+  // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.
+  EqualsSumOfMatcher a0 = EqualsSumOf();
+
+  // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.
+  EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
+
+  // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk
+  // variable, and so on.
+  EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');
+  EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');
+  EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');
+  EqualsSumOfMatcherP5<int, int, int, int, char> a5 =
+      EqualsSumOf(1, 2, 3, 4, '5');
+  EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =
+      EqualsSumOf(1, 2, 3, 4, 5, '6');
+  EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =
+      EqualsSumOf(1, 2, 3, 4, 5, 6, '7');
+  EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =
+      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');
+  EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =
+      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
+  EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
+      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
+
+  // Avoid "unused variable" warnings.
+  (void)a0;
+  (void)a1;
+  (void)a2;
+  (void)a3;
+  (void)a4;
+  (void)a5;
+  (void)a6;
+  (void)a7;
+  (void)a8;
+  (void)a9;
+  (void)a10;
+}
+
+// Tests that matcher-typed parameters can be used in Value() inside a
+// MATCHER_Pn definition.
+
+// Succeeds if arg matches exactly 2 of the 3 matchers.
+MATCHER_P3(TwoOf, m1, m2, m3, "") {
+  const int count = static_cast<int>(Value(arg, m1)) +
+                    static_cast<int>(Value(arg, m2)) +
+                    static_cast<int>(Value(arg, m3));
+  return count == 2;
+}
+
+TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
+  EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));
+  EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));
+}
+
+// Tests Contains().Times().
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(ContainsTimes);
+
+TEST(ContainsTimes, ListMatchesWhenElementQuantityMatches) {
+  list<int> some_list;
+  some_list.push_back(3);
+  some_list.push_back(1);
+  some_list.push_back(2);
+  some_list.push_back(3);
+  EXPECT_THAT(some_list, Contains(3).Times(2));
+  EXPECT_THAT(some_list, Contains(2).Times(1));
+  EXPECT_THAT(some_list, Contains(Ge(2)).Times(3));
+  EXPECT_THAT(some_list, Contains(Ge(2)).Times(Gt(2)));
+  EXPECT_THAT(some_list, Contains(4).Times(0));
+  EXPECT_THAT(some_list, Contains(_).Times(4));
+  EXPECT_THAT(some_list, Not(Contains(5).Times(1)));
+  EXPECT_THAT(some_list, Contains(5).Times(_));  // Times(_) always matches
+  EXPECT_THAT(some_list, Not(Contains(3).Times(1)));
+  EXPECT_THAT(some_list, Contains(3).Times(Not(1)));
+  EXPECT_THAT(list<int>{}, Not(Contains(_)));
+}
+
+TEST_P(ContainsTimesP, ExplainsMatchResultCorrectly) {
+  const int a[2] = {1, 2};
+  Matcher<const int(&)[2]> m = Contains(2).Times(3);
+  EXPECT_EQ(
+      "whose element #1 matches but whose match quantity of 1 does not match",
+      Explain(m, a));
+
+  m = Contains(3).Times(0);
+  EXPECT_EQ("has no element that matches and whose match quantity of 0 matches",
+            Explain(m, a));
+
+  m = Contains(3).Times(4);
+  EXPECT_EQ(
+      "has no element that matches and whose match quantity of 0 does not "
+      "match",
+      Explain(m, a));
+
+  m = Contains(2).Times(4);
+  EXPECT_EQ(
+      "whose element #1 matches but whose match quantity of 1 does not "
+      "match",
+      Explain(m, a));
+
+  m = Contains(GreaterThan(0)).Times(2);
+  EXPECT_EQ("whose elements (0, 1) match and whose match quantity of 2 matches",
+            Explain(m, a));
+
+  m = Contains(GreaterThan(10)).Times(Gt(1));
+  EXPECT_EQ(
+      "has no element that matches and whose match quantity of 0 does not "
+      "match",
+      Explain(m, a));
+
+  m = Contains(GreaterThan(0)).Times(GreaterThan<size_t>(5));
+  EXPECT_EQ(
+      "whose elements (0, 1) match but whose match quantity of 2 does not "
+      "match, which is 3 less than 5",
+      Explain(m, a));
+}
+
+TEST(ContainsTimes, DescribesItselfCorrectly) {
+  Matcher<vector<int>> m = Contains(1).Times(2);
+  EXPECT_EQ("quantity of elements that match is equal to 1 is equal to 2",
+            Describe(m));
+
+  Matcher<vector<int>> m2 = Not(m);
+  EXPECT_EQ("quantity of elements that match is equal to 1 isn't equal to 2",
+            Describe(m2));
+}
+
+// Tests AllOfArray()
+
+TEST(AllOfArrayTest, BasicForms) {
+  // Iterator
+  std::vector<int> v0{};
+  std::vector<int> v1{1};
+  std::vector<int> v2{2, 3};
+  std::vector<int> v3{4, 4, 4};
+  EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end()));
+  EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end()));
+  EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));
+  EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));
+  EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end()));
+  // Pointer +  size
+  int ar[6] = {1, 2, 3, 4, 4, 4};
+  EXPECT_THAT(0, AllOfArray(ar, 0));
+  EXPECT_THAT(1, AllOfArray(ar, 1));
+  EXPECT_THAT(2, Not(AllOfArray(ar, 1)));
+  EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3)));
+  EXPECT_THAT(4, AllOfArray(ar + 3, 3));
+  // Array
+  // int ar0[0];  Not usable
+  int ar1[1] = {1};
+  int ar2[2] = {2, 3};
+  int ar3[3] = {4, 4, 4};
+  // EXPECT_THAT(0, Not(AllOfArray(ar0)));  // Cannot work
+  EXPECT_THAT(1, AllOfArray(ar1));
+  EXPECT_THAT(2, Not(AllOfArray(ar1)));
+  EXPECT_THAT(3, Not(AllOfArray(ar2)));
+  EXPECT_THAT(4, AllOfArray(ar3));
+  // Container
+  EXPECT_THAT(0, AllOfArray(v0));
+  EXPECT_THAT(1, AllOfArray(v1));
+  EXPECT_THAT(2, Not(AllOfArray(v1)));
+  EXPECT_THAT(3, Not(AllOfArray(v2)));
+  EXPECT_THAT(4, AllOfArray(v3));
+  // Initializer
+  EXPECT_THAT(0, AllOfArray<int>({}));  // Requires template arg.
+  EXPECT_THAT(1, AllOfArray({1}));
+  EXPECT_THAT(2, Not(AllOfArray({1})));
+  EXPECT_THAT(3, Not(AllOfArray({2, 3})));
+  EXPECT_THAT(4, AllOfArray({4, 4, 4}));
+}
+
+TEST(AllOfArrayTest, Matchers) {
+  // vector
+  std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};
+  EXPECT_THAT(0, Not(AllOfArray(matchers)));
+  EXPECT_THAT(1, AllOfArray(matchers));
+  EXPECT_THAT(2, Not(AllOfArray(matchers)));
+  // initializer_list
+  EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)})));
+  EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)}));
+}
+
+INSTANTIATE_GTEST_MATCHER_TEST_P(AnyOfArrayTest);
+
+TEST(AnyOfArrayTest, BasicForms) {
+  // Iterator
+  std::vector<int> v0{};
+  std::vector<int> v1{1};
+  std::vector<int> v2{2, 3};
+  EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end())));
+  EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end()));
+  EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));
+  EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end()));
+  EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));
+  // Pointer +  size
+  int ar[3] = {1, 2, 3};
+  EXPECT_THAT(0, Not(AnyOfArray(ar, 0)));
+  EXPECT_THAT(1, AnyOfArray(ar, 1));
+  EXPECT_THAT(2, Not(AnyOfArray(ar, 1)));
+  EXPECT_THAT(3, AnyOfArray(ar + 1, 2));
+  EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2)));
+  // Array
+  // int ar0[0];  Not usable
+  int ar1[1] = {1};
+  int ar2[2] = {2, 3};
+  // EXPECT_THAT(0, Not(AnyOfArray(ar0)));  // Cannot work
+  EXPECT_THAT(1, AnyOfArray(ar1));
+  EXPECT_THAT(2, Not(AnyOfArray(ar1)));
+  EXPECT_THAT(3, AnyOfArray(ar2));
+  EXPECT_THAT(4, Not(AnyOfArray(ar2)));
+  // Container
+  EXPECT_THAT(0, Not(AnyOfArray(v0)));
+  EXPECT_THAT(1, AnyOfArray(v1));
+  EXPECT_THAT(2, Not(AnyOfArray(v1)));
+  EXPECT_THAT(3, AnyOfArray(v2));
+  EXPECT_THAT(4, Not(AnyOfArray(v2)));
+  // Initializer
+  EXPECT_THAT(0, Not(AnyOfArray<int>({})));  // Requires template arg.
+  EXPECT_THAT(1, AnyOfArray({1}));
+  EXPECT_THAT(2, Not(AnyOfArray({1})));
+  EXPECT_THAT(3, AnyOfArray({2, 3}));
+  EXPECT_THAT(4, Not(AnyOfArray({2, 3})));
+}
+
+TEST(AnyOfArrayTest, Matchers) {
+  // We negate test AllOfArrayTest.Matchers.
+  // vector
+  std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};
+  EXPECT_THAT(0, AnyOfArray(matchers));
+  EXPECT_THAT(1, Not(AnyOfArray(matchers)));
+  EXPECT_THAT(2, AnyOfArray(matchers));
+  // initializer_list
+  EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)}));
+  EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)})));
+}
+
+TEST_P(AnyOfArrayTestP, ExplainsMatchResultCorrectly) {
+  // AnyOfArray and AllOfArry use the same underlying template-template,
+  // thus it is sufficient to test one here.
+  const std::vector<int> v0{};
+  const std::vector<int> v1{1};
+  const std::vector<int> v2{2, 3};
+  const Matcher<int> m0 = AnyOfArray(v0);
+  const Matcher<int> m1 = AnyOfArray(v1);
+  const Matcher<int> m2 = AnyOfArray(v2);
+  EXPECT_EQ("", Explain(m0, 0));
+  EXPECT_EQ("", Explain(m1, 1));
+  EXPECT_EQ("", Explain(m1, 2));
+  EXPECT_EQ("", Explain(m2, 3));
+  EXPECT_EQ("", Explain(m2, 4));
+  EXPECT_EQ("()", Describe(m0));
+  EXPECT_EQ("(is equal to 1)", Describe(m1));
+  EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));
+  EXPECT_EQ("()", DescribeNegation(m0));
+  EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1));
+  EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2));
+  // Explain with matchers
+  const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});
+  const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});
+  // Explains the first positive match and all prior negative matches...
+  EXPECT_EQ("which is 1 less than 1", Explain(g1, 0));
+  EXPECT_EQ("which is the same as 1", Explain(g1, 1));
+  EXPECT_EQ("which is 1 more than 1", Explain(g1, 2));
+  EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2",
+            Explain(g2, 0));
+  EXPECT_EQ("which is the same as 1, and which is 1 less than 2",
+            Explain(g2, 1));
+  EXPECT_EQ("which is 1 more than 1",  // Only the first
+            Explain(g2, 2));
+}
+
+MATCHER(IsNotNull, "") { return arg != nullptr; }
+
+// Verifies that a matcher defined using MATCHER() can work on
+// move-only types.
+TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
+  std::unique_ptr<int> p(new int(3));
+  EXPECT_THAT(p, IsNotNull());
+  EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
+}
+
+MATCHER_P(UniquePointee, pointee, "") { return *arg == pointee; }
+
+// Verifies that a matcher defined using MATCHER_P*() can work on
+// move-only types.
+TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
+  std::unique_ptr<int> p(new int(3));
+  EXPECT_THAT(p, UniquePointee(3));
+  EXPECT_THAT(p, Not(UniquePointee(2)));
+}
+
+#if GTEST_HAS_EXCEPTIONS
+
+// std::function<void()> is used below for compatibility with older copies of
+// GCC. Normally, a raw lambda is all that is needed.
+
+// Test that examples from documentation compile
+TEST(ThrowsTest, Examples) {
+  EXPECT_THAT(
+      std::function<void()>([]() { throw std::runtime_error("message"); }),
+      Throws<std::runtime_error>());
+
+  EXPECT_THAT(
+      std::function<void()>([]() { throw std::runtime_error("message"); }),
+      ThrowsMessage<std::runtime_error>(HasSubstr("message")));
+}
+
+TEST(ThrowsTest, PrintsExceptionWhat) {
+  EXPECT_THAT(
+      std::function<void()>([]() { throw std::runtime_error("ABC123XYZ"); }),
+      ThrowsMessage<std::runtime_error>(HasSubstr("ABC123XYZ")));
+}
+
+TEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) {
+  EXPECT_THAT(std::function<void()>([]() { throw std::exception(); }),
+              Throws<std::exception>());
+}
+
+TEST(ThrowsTest, CallableExecutedExactlyOnce) {
+  size_t a = 0;
+
+  EXPECT_THAT(std::function<void()>([&a]() {
+                a++;
+                throw 10;
+              }),
+              Throws<int>());
+  EXPECT_EQ(a, 1u);
+
+  EXPECT_THAT(std::function<void()>([&a]() {
+                a++;
+                throw std::runtime_error("message");
+              }),
+              Throws<std::runtime_error>());
+  EXPECT_EQ(a, 2u);
+
+  EXPECT_THAT(std::function<void()>([&a]() {
+                a++;
+                throw std::runtime_error("message");
+              }),
+              ThrowsMessage<std::runtime_error>(HasSubstr("message")));
+  EXPECT_EQ(a, 3u);
+
+  EXPECT_THAT(std::function<void()>([&a]() {
+                a++;
+                throw std::runtime_error("message");
+              }),
+              Throws<std::runtime_error>(
+                  Property(&std::runtime_error::what, HasSubstr("message"))));
+  EXPECT_EQ(a, 4u);
+}
+
+TEST(ThrowsTest, Describe) {
+  Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
+  std::stringstream ss;
+  matcher.DescribeTo(&ss);
+  auto explanation = ss.str();
+  EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
+}
+
+TEST(ThrowsTest, Success) {
+  Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
+  StringMatchResultListener listener;
+  EXPECT_TRUE(matcher.MatchAndExplain(
+      []() { throw std::runtime_error("error message"); }, &listener));
+  EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
+}
+
+TEST(ThrowsTest, FailWrongType) {
+  Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
+  StringMatchResultListener listener;
+  EXPECT_FALSE(matcher.MatchAndExplain(
+      []() { throw std::logic_error("error message"); }, &listener));
+  EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
+  EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
+}
+
+TEST(ThrowsTest, FailWrongTypeNonStd) {
+  Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
+  StringMatchResultListener listener;
+  EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
+  EXPECT_THAT(listener.str(),
+              HasSubstr("throws an exception of an unknown type"));
+}
+
+TEST(ThrowsTest, FailNoThrow) {
+  Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
+  StringMatchResultListener listener;
+  EXPECT_FALSE(matcher.MatchAndExplain([]() { (void)0; }, &listener));
+  EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
+}
+
+class ThrowsPredicateTest
+    : public TestWithParam<Matcher<std::function<void()>>> {};
+
+TEST_P(ThrowsPredicateTest, Describe) {
+  Matcher<std::function<void()>> matcher = GetParam();
+  std::stringstream ss;
+  matcher.DescribeTo(&ss);
+  auto explanation = ss.str();
+  EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
+  EXPECT_THAT(explanation, HasSubstr("error message"));
+}
+
+TEST_P(ThrowsPredicateTest, Success) {
+  Matcher<std::function<void()>> matcher = GetParam();
+  StringMatchResultListener listener;
+  EXPECT_TRUE(matcher.MatchAndExplain(
+      []() { throw std::runtime_error("error message"); }, &listener));
+  EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
+}
+
+TEST_P(ThrowsPredicateTest, FailWrongType) {
+  Matcher<std::function<void()>> matcher = GetParam();
+  StringMatchResultListener listener;
+  EXPECT_FALSE(matcher.MatchAndExplain(
+      []() { throw std::logic_error("error message"); }, &listener));
+  EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
+  EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
+}
+
+TEST_P(ThrowsPredicateTest, FailWrongTypeNonStd) {
+  Matcher<std::function<void()>> matcher = GetParam();
+  StringMatchResultListener listener;
+  EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
+  EXPECT_THAT(listener.str(),
+              HasSubstr("throws an exception of an unknown type"));
+}
+
+TEST_P(ThrowsPredicateTest, FailNoThrow) {
+  Matcher<std::function<void()>> matcher = GetParam();
+  StringMatchResultListener listener;
+  EXPECT_FALSE(matcher.MatchAndExplain([]() {}, &listener));
+  EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
+}
+
+INSTANTIATE_TEST_SUITE_P(
+    AllMessagePredicates, ThrowsPredicateTest,
+    Values(Matcher<std::function<void()>>(
+        ThrowsMessage<std::runtime_error>(HasSubstr("error message")))));
+
+// Tests that Throws<E1>(Matcher<E2>{}) compiles even when E2 != const E1&.
+TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) {
+  {
+    Matcher<std::function<void()>> matcher =
+        ThrowsMessage<std::runtime_error>(HasSubstr("error message"));
+    EXPECT_TRUE(
+        matcher.Matches([]() { throw std::runtime_error("error message"); }));
+    EXPECT_FALSE(
+        matcher.Matches([]() { throw std::runtime_error("wrong message"); }));
+  }
+
+  {
+    Matcher<uint64_t> inner = Eq(10);
+    Matcher<std::function<void()>> matcher = Throws<uint32_t>(inner);
+    EXPECT_TRUE(matcher.Matches([]() { throw(uint32_t) 10; }));
+    EXPECT_FALSE(matcher.Matches([]() { throw(uint32_t) 11; }));
+  }
+}
+
+// Tests that ThrowsMessage("message") is equivalent
+// to ThrowsMessage(Eq<std::string>("message")).
+TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {
+  Matcher<std::function<void()>> matcher =
+      ThrowsMessage<std::runtime_error>("error message");
+  EXPECT_TRUE(
+      matcher.Matches([]() { throw std::runtime_error("error message"); }));
+  EXPECT_FALSE(matcher.Matches(
+      []() { throw std::runtime_error("wrong error message"); }));
+}
+
+#endif  // GTEST_HAS_EXCEPTIONS
+
+}  // namespace
+}  // namespace gmock_matchers_test
+}  // namespace testing
+
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc
deleted file mode 100644 (file)
index 1f48a76..0000000
+++ /dev/null
@@ -1,8562 +0,0 @@
-// Copyright 2007, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file tests some commonly used argument matchers.
-
-// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
-// possible loss of data and C4100, unreferenced local parameter
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4244)
-# pragma warning(disable:4100)
-#endif
-
-#include "gmock/gmock-matchers.h"
-
-#include <string.h>
-#include <time.h>
-
-#include <array>
-#include <cstdint>
-#include <deque>
-#include <forward_list>
-#include <functional>
-#include <iostream>
-#include <iterator>
-#include <limits>
-#include <list>
-#include <map>
-#include <memory>
-#include <set>
-#include <sstream>
-#include <string>
-#include <type_traits>
-#include <unordered_map>
-#include <unordered_set>
-#include <utility>
-#include <vector>
-
-#include "gmock/gmock-more-matchers.h"
-#include "gmock/gmock.h"
-#include "gtest/gtest-spi.h"
-#include "gtest/gtest.h"
-
-namespace testing {
-namespace gmock_matchers_test {
-namespace {
-
-using std::greater;
-using std::less;
-using std::list;
-using std::make_pair;
-using std::map;
-using std::multimap;
-using std::multiset;
-using std::ostream;
-using std::pair;
-using std::set;
-using std::stringstream;
-using std::vector;
-using testing::internal::DummyMatchResultListener;
-using testing::internal::ElementMatcherPair;
-using testing::internal::ElementMatcherPairs;
-using testing::internal::ElementsAreArrayMatcher;
-using testing::internal::ExplainMatchFailureTupleTo;
-using testing::internal::FloatingEqMatcher;
-using testing::internal::FormatMatcherDescription;
-using testing::internal::IsReadableTypeName;
-using testing::internal::MatchMatrix;
-using testing::internal::PredicateFormatterFromMatcher;
-using testing::internal::RE;
-using testing::internal::StreamMatchResultListener;
-using testing::internal::Strings;
-
-// Helper for testing container-valued matchers in mock method context. It is
-// important to test matchers in this context, since it requires additional type
-// deduction beyond what EXPECT_THAT does, thus making it more restrictive.
-struct ContainerHelper {
-  MOCK_METHOD1(Call, void(std::vector<std::unique_ptr<int>>));
-};
-
-std::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) {
-  std::vector<std::unique_ptr<int>> pointers;
-  for (int i : ints) pointers.emplace_back(new int(i));
-  return pointers;
-}
-
-// For testing ExplainMatchResultTo().
-class GreaterThanMatcher : public MatcherInterface<int> {
- public:
-  explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
-
-  void DescribeTo(ostream* os) const override { *os << "is > " << rhs_; }
-
-  bool MatchAndExplain(int lhs, MatchResultListener* listener) const override {
-    const int diff = lhs - rhs_;
-    if (diff > 0) {
-      *listener << "which is " << diff << " more than " << rhs_;
-    } else if (diff == 0) {
-      *listener << "which is the same as " << rhs_;
-    } else {
-      *listener << "which is " << -diff << " less than " << rhs_;
-    }
-
-    return lhs > rhs_;
-  }
-
- private:
-  int rhs_;
-};
-
-Matcher<int> GreaterThan(int n) {
-  return MakeMatcher(new GreaterThanMatcher(n));
-}
-
-std::string OfType(const std::string& type_name) {
-#if GTEST_HAS_RTTI
-  return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : "";
-#else
-  return "";
-#endif
-}
-
-// Returns the description of the given matcher.
-template <typename T>
-std::string Describe(const Matcher<T>& m) {
-  return DescribeMatcher<T>(m);
-}
-
-// Returns the description of the negation of the given matcher.
-template <typename T>
-std::string DescribeNegation(const Matcher<T>& m) {
-  return DescribeMatcher<T>(m, true);
-}
-
-// Returns the reason why x matches, or doesn't match, m.
-template <typename MatcherType, typename Value>
-std::string Explain(const MatcherType& m, const Value& x) {
-  StringMatchResultListener listener;
-  ExplainMatchResult(m, x, &listener);
-  return listener.str();
-}
-
-TEST(MonotonicMatcherTest, IsPrintable) {
-  stringstream ss;
-  ss << GreaterThan(5);
-  EXPECT_EQ("is > 5", ss.str());
-}
-
-TEST(MatchResultListenerTest, StreamingWorks) {
-  StringMatchResultListener listener;
-  listener << "hi" << 5;
-  EXPECT_EQ("hi5", listener.str());
-
-  listener.Clear();
-  EXPECT_EQ("", listener.str());
-
-  listener << 42;
-  EXPECT_EQ("42", listener.str());
-
-  // Streaming shouldn't crash when the underlying ostream is NULL.
-  DummyMatchResultListener dummy;
-  dummy << "hi" << 5;
-}
-
-TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
-  EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr);
-  EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr);
-
-  EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
-}
-
-TEST(MatchResultListenerTest, IsInterestedWorks) {
-  EXPECT_TRUE(StringMatchResultListener().IsInterested());
-  EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
-
-  EXPECT_FALSE(DummyMatchResultListener().IsInterested());
-  EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested());
-}
-
-// Makes sure that the MatcherInterface<T> interface doesn't
-// change.
-class EvenMatcherImpl : public MatcherInterface<int> {
- public:
-  bool MatchAndExplain(int x,
-                       MatchResultListener* /* listener */) const override {
-    return x % 2 == 0;
-  }
-
-  void DescribeTo(ostream* os) const override { *os << "is an even number"; }
-
-  // We deliberately don't define DescribeNegationTo() and
-  // ExplainMatchResultTo() here, to make sure the definition of these
-  // two methods is optional.
-};
-
-// Makes sure that the MatcherInterface API doesn't change.
-TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
-  EvenMatcherImpl m;
-}
-
-// Tests implementing a monomorphic matcher using MatchAndExplain().
-
-class NewEvenMatcherImpl : public MatcherInterface<int> {
- public:
-  bool MatchAndExplain(int x, MatchResultListener* listener) const override {
-    const bool match = x % 2 == 0;
-    // Verifies that we can stream to a listener directly.
-    *listener << "value % " << 2;
-    if (listener->stream() != nullptr) {
-      // Verifies that we can stream to a listener's underlying stream
-      // too.
-      *listener->stream() << " == " << (x % 2);
-    }
-    return match;
-  }
-
-  void DescribeTo(ostream* os) const override { *os << "is an even number"; }
-};
-
-TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
-  Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
-  EXPECT_TRUE(m.Matches(2));
-  EXPECT_FALSE(m.Matches(3));
-  EXPECT_EQ("value % 2 == 0", Explain(m, 2));
-  EXPECT_EQ("value % 2 == 1", Explain(m, 3));
-}
-
-// Tests default-constructing a matcher.
-TEST(MatcherTest, CanBeDefaultConstructed) {
-  Matcher<double> m;
-}
-
-// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
-TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
-  const MatcherInterface<int>* impl = new EvenMatcherImpl;
-  Matcher<int> m(impl);
-  EXPECT_TRUE(m.Matches(4));
-  EXPECT_FALSE(m.Matches(5));
-}
-
-// Tests that value can be used in place of Eq(value).
-TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
-  Matcher<int> m1 = 5;
-  EXPECT_TRUE(m1.Matches(5));
-  EXPECT_FALSE(m1.Matches(6));
-}
-
-// Tests that NULL can be used in place of Eq(NULL).
-TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
-  Matcher<int*> m1 = nullptr;
-  EXPECT_TRUE(m1.Matches(nullptr));
-  int n = 0;
-  EXPECT_FALSE(m1.Matches(&n));
-}
-
-// Tests that matchers can be constructed from a variable that is not properly
-// defined. This should be illegal, but many users rely on this accidentally.
-struct Undefined {
-  virtual ~Undefined() = 0;
-  static const int kInt = 1;
-};
-
-TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {
-  Matcher<int> m1 = Undefined::kInt;
-  EXPECT_TRUE(m1.Matches(1));
-  EXPECT_FALSE(m1.Matches(2));
-}
-
-// Test that a matcher parameterized with an abstract class compiles.
-TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; }
-
-// Tests that matchers are copyable.
-TEST(MatcherTest, IsCopyable) {
-  // Tests the copy constructor.
-  Matcher<bool> m1 = Eq(false);
-  EXPECT_TRUE(m1.Matches(false));
-  EXPECT_FALSE(m1.Matches(true));
-
-  // Tests the assignment operator.
-  m1 = Eq(true);
-  EXPECT_TRUE(m1.Matches(true));
-  EXPECT_FALSE(m1.Matches(false));
-}
-
-// Tests that Matcher<T>::DescribeTo() calls
-// MatcherInterface<T>::DescribeTo().
-TEST(MatcherTest, CanDescribeItself) {
-  EXPECT_EQ("is an even number",
-            Describe(Matcher<int>(new EvenMatcherImpl)));
-}
-
-// Tests Matcher<T>::MatchAndExplain().
-TEST(MatcherTest, MatchAndExplain) {
-  Matcher<int> m = GreaterThan(0);
-  StringMatchResultListener listener1;
-  EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
-  EXPECT_EQ("which is 42 more than 0", listener1.str());
-
-  StringMatchResultListener listener2;
-  EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
-  EXPECT_EQ("which is 9 less than 0", listener2.str());
-}
-
-// Tests that a C-string literal can be implicitly converted to a
-// Matcher<std::string> or Matcher<const std::string&>.
-TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
-  Matcher<std::string> m1 = "hi";
-  EXPECT_TRUE(m1.Matches("hi"));
-  EXPECT_FALSE(m1.Matches("hello"));
-
-  Matcher<const std::string&> m2 = "hi";
-  EXPECT_TRUE(m2.Matches("hi"));
-  EXPECT_FALSE(m2.Matches("hello"));
-}
-
-// Tests that a string object can be implicitly converted to a
-// Matcher<std::string> or Matcher<const std::string&>.
-TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
-  Matcher<std::string> m1 = std::string("hi");
-  EXPECT_TRUE(m1.Matches("hi"));
-  EXPECT_FALSE(m1.Matches("hello"));
-
-  Matcher<const std::string&> m2 = std::string("hi");
-  EXPECT_TRUE(m2.Matches("hi"));
-  EXPECT_FALSE(m2.Matches("hello"));
-}
-
-#if GTEST_INTERNAL_HAS_STRING_VIEW
-// Tests that a C-string literal can be implicitly converted to a
-// Matcher<StringView> or Matcher<const StringView&>.
-TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
-  Matcher<internal::StringView> m1 = "cats";
-  EXPECT_TRUE(m1.Matches("cats"));
-  EXPECT_FALSE(m1.Matches("dogs"));
-
-  Matcher<const internal::StringView&> m2 = "cats";
-  EXPECT_TRUE(m2.Matches("cats"));
-  EXPECT_FALSE(m2.Matches("dogs"));
-}
-
-// Tests that a std::string object can be implicitly converted to a
-// Matcher<StringView> or Matcher<const StringView&>.
-TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
-  Matcher<internal::StringView> m1 = std::string("cats");
-  EXPECT_TRUE(m1.Matches("cats"));
-  EXPECT_FALSE(m1.Matches("dogs"));
-
-  Matcher<const internal::StringView&> m2 = std::string("cats");
-  EXPECT_TRUE(m2.Matches("cats"));
-  EXPECT_FALSE(m2.Matches("dogs"));
-}
-
-// Tests that a StringView object can be implicitly converted to a
-// Matcher<StringView> or Matcher<const StringView&>.
-TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
-  Matcher<internal::StringView> m1 = internal::StringView("cats");
-  EXPECT_TRUE(m1.Matches("cats"));
-  EXPECT_FALSE(m1.Matches("dogs"));
-
-  Matcher<const internal::StringView&> m2 = internal::StringView("cats");
-  EXPECT_TRUE(m2.Matches("cats"));
-  EXPECT_FALSE(m2.Matches("dogs"));
-}
-#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
-
-// Tests that a std::reference_wrapper<std::string> object can be implicitly
-// converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().
-TEST(StringMatcherTest,
-     CanBeImplicitlyConstructedFromEqReferenceWrapperString) {
-  std::string value = "cats";
-  Matcher<std::string> m1 = Eq(std::ref(value));
-  EXPECT_TRUE(m1.Matches("cats"));
-  EXPECT_FALSE(m1.Matches("dogs"));
-
-  Matcher<const std::string&> m2 = Eq(std::ref(value));
-  EXPECT_TRUE(m2.Matches("cats"));
-  EXPECT_FALSE(m2.Matches("dogs"));
-}
-
-// Tests that MakeMatcher() constructs a Matcher<T> from a
-// MatcherInterface* without requiring the user to explicitly
-// write the type.
-TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
-  const MatcherInterface<int>* dummy_impl = new EvenMatcherImpl;
-  Matcher<int> m = MakeMatcher(dummy_impl);
-}
-
-// Tests that MakePolymorphicMatcher() can construct a polymorphic
-// matcher from its implementation using the old API.
-const int g_bar = 1;
-class ReferencesBarOrIsZeroImpl {
- public:
-  template <typename T>
-  bool MatchAndExplain(const T& x,
-                       MatchResultListener* /* listener */) const {
-    const void* p = &x;
-    return p == &g_bar || x == 0;
-  }
-
-  void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
-
-  void DescribeNegationTo(ostream* os) const {
-    *os << "doesn't reference g_bar and is not zero";
-  }
-};
-
-// This function verifies that MakePolymorphicMatcher() returns a
-// PolymorphicMatcher<T> where T is the argument's type.
-PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
-  return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
-}
-
-TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
-  // Using a polymorphic matcher to match a reference type.
-  Matcher<const int&> m1 = ReferencesBarOrIsZero();
-  EXPECT_TRUE(m1.Matches(0));
-  // Verifies that the identity of a by-reference argument is preserved.
-  EXPECT_TRUE(m1.Matches(g_bar));
-  EXPECT_FALSE(m1.Matches(1));
-  EXPECT_EQ("g_bar or zero", Describe(m1));
-
-  // Using a polymorphic matcher to match a value type.
-  Matcher<double> m2 = ReferencesBarOrIsZero();
-  EXPECT_TRUE(m2.Matches(0.0));
-  EXPECT_FALSE(m2.Matches(0.1));
-  EXPECT_EQ("g_bar or zero", Describe(m2));
-}
-
-// Tests implementing a polymorphic matcher using MatchAndExplain().
-
-class PolymorphicIsEvenImpl {
- public:
-  void DescribeTo(ostream* os) const { *os << "is even"; }
-
-  void DescribeNegationTo(ostream* os) const {
-    *os << "is odd";
-  }
-
-  template <typename T>
-  bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
-    // Verifies that we can stream to the listener directly.
-    *listener << "% " << 2;
-    if (listener->stream() != nullptr) {
-      // Verifies that we can stream to the listener's underlying stream
-      // too.
-      *listener->stream() << " == " << (x % 2);
-    }
-    return (x % 2) == 0;
-  }
-};
-
-PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
-  return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
-}
-
-TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
-  // Using PolymorphicIsEven() as a Matcher<int>.
-  const Matcher<int> m1 = PolymorphicIsEven();
-  EXPECT_TRUE(m1.Matches(42));
-  EXPECT_FALSE(m1.Matches(43));
-  EXPECT_EQ("is even", Describe(m1));
-
-  const Matcher<int> not_m1 = Not(m1);
-  EXPECT_EQ("is odd", Describe(not_m1));
-
-  EXPECT_EQ("% 2 == 0", Explain(m1, 42));
-
-  // Using PolymorphicIsEven() as a Matcher<char>.
-  const Matcher<char> m2 = PolymorphicIsEven();
-  EXPECT_TRUE(m2.Matches('\x42'));
-  EXPECT_FALSE(m2.Matches('\x43'));
-  EXPECT_EQ("is even", Describe(m2));
-
-  const Matcher<char> not_m2 = Not(m2);
-  EXPECT_EQ("is odd", Describe(not_m2));
-
-  EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
-}
-
-// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
-TEST(MatcherCastTest, FromPolymorphicMatcher) {
-  Matcher<int> m = MatcherCast<int>(Eq(5));
-  EXPECT_TRUE(m.Matches(5));
-  EXPECT_FALSE(m.Matches(6));
-}
-
-// For testing casting matchers between compatible types.
-class IntValue {
- public:
-  // An int can be statically (although not implicitly) cast to a
-  // IntValue.
-  explicit IntValue(int a_value) : value_(a_value) {}
-
-  int value() const { return value_; }
- private:
-  int value_;
-};
-
-// For testing casting matchers between compatible types.
-bool IsPositiveIntValue(const IntValue& foo) {
-  return foo.value() > 0;
-}
-
-// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
-// can be statically converted to U.
-TEST(MatcherCastTest, FromCompatibleType) {
-  Matcher<double> m1 = Eq(2.0);
-  Matcher<int> m2 = MatcherCast<int>(m1);
-  EXPECT_TRUE(m2.Matches(2));
-  EXPECT_FALSE(m2.Matches(3));
-
-  Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
-  Matcher<int> m4 = MatcherCast<int>(m3);
-  // In the following, the arguments 1 and 0 are statically converted
-  // to IntValue objects, and then tested by the IsPositiveIntValue()
-  // predicate.
-  EXPECT_TRUE(m4.Matches(1));
-  EXPECT_FALSE(m4.Matches(0));
-}
-
-// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
-TEST(MatcherCastTest, FromConstReferenceToNonReference) {
-  Matcher<const int&> m1 = Eq(0);
-  Matcher<int> m2 = MatcherCast<int>(m1);
-  EXPECT_TRUE(m2.Matches(0));
-  EXPECT_FALSE(m2.Matches(1));
-}
-
-// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
-TEST(MatcherCastTest, FromReferenceToNonReference) {
-  Matcher<int&> m1 = Eq(0);
-  Matcher<int> m2 = MatcherCast<int>(m1);
-  EXPECT_TRUE(m2.Matches(0));
-  EXPECT_FALSE(m2.Matches(1));
-}
-
-// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
-TEST(MatcherCastTest, FromNonReferenceToConstReference) {
-  Matcher<int> m1 = Eq(0);
-  Matcher<const int&> m2 = MatcherCast<const int&>(m1);
-  EXPECT_TRUE(m2.Matches(0));
-  EXPECT_FALSE(m2.Matches(1));
-}
-
-// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
-TEST(MatcherCastTest, FromNonReferenceToReference) {
-  Matcher<int> m1 = Eq(0);
-  Matcher<int&> m2 = MatcherCast<int&>(m1);
-  int n = 0;
-  EXPECT_TRUE(m2.Matches(n));
-  n = 1;
-  EXPECT_FALSE(m2.Matches(n));
-}
-
-// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
-TEST(MatcherCastTest, FromSameType) {
-  Matcher<int> m1 = Eq(0);
-  Matcher<int> m2 = MatcherCast<int>(m1);
-  EXPECT_TRUE(m2.Matches(0));
-  EXPECT_FALSE(m2.Matches(1));
-}
-
-// Tests that MatcherCast<T>(m) works when m is a value of the same type as the
-// value type of the Matcher.
-TEST(MatcherCastTest, FromAValue) {
-  Matcher<int> m = MatcherCast<int>(42);
-  EXPECT_TRUE(m.Matches(42));
-  EXPECT_FALSE(m.Matches(239));
-}
-
-// Tests that MatcherCast<T>(m) works when m is a value of the type implicitly
-// convertible to the value type of the Matcher.
-TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {
-  const int kExpected = 'c';
-  Matcher<int> m = MatcherCast<int>('c');
-  EXPECT_TRUE(m.Matches(kExpected));
-  EXPECT_FALSE(m.Matches(kExpected + 1));
-}
-
-struct NonImplicitlyConstructibleTypeWithOperatorEq {
-  friend bool operator==(
-      const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */,
-      int rhs) {
-    return 42 == rhs;
-  }
-  friend bool operator==(
-      int lhs,
-      const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) {
-    return lhs == 42;
-  }
-};
-
-// Tests that MatcherCast<T>(m) works when m is a neither a matcher nor
-// implicitly convertible to the value type of the Matcher, but the value type
-// of the matcher has operator==() overload accepting m.
-TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {
-  Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 =
-      MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42);
-  EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
-
-  Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 =
-      MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239);
-  EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
-
-  // When updating the following lines please also change the comment to
-  // namespace convertible_from_any.
-  Matcher<int> m3 =
-      MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq());
-  EXPECT_TRUE(m3.Matches(42));
-  EXPECT_FALSE(m3.Matches(239));
-}
-
-// ConvertibleFromAny does not work with MSVC. resulting in
-// error C2440: 'initializing': cannot convert from 'Eq' to 'M'
-// No constructor could take the source type, or constructor overload
-// resolution was ambiguous
-
-#if !defined _MSC_VER
-
-// The below ConvertibleFromAny struct is implicitly constructible from anything
-// and when in the same namespace can interact with other tests. In particular,
-// if it is in the same namespace as other tests and one removes
-//   NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...);
-// then the corresponding test still compiles (and it should not!) by implicitly
-// converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny
-// in m3.Matcher().
-namespace convertible_from_any {
-// Implicitly convertible from any type.
-struct ConvertibleFromAny {
-  ConvertibleFromAny(int a_value) : value(a_value) {}
-  template <typename T>
-  ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
-    ADD_FAILURE() << "Conversion constructor called";
-  }
-  int value;
-};
-
-bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
-  return a.value == b.value;
-}
-
-ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
-  return os << a.value;
-}
-
-TEST(MatcherCastTest, ConversionConstructorIsUsed) {
-  Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
-  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
-  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
-}
-
-TEST(MatcherCastTest, FromConvertibleFromAny) {
-  Matcher<ConvertibleFromAny> m =
-      MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
-  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
-  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
-}
-}  // namespace convertible_from_any
-
-#endif  // !defined _MSC_VER
-
-struct IntReferenceWrapper {
-  IntReferenceWrapper(const int& a_value) : value(&a_value) {}
-  const int* value;
-};
-
-bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
-  return a.value == b.value;
-}
-
-TEST(MatcherCastTest, ValueIsNotCopied) {
-  int n = 42;
-  Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
-  // Verify that the matcher holds a reference to n, not to its temporary copy.
-  EXPECT_TRUE(m.Matches(n));
-}
-
-class Base {
- public:
-  virtual ~Base() {}
-  Base() {}
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
-};
-
-class Derived : public Base {
- public:
-  Derived() : Base() {}
-  int i;
-};
-
-class OtherDerived : public Base {};
-
-// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
-TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
-  Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
-  EXPECT_TRUE(m2.Matches(' '));
-  EXPECT_FALSE(m2.Matches('\n'));
-}
-
-// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
-// T and U are arithmetic types and T can be losslessly converted to
-// U.
-TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
-  Matcher<double> m1 = DoubleEq(1.0);
-  Matcher<float> m2 = SafeMatcherCast<float>(m1);
-  EXPECT_TRUE(m2.Matches(1.0f));
-  EXPECT_FALSE(m2.Matches(2.0f));
-
-  Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
-  EXPECT_TRUE(m3.Matches('a'));
-  EXPECT_FALSE(m3.Matches('b'));
-}
-
-// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
-// are pointers or references to a derived and a base class, correspondingly.
-TEST(SafeMatcherCastTest, FromBaseClass) {
-  Derived d, d2;
-  Matcher<Base*> m1 = Eq(&d);
-  Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
-  EXPECT_TRUE(m2.Matches(&d));
-  EXPECT_FALSE(m2.Matches(&d2));
-
-  Matcher<Base&> m3 = Ref(d);
-  Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
-  EXPECT_TRUE(m4.Matches(d));
-  EXPECT_FALSE(m4.Matches(d2));
-}
-
-// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
-TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
-  int n = 0;
-  Matcher<const int&> m1 = Ref(n);
-  Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
-  int n1 = 0;
-  EXPECT_TRUE(m2.Matches(n));
-  EXPECT_FALSE(m2.Matches(n1));
-}
-
-// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
-TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
-  Matcher<std::unique_ptr<int>> m1 = IsNull();
-  Matcher<const std::unique_ptr<int>&> m2 =
-      SafeMatcherCast<const std::unique_ptr<int>&>(m1);
-  EXPECT_TRUE(m2.Matches(std::unique_ptr<int>()));
-  EXPECT_FALSE(m2.Matches(std::unique_ptr<int>(new int)));
-}
-
-// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
-TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
-  Matcher<int> m1 = Eq(0);
-  Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
-  int n = 0;
-  EXPECT_TRUE(m2.Matches(n));
-  n = 1;
-  EXPECT_FALSE(m2.Matches(n));
-}
-
-// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
-TEST(SafeMatcherCastTest, FromSameType) {
-  Matcher<int> m1 = Eq(0);
-  Matcher<int> m2 = SafeMatcherCast<int>(m1);
-  EXPECT_TRUE(m2.Matches(0));
-  EXPECT_FALSE(m2.Matches(1));
-}
-
-#if !defined _MSC_VER
-
-namespace convertible_from_any {
-TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
-  Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
-  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
-  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
-}
-
-TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
-  Matcher<ConvertibleFromAny> m =
-      SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
-  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
-  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
-}
-}  // namespace convertible_from_any
-
-#endif  // !defined _MSC_VER
-
-TEST(SafeMatcherCastTest, ValueIsNotCopied) {
-  int n = 42;
-  Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
-  // Verify that the matcher holds a reference to n, not to its temporary copy.
-  EXPECT_TRUE(m.Matches(n));
-}
-
-TEST(ExpectThat, TakesLiterals) {
-  EXPECT_THAT(1, 1);
-  EXPECT_THAT(1.0, 1.0);
-  EXPECT_THAT(std::string(), "");
-}
-
-TEST(ExpectThat, TakesFunctions) {
-  struct Helper {
-    static void Func() {}
-  };
-  void (*func)() = Helper::Func;
-  EXPECT_THAT(func, Helper::Func);
-  EXPECT_THAT(func, &Helper::Func);
-}
-
-// Tests that A<T>() matches any value of type T.
-TEST(ATest, MatchesAnyValue) {
-  // Tests a matcher for a value type.
-  Matcher<double> m1 = A<double>();
-  EXPECT_TRUE(m1.Matches(91.43));
-  EXPECT_TRUE(m1.Matches(-15.32));
-
-  // Tests a matcher for a reference type.
-  int a = 2;
-  int b = -6;
-  Matcher<int&> m2 = A<int&>();
-  EXPECT_TRUE(m2.Matches(a));
-  EXPECT_TRUE(m2.Matches(b));
-}
-
-TEST(ATest, WorksForDerivedClass) {
-  Base base;
-  Derived derived;
-  EXPECT_THAT(&base, A<Base*>());
-  // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
-  EXPECT_THAT(&derived, A<Base*>());
-  EXPECT_THAT(&derived, A<Derived*>());
-}
-
-// Tests that A<T>() describes itself properly.
-TEST(ATest, CanDescribeSelf) {
-  EXPECT_EQ("is anything", Describe(A<bool>()));
-}
-
-// Tests that An<T>() matches any value of type T.
-TEST(AnTest, MatchesAnyValue) {
-  // Tests a matcher for a value type.
-  Matcher<int> m1 = An<int>();
-  EXPECT_TRUE(m1.Matches(9143));
-  EXPECT_TRUE(m1.Matches(-1532));
-
-  // Tests a matcher for a reference type.
-  int a = 2;
-  int b = -6;
-  Matcher<int&> m2 = An<int&>();
-  EXPECT_TRUE(m2.Matches(a));
-  EXPECT_TRUE(m2.Matches(b));
-}
-
-// Tests that An<T>() describes itself properly.
-TEST(AnTest, CanDescribeSelf) {
-  EXPECT_EQ("is anything", Describe(An<int>()));
-}
-
-// Tests that _ can be used as a matcher for any type and matches any
-// value of that type.
-TEST(UnderscoreTest, MatchesAnyValue) {
-  // Uses _ as a matcher for a value type.
-  Matcher<int> m1 = _;
-  EXPECT_TRUE(m1.Matches(123));
-  EXPECT_TRUE(m1.Matches(-242));
-
-  // Uses _ as a matcher for a reference type.
-  bool a = false;
-  const bool b = true;
-  Matcher<const bool&> m2 = _;
-  EXPECT_TRUE(m2.Matches(a));
-  EXPECT_TRUE(m2.Matches(b));
-}
-
-// Tests that _ describes itself properly.
-TEST(UnderscoreTest, CanDescribeSelf) {
-  Matcher<int> m = _;
-  EXPECT_EQ("is anything", Describe(m));
-}
-
-// Tests that Eq(x) matches any value equal to x.
-TEST(EqTest, MatchesEqualValue) {
-  // 2 C-strings with same content but different addresses.
-  const char a1[] = "hi";
-  const char a2[] = "hi";
-
-  Matcher<const char*> m1 = Eq(a1);
-  EXPECT_TRUE(m1.Matches(a1));
-  EXPECT_FALSE(m1.Matches(a2));
-}
-
-// Tests that Eq(v) describes itself properly.
-
-class Unprintable {
- public:
-  Unprintable() : c_('a') {}
-
-  bool operator==(const Unprintable& /* rhs */) const { return true; }
-  // -Wunused-private-field: dummy accessor for `c_`.
-  char dummy_c() { return c_; }
- private:
-  char c_;
-};
-
-TEST(EqTest, CanDescribeSelf) {
-  Matcher<Unprintable> m = Eq(Unprintable());
-  EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
-}
-
-// Tests that Eq(v) can be used to match any type that supports
-// comparing with type T, where T is v's type.
-TEST(EqTest, IsPolymorphic) {
-  Matcher<int> m1 = Eq(1);
-  EXPECT_TRUE(m1.Matches(1));
-  EXPECT_FALSE(m1.Matches(2));
-
-  Matcher<char> m2 = Eq(1);
-  EXPECT_TRUE(m2.Matches('\1'));
-  EXPECT_FALSE(m2.Matches('a'));
-}
-
-// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
-TEST(TypedEqTest, ChecksEqualityForGivenType) {
-  Matcher<char> m1 = TypedEq<char>('a');
-  EXPECT_TRUE(m1.Matches('a'));
-  EXPECT_FALSE(m1.Matches('b'));
-
-  Matcher<int> m2 = TypedEq<int>(6);
-  EXPECT_TRUE(m2.Matches(6));
-  EXPECT_FALSE(m2.Matches(7));
-}
-
-// Tests that TypedEq(v) describes itself properly.
-TEST(TypedEqTest, CanDescribeSelf) {
-  EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
-}
-
-// Tests that TypedEq<T>(v) has type Matcher<T>.
-
-// Type<T>::IsTypeOf(v) compiles if and only if the type of value v is T, where
-// T is a "bare" type (i.e. not in the form of const U or U&).  If v's type is
-// not T, the compiler will generate a message about "undefined reference".
-template <typename T>
-struct Type {
-  static bool IsTypeOf(const T& /* v */) { return true; }
-
-  template <typename T2>
-  static void IsTypeOf(T2 v);
-};
-
-TEST(TypedEqTest, HasSpecifiedType) {
-  // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
-  Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
-  Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
-}
-
-// Tests that Ge(v) matches anything >= v.
-TEST(GeTest, ImplementsGreaterThanOrEqual) {
-  Matcher<int> m1 = Ge(0);
-  EXPECT_TRUE(m1.Matches(1));
-  EXPECT_TRUE(m1.Matches(0));
-  EXPECT_FALSE(m1.Matches(-1));
-}
-
-// Tests that Ge(v) describes itself properly.
-TEST(GeTest, CanDescribeSelf) {
-  Matcher<int> m = Ge(5);
-  EXPECT_EQ("is >= 5", Describe(m));
-}
-
-// Tests that Gt(v) matches anything > v.
-TEST(GtTest, ImplementsGreaterThan) {
-  Matcher<double> m1 = Gt(0);
-  EXPECT_TRUE(m1.Matches(1.0));
-  EXPECT_FALSE(m1.Matches(0.0));
-  EXPECT_FALSE(m1.Matches(-1.0));
-}
-
-// Tests that Gt(v) describes itself properly.
-TEST(GtTest, CanDescribeSelf) {
-  Matcher<int> m = Gt(5);
-  EXPECT_EQ("is > 5", Describe(m));
-}
-
-// Tests that Le(v) matches anything <= v.
-TEST(LeTest, ImplementsLessThanOrEqual) {
-  Matcher<char> m1 = Le('b');
-  EXPECT_TRUE(m1.Matches('a'));
-  EXPECT_TRUE(m1.Matches('b'));
-  EXPECT_FALSE(m1.Matches('c'));
-}
-
-// Tests that Le(v) describes itself properly.
-TEST(LeTest, CanDescribeSelf) {
-  Matcher<int> m = Le(5);
-  EXPECT_EQ("is <= 5", Describe(m));
-}
-
-// Tests that Lt(v) matches anything < v.
-TEST(LtTest, ImplementsLessThan) {
-  Matcher<const std::string&> m1 = Lt("Hello");
-  EXPECT_TRUE(m1.Matches("Abc"));
-  EXPECT_FALSE(m1.Matches("Hello"));
-  EXPECT_FALSE(m1.Matches("Hello, world!"));
-}
-
-// Tests that Lt(v) describes itself properly.
-TEST(LtTest, CanDescribeSelf) {
-  Matcher<int> m = Lt(5);
-  EXPECT_EQ("is < 5", Describe(m));
-}
-
-// Tests that Ne(v) matches anything != v.
-TEST(NeTest, ImplementsNotEqual) {
-  Matcher<int> m1 = Ne(0);
-  EXPECT_TRUE(m1.Matches(1));
-  EXPECT_TRUE(m1.Matches(-1));
-  EXPECT_FALSE(m1.Matches(0));
-}
-
-// Tests that Ne(v) describes itself properly.
-TEST(NeTest, CanDescribeSelf) {
-  Matcher<int> m = Ne(5);
-  EXPECT_EQ("isn't equal to 5", Describe(m));
-}
-
-class MoveOnly {
- public:
-  explicit MoveOnly(int i) : i_(i) {}
-  MoveOnly(const MoveOnly&) = delete;
-  MoveOnly(MoveOnly&&) = default;
-  MoveOnly& operator=(const MoveOnly&) = delete;
-  MoveOnly& operator=(MoveOnly&&) = default;
-
-  bool operator==(const MoveOnly& other) const { return i_ == other.i_; }
-  bool operator!=(const MoveOnly& other) const { return i_ != other.i_; }
-  bool operator<(const MoveOnly& other) const { return i_ < other.i_; }
-  bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; }
-  bool operator>(const MoveOnly& other) const { return i_ > other.i_; }
-  bool operator>=(const MoveOnly& other) const { return i_ >= other.i_; }
-
- private:
-  int i_;
-};
-
-struct MoveHelper {
-  MOCK_METHOD1(Call, void(MoveOnly));
-};
-
-// Disable this test in VS 2015 (version 14), where it fails when SEH is enabled
-#if defined(_MSC_VER) && (_MSC_VER < 1910)
-TEST(ComparisonBaseTest, DISABLED_WorksWithMoveOnly) {
-#else
-TEST(ComparisonBaseTest, WorksWithMoveOnly) {
-#endif
-  MoveOnly m{0};
-  MoveHelper helper;
-
-  EXPECT_CALL(helper, Call(Eq(ByRef(m))));
-  helper.Call(MoveOnly(0));
-  EXPECT_CALL(helper, Call(Ne(ByRef(m))));
-  helper.Call(MoveOnly(1));
-  EXPECT_CALL(helper, Call(Le(ByRef(m))));
-  helper.Call(MoveOnly(0));
-  EXPECT_CALL(helper, Call(Lt(ByRef(m))));
-  helper.Call(MoveOnly(-1));
-  EXPECT_CALL(helper, Call(Ge(ByRef(m))));
-  helper.Call(MoveOnly(0));
-  EXPECT_CALL(helper, Call(Gt(ByRef(m))));
-  helper.Call(MoveOnly(1));
-}
-
-// Tests that IsNull() matches any NULL pointer of any type.
-TEST(IsNullTest, MatchesNullPointer) {
-  Matcher<int*> m1 = IsNull();
-  int* p1 = nullptr;
-  int n = 0;
-  EXPECT_TRUE(m1.Matches(p1));
-  EXPECT_FALSE(m1.Matches(&n));
-
-  Matcher<const char*> m2 = IsNull();
-  const char* p2 = nullptr;
-  EXPECT_TRUE(m2.Matches(p2));
-  EXPECT_FALSE(m2.Matches("hi"));
-
-  Matcher<void*> m3 = IsNull();
-  void* p3 = nullptr;
-  EXPECT_TRUE(m3.Matches(p3));
-  EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
-}
-
-TEST(IsNullTest, StdFunction) {
-  const Matcher<std::function<void()>> m = IsNull();
-
-  EXPECT_TRUE(m.Matches(std::function<void()>()));
-  EXPECT_FALSE(m.Matches([]{}));
-}
-
-// Tests that IsNull() describes itself properly.
-TEST(IsNullTest, CanDescribeSelf) {
-  Matcher<int*> m = IsNull();
-  EXPECT_EQ("is NULL", Describe(m));
-  EXPECT_EQ("isn't NULL", DescribeNegation(m));
-}
-
-// Tests that NotNull() matches any non-NULL pointer of any type.
-TEST(NotNullTest, MatchesNonNullPointer) {
-  Matcher<int*> m1 = NotNull();
-  int* p1 = nullptr;
-  int n = 0;
-  EXPECT_FALSE(m1.Matches(p1));
-  EXPECT_TRUE(m1.Matches(&n));
-
-  Matcher<const char*> m2 = NotNull();
-  const char* p2 = nullptr;
-  EXPECT_FALSE(m2.Matches(p2));
-  EXPECT_TRUE(m2.Matches("hi"));
-}
-
-TEST(NotNullTest, LinkedPtr) {
-  const Matcher<std::shared_ptr<int>> m = NotNull();
-  const std::shared_ptr<int> null_p;
-  const std::shared_ptr<int> non_null_p(new int);
-
-  EXPECT_FALSE(m.Matches(null_p));
-  EXPECT_TRUE(m.Matches(non_null_p));
-}
-
-TEST(NotNullTest, ReferenceToConstLinkedPtr) {
-  const Matcher<const std::shared_ptr<double>&> m = NotNull();
-  const std::shared_ptr<double> null_p;
-  const std::shared_ptr<double> non_null_p(new double);
-
-  EXPECT_FALSE(m.Matches(null_p));
-  EXPECT_TRUE(m.Matches(non_null_p));
-}
-
-TEST(NotNullTest, StdFunction) {
-  const Matcher<std::function<void()>> m = NotNull();
-
-  EXPECT_TRUE(m.Matches([]{}));
-  EXPECT_FALSE(m.Matches(std::function<void()>()));
-}
-
-// Tests that NotNull() describes itself properly.
-TEST(NotNullTest, CanDescribeSelf) {
-  Matcher<int*> m = NotNull();
-  EXPECT_EQ("isn't NULL", Describe(m));
-}
-
-// Tests that Ref(variable) matches an argument that references
-// 'variable'.
-TEST(RefTest, MatchesSameVariable) {
-  int a = 0;
-  int b = 0;
-  Matcher<int&> m = Ref(a);
-  EXPECT_TRUE(m.Matches(a));
-  EXPECT_FALSE(m.Matches(b));
-}
-
-// Tests that Ref(variable) describes itself properly.
-TEST(RefTest, CanDescribeSelf) {
-  int n = 5;
-  Matcher<int&> m = Ref(n);
-  stringstream ss;
-  ss << "references the variable @" << &n << " 5";
-  EXPECT_EQ(ss.str(), Describe(m));
-}
-
-// Test that Ref(non_const_varialbe) can be used as a matcher for a
-// const reference.
-TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
-  int a = 0;
-  int b = 0;
-  Matcher<const int&> m = Ref(a);
-  EXPECT_TRUE(m.Matches(a));
-  EXPECT_FALSE(m.Matches(b));
-}
-
-// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
-// used wherever Ref(base) can be used (Ref(derived) is a sub-type
-// of Ref(base), but not vice versa.
-
-TEST(RefTest, IsCovariant) {
-  Base base, base2;
-  Derived derived;
-  Matcher<const Base&> m1 = Ref(base);
-  EXPECT_TRUE(m1.Matches(base));
-  EXPECT_FALSE(m1.Matches(base2));
-  EXPECT_FALSE(m1.Matches(derived));
-
-  m1 = Ref(derived);
-  EXPECT_TRUE(m1.Matches(derived));
-  EXPECT_FALSE(m1.Matches(base));
-  EXPECT_FALSE(m1.Matches(base2));
-}
-
-TEST(RefTest, ExplainsResult) {
-  int n = 0;
-  EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
-              StartsWith("which is located @"));
-
-  int m = 0;
-  EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
-              StartsWith("which is located @"));
-}
-
-// Tests string comparison matchers.
-
-template <typename T = std::string>
-std::string FromStringLike(internal::StringLike<T> str) {
-  return std::string(str);
-}
-
-TEST(StringLike, TestConversions) {
-  EXPECT_EQ("foo", FromStringLike("foo"));
-  EXPECT_EQ("foo", FromStringLike(std::string("foo")));
-#if GTEST_INTERNAL_HAS_STRING_VIEW
-  EXPECT_EQ("foo", FromStringLike(internal::StringView("foo")));
-#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
-
-  // Non deducible types.
-  EXPECT_EQ("", FromStringLike({}));
-  EXPECT_EQ("foo", FromStringLike({'f', 'o', 'o'}));
-  const char buf[] = "foo";
-  EXPECT_EQ("foo", FromStringLike({buf, buf + 3}));
-}
-
-TEST(StrEqTest, MatchesEqualString) {
-  Matcher<const char*> m = StrEq(std::string("Hello"));
-  EXPECT_TRUE(m.Matches("Hello"));
-  EXPECT_FALSE(m.Matches("hello"));
-  EXPECT_FALSE(m.Matches(nullptr));
-
-  Matcher<const std::string&> m2 = StrEq("Hello");
-  EXPECT_TRUE(m2.Matches("Hello"));
-  EXPECT_FALSE(m2.Matches("Hi"));
-
-#if GTEST_INTERNAL_HAS_STRING_VIEW
-  Matcher<const internal::StringView&> m3 =
-      StrEq(internal::StringView("Hello"));
-  EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
-  EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
-  EXPECT_FALSE(m3.Matches(internal::StringView()));
-
-  Matcher<const internal::StringView&> m_empty = StrEq("");
-  EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
-  EXPECT_TRUE(m_empty.Matches(internal::StringView()));
-  EXPECT_FALSE(m_empty.Matches(internal::StringView("hello")));
-#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
-}
-
-TEST(StrEqTest, CanDescribeSelf) {
-  Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
-  EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
-      Describe(m));
-
-  std::string str("01204500800");
-  str[3] = '\0';
-  Matcher<std::string> m2 = StrEq(str);
-  EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
-  str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
-  Matcher<std::string> m3 = StrEq(str);
-  EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
-}
-
-TEST(StrNeTest, MatchesUnequalString) {
-  Matcher<const char*> m = StrNe("Hello");
-  EXPECT_TRUE(m.Matches(""));
-  EXPECT_TRUE(m.Matches(nullptr));
-  EXPECT_FALSE(m.Matches("Hello"));
-
-  Matcher<std::string> m2 = StrNe(std::string("Hello"));
-  EXPECT_TRUE(m2.Matches("hello"));
-  EXPECT_FALSE(m2.Matches("Hello"));
-
-#if GTEST_INTERNAL_HAS_STRING_VIEW
-  Matcher<const internal::StringView> m3 = StrNe(internal::StringView("Hello"));
-  EXPECT_TRUE(m3.Matches(internal::StringView("")));
-  EXPECT_TRUE(m3.Matches(internal::StringView()));
-  EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
-#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
-}
-
-TEST(StrNeTest, CanDescribeSelf) {
-  Matcher<const char*> m = StrNe("Hi");
-  EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
-}
-
-TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
-  Matcher<const char*> m = StrCaseEq(std::string("Hello"));
-  EXPECT_TRUE(m.Matches("Hello"));
-  EXPECT_TRUE(m.Matches("hello"));
-  EXPECT_FALSE(m.Matches("Hi"));
-  EXPECT_FALSE(m.Matches(nullptr));
-
-  Matcher<const std::string&> m2 = StrCaseEq("Hello");
-  EXPECT_TRUE(m2.Matches("hello"));
-  EXPECT_FALSE(m2.Matches("Hi"));
-
-#if GTEST_INTERNAL_HAS_STRING_VIEW
-  Matcher<const internal::StringView&> m3 =
-      StrCaseEq(internal::StringView("Hello"));
-  EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
-  EXPECT_TRUE(m3.Matches(internal::StringView("hello")));
-  EXPECT_FALSE(m3.Matches(internal::StringView("Hi")));
-  EXPECT_FALSE(m3.Matches(internal::StringView()));
-#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
-}
-
-TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
-  std::string str1("oabocdooeoo");
-  std::string str2("OABOCDOOEOO");
-  Matcher<const std::string&> m0 = StrCaseEq(str1);
-  EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
-
-  str1[3] = str2[3] = '\0';
-  Matcher<const std::string&> m1 = StrCaseEq(str1);
-  EXPECT_TRUE(m1.Matches(str2));
-
-  str1[0] = str1[6] = str1[7] = str1[10] = '\0';
-  str2[0] = str2[6] = str2[7] = str2[10] = '\0';
-  Matcher<const std::string&> m2 = StrCaseEq(str1);
-  str1[9] = str2[9] = '\0';
-  EXPECT_FALSE(m2.Matches(str2));
-
-  Matcher<const std::string&> m3 = StrCaseEq(str1);
-  EXPECT_TRUE(m3.Matches(str2));
-
-  EXPECT_FALSE(m3.Matches(str2 + "x"));
-  str2.append(1, '\0');
-  EXPECT_FALSE(m3.Matches(str2));
-  EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
-}
-
-TEST(StrCaseEqTest, CanDescribeSelf) {
-  Matcher<std::string> m = StrCaseEq("Hi");
-  EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
-}
-
-TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
-  Matcher<const char*> m = StrCaseNe("Hello");
-  EXPECT_TRUE(m.Matches("Hi"));
-  EXPECT_TRUE(m.Matches(nullptr));
-  EXPECT_FALSE(m.Matches("Hello"));
-  EXPECT_FALSE(m.Matches("hello"));
-
-  Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
-  EXPECT_TRUE(m2.Matches(""));
-  EXPECT_FALSE(m2.Matches("Hello"));
-
-#if GTEST_INTERNAL_HAS_STRING_VIEW
-  Matcher<const internal::StringView> m3 =
-      StrCaseNe(internal::StringView("Hello"));
-  EXPECT_TRUE(m3.Matches(internal::StringView("Hi")));
-  EXPECT_TRUE(m3.Matches(internal::StringView()));
-  EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
-  EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
-#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
-}
-
-TEST(StrCaseNeTest, CanDescribeSelf) {
-  Matcher<const char*> m = StrCaseNe("Hi");
-  EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
-}
-
-// Tests that HasSubstr() works for matching string-typed values.
-TEST(HasSubstrTest, WorksForStringClasses) {
-  const Matcher<std::string> m1 = HasSubstr("foo");
-  EXPECT_TRUE(m1.Matches(std::string("I love food.")));
-  EXPECT_FALSE(m1.Matches(std::string("tofo")));
-
-  const Matcher<const std::string&> m2 = HasSubstr("foo");
-  EXPECT_TRUE(m2.Matches(std::string("I love food.")));
-  EXPECT_FALSE(m2.Matches(std::string("tofo")));
-
-  const Matcher<std::string> m_empty = HasSubstr("");
-  EXPECT_TRUE(m_empty.Matches(std::string()));
-  EXPECT_TRUE(m_empty.Matches(std::string("not empty")));
-}
-
-// Tests that HasSubstr() works for matching C-string-typed values.
-TEST(HasSubstrTest, WorksForCStrings) {
-  const Matcher<char*> m1 = HasSubstr("foo");
-  EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
-  EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
-  EXPECT_FALSE(m1.Matches(nullptr));
-
-  const Matcher<const char*> m2 = HasSubstr("foo");
-  EXPECT_TRUE(m2.Matches("I love food."));
-  EXPECT_FALSE(m2.Matches("tofo"));
-  EXPECT_FALSE(m2.Matches(nullptr));
-
-  const Matcher<const char*> m_empty = HasSubstr("");
-  EXPECT_TRUE(m_empty.Matches("not empty"));
-  EXPECT_TRUE(m_empty.Matches(""));
-  EXPECT_FALSE(m_empty.Matches(nullptr));
-}
-
-#if GTEST_INTERNAL_HAS_STRING_VIEW
-// Tests that HasSubstr() works for matching StringView-typed values.
-TEST(HasSubstrTest, WorksForStringViewClasses) {
-  const Matcher<internal::StringView> m1 =
-      HasSubstr(internal::StringView("foo"));
-  EXPECT_TRUE(m1.Matches(internal::StringView("I love food.")));
-  EXPECT_FALSE(m1.Matches(internal::StringView("tofo")));
-  EXPECT_FALSE(m1.Matches(internal::StringView()));
-
-  const Matcher<const internal::StringView&> m2 = HasSubstr("foo");
-  EXPECT_TRUE(m2.Matches(internal::StringView("I love food.")));
-  EXPECT_FALSE(m2.Matches(internal::StringView("tofo")));
-  EXPECT_FALSE(m2.Matches(internal::StringView()));
-
-  const Matcher<const internal::StringView&> m3 = HasSubstr("");
-  EXPECT_TRUE(m3.Matches(internal::StringView("foo")));
-  EXPECT_TRUE(m3.Matches(internal::StringView("")));
-  EXPECT_TRUE(m3.Matches(internal::StringView()));
-}
-#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
-
-// Tests that HasSubstr(s) describes itself properly.
-TEST(HasSubstrTest, CanDescribeSelf) {
-  Matcher<std::string> m = HasSubstr("foo\n\"");
-  EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
-}
-
-TEST(KeyTest, CanDescribeSelf) {
-  Matcher<const pair<std::string, int>&> m = Key("foo");
-  EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
-  EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
-}
-
-TEST(KeyTest, ExplainsResult) {
-  Matcher<pair<int, bool> > m = Key(GreaterThan(10));
-  EXPECT_EQ("whose first field is a value which is 5 less than 10",
-            Explain(m, make_pair(5, true)));
-  EXPECT_EQ("whose first field is a value which is 5 more than 10",
-            Explain(m, make_pair(15, true)));
-}
-
-TEST(KeyTest, MatchesCorrectly) {
-  pair<int, std::string> p(25, "foo");
-  EXPECT_THAT(p, Key(25));
-  EXPECT_THAT(p, Not(Key(42)));
-  EXPECT_THAT(p, Key(Ge(20)));
-  EXPECT_THAT(p, Not(Key(Lt(25))));
-}
-
-TEST(KeyTest, WorksWithMoveOnly) {
-  pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
-  EXPECT_THAT(p, Key(Eq(nullptr)));
-}
-
-template <size_t I>
-struct Tag {};
-
-struct PairWithGet {
-  int member_1;
-  std::string member_2;
-  using first_type = int;
-  using second_type = std::string;
-
-  const int& GetImpl(Tag<0>) const { return member_1; }
-  const std::string& GetImpl(Tag<1>) const { return member_2; }
-};
-template <size_t I>
-auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) {
-  return value.GetImpl(Tag<I>());
-}
-TEST(PairTest, MatchesPairWithGetCorrectly) {
-  PairWithGet p{25, "foo"};
-  EXPECT_THAT(p, Key(25));
-  EXPECT_THAT(p, Not(Key(42)));
-  EXPECT_THAT(p, Key(Ge(20)));
-  EXPECT_THAT(p, Not(Key(Lt(25))));
-
-  std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
-  EXPECT_THAT(v, Contains(Key(29)));
-}
-
-TEST(KeyTest, SafelyCastsInnerMatcher) {
-  Matcher<int> is_positive = Gt(0);
-  Matcher<int> is_negative = Lt(0);
-  pair<char, bool> p('a', true);
-  EXPECT_THAT(p, Key(is_positive));
-  EXPECT_THAT(p, Not(Key(is_negative)));
-}
-
-TEST(KeyTest, InsideContainsUsingMap) {
-  map<int, char> container;
-  container.insert(make_pair(1, 'a'));
-  container.insert(make_pair(2, 'b'));
-  container.insert(make_pair(4, 'c'));
-  EXPECT_THAT(container, Contains(Key(1)));
-  EXPECT_THAT(container, Not(Contains(Key(3))));
-}
-
-TEST(KeyTest, InsideContainsUsingMultimap) {
-  multimap<int, char> container;
-  container.insert(make_pair(1, 'a'));
-  container.insert(make_pair(2, 'b'));
-  container.insert(make_pair(4, 'c'));
-
-  EXPECT_THAT(container, Not(Contains(Key(25))));
-  container.insert(make_pair(25, 'd'));
-  EXPECT_THAT(container, Contains(Key(25)));
-  container.insert(make_pair(25, 'e'));
-  EXPECT_THAT(container, Contains(Key(25)));
-
-  EXPECT_THAT(container, Contains(Key(1)));
-  EXPECT_THAT(container, Not(Contains(Key(3))));
-}
-
-TEST(PairTest, Typing) {
-  // Test verifies the following type conversions can be compiled.
-  Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
-  Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
-  Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
-
-  Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
-  Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
-}
-
-TEST(PairTest, CanDescribeSelf) {
-  Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
-  EXPECT_EQ("has a first field that is equal to \"foo\""
-            ", and has a second field that is equal to 42",
-            Describe(m1));
-  EXPECT_EQ("has a first field that isn't equal to \"foo\""
-            ", or has a second field that isn't equal to 42",
-            DescribeNegation(m1));
-  // Double and triple negation (1 or 2 times not and description of negation).
-  Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
-  EXPECT_EQ("has a first field that isn't equal to 13"
-            ", and has a second field that is equal to 42",
-            DescribeNegation(m2));
-}
-
-TEST(PairTest, CanExplainMatchResultTo) {
-  // If neither field matches, Pair() should explain about the first
-  // field.
-  const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
-  EXPECT_EQ("whose first field does not match, which is 1 less than 0",
-            Explain(m, make_pair(-1, -2)));
-
-  // If the first field matches but the second doesn't, Pair() should
-  // explain about the second field.
-  EXPECT_EQ("whose second field does not match, which is 2 less than 0",
-            Explain(m, make_pair(1, -2)));
-
-  // If the first field doesn't match but the second does, Pair()
-  // should explain about the first field.
-  EXPECT_EQ("whose first field does not match, which is 1 less than 0",
-            Explain(m, make_pair(-1, 2)));
-
-  // If both fields match, Pair() should explain about them both.
-  EXPECT_EQ("whose both fields match, where the first field is a value "
-            "which is 1 more than 0, and the second field is a value "
-            "which is 2 more than 0",
-            Explain(m, make_pair(1, 2)));
-
-  // If only the first match has an explanation, only this explanation should
-  // be printed.
-  const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
-  EXPECT_EQ("whose both fields match, where the first field is a value "
-            "which is 1 more than 0",
-            Explain(explain_first, make_pair(1, 0)));
-
-  // If only the second match has an explanation, only this explanation should
-  // be printed.
-  const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
-  EXPECT_EQ("whose both fields match, where the second field is a value "
-            "which is 1 more than 0",
-            Explain(explain_second, make_pair(0, 1)));
-}
-
-TEST(PairTest, MatchesCorrectly) {
-  pair<int, std::string> p(25, "foo");
-
-  // Both fields match.
-  EXPECT_THAT(p, Pair(25, "foo"));
-  EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
-
-  // 'first' doesnt' match, but 'second' matches.
-  EXPECT_THAT(p, Not(Pair(42, "foo")));
-  EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
-
-  // 'first' matches, but 'second' doesn't match.
-  EXPECT_THAT(p, Not(Pair(25, "bar")));
-  EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
-
-  // Neither field matches.
-  EXPECT_THAT(p, Not(Pair(13, "bar")));
-  EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
-}
-
-TEST(PairTest, WorksWithMoveOnly) {
-  pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
-  p.second.reset(new int(7));
-  EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));
-}
-
-TEST(PairTest, SafelyCastsInnerMatchers) {
-  Matcher<int> is_positive = Gt(0);
-  Matcher<int> is_negative = Lt(0);
-  pair<char, bool> p('a', true);
-  EXPECT_THAT(p, Pair(is_positive, _));
-  EXPECT_THAT(p, Not(Pair(is_negative, _)));
-  EXPECT_THAT(p, Pair(_, is_positive));
-  EXPECT_THAT(p, Not(Pair(_, is_negative)));
-}
-
-TEST(PairTest, InsideContainsUsingMap) {
-  map<int, char> container;
-  container.insert(make_pair(1, 'a'));
-  container.insert(make_pair(2, 'b'));
-  container.insert(make_pair(4, 'c'));
-  EXPECT_THAT(container, Contains(Pair(1, 'a')));
-  EXPECT_THAT(container, Contains(Pair(1, _)));
-  EXPECT_THAT(container, Contains(Pair(_, 'a')));
-  EXPECT_THAT(container, Not(Contains(Pair(3, _))));
-}
-
-TEST(FieldsAreTest, MatchesCorrectly) {
-  std::tuple<int, std::string, double> p(25, "foo", .5);
-
-  // All fields match.
-  EXPECT_THAT(p, FieldsAre(25, "foo", .5));
-  EXPECT_THAT(p, FieldsAre(Ge(20), HasSubstr("o"), DoubleEq(.5)));
-
-  // Some don't match.
-  EXPECT_THAT(p, Not(FieldsAre(26, "foo", .5)));
-  EXPECT_THAT(p, Not(FieldsAre(25, "fo", .5)));
-  EXPECT_THAT(p, Not(FieldsAre(25, "foo", .6)));
-}
-
-TEST(FieldsAreTest, CanDescribeSelf) {
-  Matcher<const pair<std::string, int>&> m1 = FieldsAre("foo", 42);
-  EXPECT_EQ(
-      "has field #0 that is equal to \"foo\""
-      ", and has field #1 that is equal to 42",
-      Describe(m1));
-  EXPECT_EQ(
-      "has field #0 that isn't equal to \"foo\""
-      ", or has field #1 that isn't equal to 42",
-      DescribeNegation(m1));
-}
-
-TEST(FieldsAreTest, CanExplainMatchResultTo) {
-  // The first one that fails is the one that gives the error.
-  Matcher<std::tuple<int, int, int>> m =
-      FieldsAre(GreaterThan(0), GreaterThan(0), GreaterThan(0));
-
-  EXPECT_EQ("whose field #0 does not match, which is 1 less than 0",
-            Explain(m, std::make_tuple(-1, -2, -3)));
-  EXPECT_EQ("whose field #1 does not match, which is 2 less than 0",
-            Explain(m, std::make_tuple(1, -2, -3)));
-  EXPECT_EQ("whose field #2 does not match, which is 3 less than 0",
-            Explain(m, std::make_tuple(1, 2, -3)));
-
-  // If they all match, we get a long explanation of success.
-  EXPECT_EQ(
-      "whose all elements match, "
-      "where field #0 is a value which is 1 more than 0"
-      ", and field #1 is a value which is 2 more than 0"
-      ", and field #2 is a value which is 3 more than 0",
-      Explain(m, std::make_tuple(1, 2, 3)));
-
-  // Only print those that have an explanation.
-  m = FieldsAre(GreaterThan(0), 0, GreaterThan(0));
-  EXPECT_EQ(
-      "whose all elements match, "
-      "where field #0 is a value which is 1 more than 0"
-      ", and field #2 is a value which is 3 more than 0",
-      Explain(m, std::make_tuple(1, 0, 3)));
-
-  // If only one has an explanation, then print that one.
-  m = FieldsAre(0, GreaterThan(0), 0);
-  EXPECT_EQ(
-      "whose all elements match, "
-      "where field #1 is a value which is 1 more than 0",
-      Explain(m, std::make_tuple(0, 1, 0)));
-}
-
-#if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
-TEST(FieldsAreTest, StructuredBindings) {
-  // testing::FieldsAre can also match aggregates and such with C++17 and up.
-  struct MyType {
-    int i;
-    std::string str;
-  };
-  EXPECT_THAT((MyType{17, "foo"}), FieldsAre(Eq(17), HasSubstr("oo")));
-
-  // Test all the supported arities.
-  struct MyVarType1 {
-    int a;
-  };
-  EXPECT_THAT(MyVarType1{}, FieldsAre(0));
-  struct MyVarType2 {
-    int a, b;
-  };
-  EXPECT_THAT(MyVarType2{}, FieldsAre(0, 0));
-  struct MyVarType3 {
-    int a, b, c;
-  };
-  EXPECT_THAT(MyVarType3{}, FieldsAre(0, 0, 0));
-  struct MyVarType4 {
-    int a, b, c, d;
-  };
-  EXPECT_THAT(MyVarType4{}, FieldsAre(0, 0, 0, 0));
-  struct MyVarType5 {
-    int a, b, c, d, e;
-  };
-  EXPECT_THAT(MyVarType5{}, FieldsAre(0, 0, 0, 0, 0));
-  struct MyVarType6 {
-    int a, b, c, d, e, f;
-  };
-  EXPECT_THAT(MyVarType6{}, FieldsAre(0, 0, 0, 0, 0, 0));
-  struct MyVarType7 {
-    int a, b, c, d, e, f, g;
-  };
-  EXPECT_THAT(MyVarType7{}, FieldsAre(0, 0, 0, 0, 0, 0, 0));
-  struct MyVarType8 {
-    int a, b, c, d, e, f, g, h;
-  };
-  EXPECT_THAT(MyVarType8{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0));
-  struct MyVarType9 {
-    int a, b, c, d, e, f, g, h, i;
-  };
-  EXPECT_THAT(MyVarType9{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0));
-  struct MyVarType10 {
-    int a, b, c, d, e, f, g, h, i, j;
-  };
-  EXPECT_THAT(MyVarType10{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
-  struct MyVarType11 {
-    int a, b, c, d, e, f, g, h, i, j, k;
-  };
-  EXPECT_THAT(MyVarType11{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
-  struct MyVarType12 {
-    int a, b, c, d, e, f, g, h, i, j, k, l;
-  };
-  EXPECT_THAT(MyVarType12{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
-  struct MyVarType13 {
-    int a, b, c, d, e, f, g, h, i, j, k, l, m;
-  };
-  EXPECT_THAT(MyVarType13{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
-  struct MyVarType14 {
-    int a, b, c, d, e, f, g, h, i, j, k, l, m, n;
-  };
-  EXPECT_THAT(MyVarType14{},
-              FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
-  struct MyVarType15 {
-    int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o;
-  };
-  EXPECT_THAT(MyVarType15{},
-              FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
-  struct MyVarType16 {
-    int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p;
-  };
-  EXPECT_THAT(MyVarType16{},
-              FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
-}
-#endif
-
-TEST(ContainsTest, WorksWithMoveOnly) {
-  ContainerHelper helper;
-  EXPECT_CALL(helper, Call(Contains(Pointee(2))));
-  helper.Call(MakeUniquePtrs({1, 2}));
-}
-
-TEST(PairTest, UseGetInsteadOfMembers) {
-  PairWithGet pair{7, "ABC"};
-  EXPECT_THAT(pair, Pair(7, "ABC"));
-  EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB")));
-  EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC")));
-
-  std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
-  EXPECT_THAT(v,
-              ElementsAre(Pair(11, std::string("Foo")), Pair(Ge(10), Not(""))));
-}
-
-// Tests StartsWith(s).
-
-TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
-  const Matcher<const char*> m1 = StartsWith(std::string(""));
-  EXPECT_TRUE(m1.Matches("Hi"));
-  EXPECT_TRUE(m1.Matches(""));
-  EXPECT_FALSE(m1.Matches(nullptr));
-
-  const Matcher<const std::string&> m2 = StartsWith("Hi");
-  EXPECT_TRUE(m2.Matches("Hi"));
-  EXPECT_TRUE(m2.Matches("Hi Hi!"));
-  EXPECT_TRUE(m2.Matches("High"));
-  EXPECT_FALSE(m2.Matches("H"));
-  EXPECT_FALSE(m2.Matches(" Hi"));
-
-#if GTEST_INTERNAL_HAS_STRING_VIEW
-  const Matcher<internal::StringView> m_empty =
-      StartsWith(internal::StringView(""));
-  EXPECT_TRUE(m_empty.Matches(internal::StringView()));
-  EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
-  EXPECT_TRUE(m_empty.Matches(internal::StringView("not empty")));
-#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
-}
-
-TEST(StartsWithTest, CanDescribeSelf) {
-  Matcher<const std::string> m = StartsWith("Hi");
-  EXPECT_EQ("starts with \"Hi\"", Describe(m));
-}
-
-// Tests EndsWith(s).
-
-TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
-  const Matcher<const char*> m1 = EndsWith("");
-  EXPECT_TRUE(m1.Matches("Hi"));
-  EXPECT_TRUE(m1.Matches(""));
-  EXPECT_FALSE(m1.Matches(nullptr));
-
-  const Matcher<const std::string&> m2 = EndsWith(std::string("Hi"));
-  EXPECT_TRUE(m2.Matches("Hi"));
-  EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
-  EXPECT_TRUE(m2.Matches("Super Hi"));
-  EXPECT_FALSE(m2.Matches("i"));
-  EXPECT_FALSE(m2.Matches("Hi "));
-
-#if GTEST_INTERNAL_HAS_STRING_VIEW
-  const Matcher<const internal::StringView&> m4 =
-      EndsWith(internal::StringView(""));
-  EXPECT_TRUE(m4.Matches("Hi"));
-  EXPECT_TRUE(m4.Matches(""));
-  EXPECT_TRUE(m4.Matches(internal::StringView()));
-  EXPECT_TRUE(m4.Matches(internal::StringView("")));
-#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
-}
-
-TEST(EndsWithTest, CanDescribeSelf) {
-  Matcher<const std::string> m = EndsWith("Hi");
-  EXPECT_EQ("ends with \"Hi\"", Describe(m));
-}
-
-// Tests MatchesRegex().
-
-TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
-  const Matcher<const char*> m1 = MatchesRegex("a.*z");
-  EXPECT_TRUE(m1.Matches("az"));
-  EXPECT_TRUE(m1.Matches("abcz"));
-  EXPECT_FALSE(m1.Matches(nullptr));
-
-  const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
-  EXPECT_TRUE(m2.Matches("azbz"));
-  EXPECT_FALSE(m2.Matches("az1"));
-  EXPECT_FALSE(m2.Matches("1az"));
-
-#if GTEST_INTERNAL_HAS_STRING_VIEW
-  const Matcher<const internal::StringView&> m3 = MatchesRegex("a.*z");
-  EXPECT_TRUE(m3.Matches(internal::StringView("az")));
-  EXPECT_TRUE(m3.Matches(internal::StringView("abcz")));
-  EXPECT_FALSE(m3.Matches(internal::StringView("1az")));
-  EXPECT_FALSE(m3.Matches(internal::StringView()));
-  const Matcher<const internal::StringView&> m4 =
-      MatchesRegex(internal::StringView(""));
-  EXPECT_TRUE(m4.Matches(internal::StringView("")));
-  EXPECT_TRUE(m4.Matches(internal::StringView()));
-#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
-}
-
-TEST(MatchesRegexTest, CanDescribeSelf) {
-  Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
-  EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
-
-  Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
-  EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
-
-#if GTEST_INTERNAL_HAS_STRING_VIEW
-  Matcher<const internal::StringView> m3 = MatchesRegex(new RE("0.*"));
-  EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
-#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
-}
-
-// Tests ContainsRegex().
-
-TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
-  const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
-  EXPECT_TRUE(m1.Matches("az"));
-  EXPECT_TRUE(m1.Matches("0abcz1"));
-  EXPECT_FALSE(m1.Matches(nullptr));
-
-  const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
-  EXPECT_TRUE(m2.Matches("azbz"));
-  EXPECT_TRUE(m2.Matches("az1"));
-  EXPECT_FALSE(m2.Matches("1a"));
-
-#if GTEST_INTERNAL_HAS_STRING_VIEW
-  const Matcher<const internal::StringView&> m3 =
-      ContainsRegex(new RE("a.*z"));
-  EXPECT_TRUE(m3.Matches(internal::StringView("azbz")));
-  EXPECT_TRUE(m3.Matches(internal::StringView("az1")));
-  EXPECT_FALSE(m3.Matches(internal::StringView("1a")));
-  EXPECT_FALSE(m3.Matches(internal::StringView()));
-  const Matcher<const internal::StringView&> m4 =
-      ContainsRegex(internal::StringView(""));
-  EXPECT_TRUE(m4.Matches(internal::StringView("")));
-  EXPECT_TRUE(m4.Matches(internal::StringView()));
-#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
-}
-
-TEST(ContainsRegexTest, CanDescribeSelf) {
-  Matcher<const std::string> m1 = ContainsRegex("Hi.*");
-  EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
-
-  Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
-  EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
-
-#if GTEST_INTERNAL_HAS_STRING_VIEW
-  Matcher<const internal::StringView> m3 = ContainsRegex(new RE("0.*"));
-  EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
-#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
-}
-
-// Tests for wide strings.
-#if GTEST_HAS_STD_WSTRING
-TEST(StdWideStrEqTest, MatchesEqual) {
-  Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
-  EXPECT_TRUE(m.Matches(L"Hello"));
-  EXPECT_FALSE(m.Matches(L"hello"));
-  EXPECT_FALSE(m.Matches(nullptr));
-
-  Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
-  EXPECT_TRUE(m2.Matches(L"Hello"));
-  EXPECT_FALSE(m2.Matches(L"Hi"));
-
-  Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
-  EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
-  EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
-
-  ::std::wstring str(L"01204500800");
-  str[3] = L'\0';
-  Matcher<const ::std::wstring&> m4 = StrEq(str);
-  EXPECT_TRUE(m4.Matches(str));
-  str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
-  Matcher<const ::std::wstring&> m5 = StrEq(str);
-  EXPECT_TRUE(m5.Matches(str));
-}
-
-TEST(StdWideStrEqTest, CanDescribeSelf) {
-  Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
-  EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
-    Describe(m));
-
-  Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
-  EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
-    Describe(m2));
-
-  ::std::wstring str(L"01204500800");
-  str[3] = L'\0';
-  Matcher<const ::std::wstring&> m4 = StrEq(str);
-  EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
-  str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
-  Matcher<const ::std::wstring&> m5 = StrEq(str);
-  EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
-}
-
-TEST(StdWideStrNeTest, MatchesUnequalString) {
-  Matcher<const wchar_t*> m = StrNe(L"Hello");
-  EXPECT_TRUE(m.Matches(L""));
-  EXPECT_TRUE(m.Matches(nullptr));
-  EXPECT_FALSE(m.Matches(L"Hello"));
-
-  Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
-  EXPECT_TRUE(m2.Matches(L"hello"));
-  EXPECT_FALSE(m2.Matches(L"Hello"));
-}
-
-TEST(StdWideStrNeTest, CanDescribeSelf) {
-  Matcher<const wchar_t*> m = StrNe(L"Hi");
-  EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
-}
-
-TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
-  Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
-  EXPECT_TRUE(m.Matches(L"Hello"));
-  EXPECT_TRUE(m.Matches(L"hello"));
-  EXPECT_FALSE(m.Matches(L"Hi"));
-  EXPECT_FALSE(m.Matches(nullptr));
-
-  Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
-  EXPECT_TRUE(m2.Matches(L"hello"));
-  EXPECT_FALSE(m2.Matches(L"Hi"));
-}
-
-TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
-  ::std::wstring str1(L"oabocdooeoo");
-  ::std::wstring str2(L"OABOCDOOEOO");
-  Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
-  EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
-
-  str1[3] = str2[3] = L'\0';
-  Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
-  EXPECT_TRUE(m1.Matches(str2));
-
-  str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
-  str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
-  Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
-  str1[9] = str2[9] = L'\0';
-  EXPECT_FALSE(m2.Matches(str2));
-
-  Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
-  EXPECT_TRUE(m3.Matches(str2));
-
-  EXPECT_FALSE(m3.Matches(str2 + L"x"));
-  str2.append(1, L'\0');
-  EXPECT_FALSE(m3.Matches(str2));
-  EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
-}
-
-TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
-  Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
-  EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
-}
-
-TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
-  Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
-  EXPECT_TRUE(m.Matches(L"Hi"));
-  EXPECT_TRUE(m.Matches(nullptr));
-  EXPECT_FALSE(m.Matches(L"Hello"));
-  EXPECT_FALSE(m.Matches(L"hello"));
-
-  Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
-  EXPECT_TRUE(m2.Matches(L""));
-  EXPECT_FALSE(m2.Matches(L"Hello"));
-}
-
-TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
-  Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
-  EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
-}
-
-// Tests that HasSubstr() works for matching wstring-typed values.
-TEST(StdWideHasSubstrTest, WorksForStringClasses) {
-  const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
-  EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
-  EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
-
-  const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
-  EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
-  EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
-}
-
-// Tests that HasSubstr() works for matching C-wide-string-typed values.
-TEST(StdWideHasSubstrTest, WorksForCStrings) {
-  const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
-  EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
-  EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
-  EXPECT_FALSE(m1.Matches(nullptr));
-
-  const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
-  EXPECT_TRUE(m2.Matches(L"I love food."));
-  EXPECT_FALSE(m2.Matches(L"tofo"));
-  EXPECT_FALSE(m2.Matches(nullptr));
-}
-
-// Tests that HasSubstr(s) describes itself properly.
-TEST(StdWideHasSubstrTest, CanDescribeSelf) {
-  Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
-  EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
-}
-
-// Tests StartsWith(s).
-
-TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
-  const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
-  EXPECT_TRUE(m1.Matches(L"Hi"));
-  EXPECT_TRUE(m1.Matches(L""));
-  EXPECT_FALSE(m1.Matches(nullptr));
-
-  const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
-  EXPECT_TRUE(m2.Matches(L"Hi"));
-  EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
-  EXPECT_TRUE(m2.Matches(L"High"));
-  EXPECT_FALSE(m2.Matches(L"H"));
-  EXPECT_FALSE(m2.Matches(L" Hi"));
-}
-
-TEST(StdWideStartsWithTest, CanDescribeSelf) {
-  Matcher<const ::std::wstring> m = StartsWith(L"Hi");
-  EXPECT_EQ("starts with L\"Hi\"", Describe(m));
-}
-
-// Tests EndsWith(s).
-
-TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
-  const Matcher<const wchar_t*> m1 = EndsWith(L"");
-  EXPECT_TRUE(m1.Matches(L"Hi"));
-  EXPECT_TRUE(m1.Matches(L""));
-  EXPECT_FALSE(m1.Matches(nullptr));
-
-  const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
-  EXPECT_TRUE(m2.Matches(L"Hi"));
-  EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
-  EXPECT_TRUE(m2.Matches(L"Super Hi"));
-  EXPECT_FALSE(m2.Matches(L"i"));
-  EXPECT_FALSE(m2.Matches(L"Hi "));
-}
-
-TEST(StdWideEndsWithTest, CanDescribeSelf) {
-  Matcher<const ::std::wstring> m = EndsWith(L"Hi");
-  EXPECT_EQ("ends with L\"Hi\"", Describe(m));
-}
-
-#endif  // GTEST_HAS_STD_WSTRING
-
-typedef ::std::tuple<long, int> Tuple2;  // NOLINT
-
-// Tests that Eq() matches a 2-tuple where the first field == the
-// second field.
-TEST(Eq2Test, MatchesEqualArguments) {
-  Matcher<const Tuple2&> m = Eq();
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
-  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
-}
-
-// Tests that Eq() describes itself properly.
-TEST(Eq2Test, CanDescribeSelf) {
-  Matcher<const Tuple2&> m = Eq();
-  EXPECT_EQ("are an equal pair", Describe(m));
-}
-
-// Tests that Ge() matches a 2-tuple where the first field >= the
-// second field.
-TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
-  Matcher<const Tuple2&> m = Ge();
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
-  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
-}
-
-// Tests that Ge() describes itself properly.
-TEST(Ge2Test, CanDescribeSelf) {
-  Matcher<const Tuple2&> m = Ge();
-  EXPECT_EQ("are a pair where the first >= the second", Describe(m));
-}
-
-// Tests that Gt() matches a 2-tuple where the first field > the
-// second field.
-TEST(Gt2Test, MatchesGreaterThanArguments) {
-  Matcher<const Tuple2&> m = Gt();
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
-  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
-  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
-}
-
-// Tests that Gt() describes itself properly.
-TEST(Gt2Test, CanDescribeSelf) {
-  Matcher<const Tuple2&> m = Gt();
-  EXPECT_EQ("are a pair where the first > the second", Describe(m));
-}
-
-// Tests that Le() matches a 2-tuple where the first field <= the
-// second field.
-TEST(Le2Test, MatchesLessThanOrEqualArguments) {
-  Matcher<const Tuple2&> m = Le();
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
-  EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
-}
-
-// Tests that Le() describes itself properly.
-TEST(Le2Test, CanDescribeSelf) {
-  Matcher<const Tuple2&> m = Le();
-  EXPECT_EQ("are a pair where the first <= the second", Describe(m));
-}
-
-// Tests that Lt() matches a 2-tuple where the first field < the
-// second field.
-TEST(Lt2Test, MatchesLessThanArguments) {
-  Matcher<const Tuple2&> m = Lt();
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
-  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
-  EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
-}
-
-// Tests that Lt() describes itself properly.
-TEST(Lt2Test, CanDescribeSelf) {
-  Matcher<const Tuple2&> m = Lt();
-  EXPECT_EQ("are a pair where the first < the second", Describe(m));
-}
-
-// Tests that Ne() matches a 2-tuple where the first field != the
-// second field.
-TEST(Ne2Test, MatchesUnequalArguments) {
-  Matcher<const Tuple2&> m = Ne();
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
-  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
-  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
-}
-
-// Tests that Ne() describes itself properly.
-TEST(Ne2Test, CanDescribeSelf) {
-  Matcher<const Tuple2&> m = Ne();
-  EXPECT_EQ("are an unequal pair", Describe(m));
-}
-
-TEST(PairMatchBaseTest, WorksWithMoveOnly) {
-  using Pointers = std::tuple<std::unique_ptr<int>, std::unique_ptr<int>>;
-  Matcher<Pointers> matcher = Eq();
-  Pointers pointers;
-  // Tested values don't matter; the point is that matcher does not copy the
-  // matched values.
-  EXPECT_TRUE(matcher.Matches(pointers));
-}
-
-// Tests that IsNan() matches a NaN, with float.
-TEST(IsNan, FloatMatchesNan) {
-  float quiet_nan = std::numeric_limits<float>::quiet_NaN();
-  float other_nan = std::nanf("1");
-  float real_value = 1.0f;
-
-  Matcher<float> m = IsNan();
-  EXPECT_TRUE(m.Matches(quiet_nan));
-  EXPECT_TRUE(m.Matches(other_nan));
-  EXPECT_FALSE(m.Matches(real_value));
-
-  Matcher<float&> m_ref = IsNan();
-  EXPECT_TRUE(m_ref.Matches(quiet_nan));
-  EXPECT_TRUE(m_ref.Matches(other_nan));
-  EXPECT_FALSE(m_ref.Matches(real_value));
-
-  Matcher<const float&> m_cref = IsNan();
-  EXPECT_TRUE(m_cref.Matches(quiet_nan));
-  EXPECT_TRUE(m_cref.Matches(other_nan));
-  EXPECT_FALSE(m_cref.Matches(real_value));
-}
-
-// Tests that IsNan() matches a NaN, with double.
-TEST(IsNan, DoubleMatchesNan) {
-  double quiet_nan = std::numeric_limits<double>::quiet_NaN();
-  double other_nan = std::nan("1");
-  double real_value = 1.0;
-
-  Matcher<double> m = IsNan();
-  EXPECT_TRUE(m.Matches(quiet_nan));
-  EXPECT_TRUE(m.Matches(other_nan));
-  EXPECT_FALSE(m.Matches(real_value));
-
-  Matcher<double&> m_ref = IsNan();
-  EXPECT_TRUE(m_ref.Matches(quiet_nan));
-  EXPECT_TRUE(m_ref.Matches(other_nan));
-  EXPECT_FALSE(m_ref.Matches(real_value));
-
-  Matcher<const double&> m_cref = IsNan();
-  EXPECT_TRUE(m_cref.Matches(quiet_nan));
-  EXPECT_TRUE(m_cref.Matches(other_nan));
-  EXPECT_FALSE(m_cref.Matches(real_value));
-}
-
-// Tests that IsNan() matches a NaN, with long double.
-TEST(IsNan, LongDoubleMatchesNan) {
-  long double quiet_nan = std::numeric_limits<long double>::quiet_NaN();
-  long double other_nan = std::nan("1");
-  long double real_value = 1.0;
-
-  Matcher<long double> m = IsNan();
-  EXPECT_TRUE(m.Matches(quiet_nan));
-  EXPECT_TRUE(m.Matches(other_nan));
-  EXPECT_FALSE(m.Matches(real_value));
-
-  Matcher<long double&> m_ref = IsNan();
-  EXPECT_TRUE(m_ref.Matches(quiet_nan));
-  EXPECT_TRUE(m_ref.Matches(other_nan));
-  EXPECT_FALSE(m_ref.Matches(real_value));
-
-  Matcher<const long double&> m_cref = IsNan();
-  EXPECT_TRUE(m_cref.Matches(quiet_nan));
-  EXPECT_TRUE(m_cref.Matches(other_nan));
-  EXPECT_FALSE(m_cref.Matches(real_value));
-}
-
-// Tests that IsNan() works with Not.
-TEST(IsNan, NotMatchesNan) {
-  Matcher<float> mf = Not(IsNan());
-  EXPECT_FALSE(mf.Matches(std::numeric_limits<float>::quiet_NaN()));
-  EXPECT_FALSE(mf.Matches(std::nanf("1")));
-  EXPECT_TRUE(mf.Matches(1.0));
-
-  Matcher<double> md = Not(IsNan());
-  EXPECT_FALSE(md.Matches(std::numeric_limits<double>::quiet_NaN()));
-  EXPECT_FALSE(md.Matches(std::nan("1")));
-  EXPECT_TRUE(md.Matches(1.0));
-
-  Matcher<long double> mld = Not(IsNan());
-  EXPECT_FALSE(mld.Matches(std::numeric_limits<long double>::quiet_NaN()));
-  EXPECT_FALSE(mld.Matches(std::nanl("1")));
-  EXPECT_TRUE(mld.Matches(1.0));
-}
-
-// Tests that IsNan() can describe itself.
-TEST(IsNan, CanDescribeSelf) {
-  Matcher<float> mf = IsNan();
-  EXPECT_EQ("is NaN", Describe(mf));
-
-  Matcher<double> md = IsNan();
-  EXPECT_EQ("is NaN", Describe(md));
-
-  Matcher<long double> mld = IsNan();
-  EXPECT_EQ("is NaN", Describe(mld));
-}
-
-// Tests that IsNan() can describe itself with Not.
-TEST(IsNan, CanDescribeSelfWithNot) {
-  Matcher<float> mf = Not(IsNan());
-  EXPECT_EQ("isn't NaN", Describe(mf));
-
-  Matcher<double> md = Not(IsNan());
-  EXPECT_EQ("isn't NaN", Describe(md));
-
-  Matcher<long double> mld = Not(IsNan());
-  EXPECT_EQ("isn't NaN", Describe(mld));
-}
-
-// Tests that FloatEq() matches a 2-tuple where
-// FloatEq(first field) matches the second field.
-TEST(FloatEq2Test, MatchesEqualArguments) {
-  typedef ::std::tuple<float, float> Tpl;
-  Matcher<const Tpl&> m = FloatEq();
-  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
-  EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f)));
-  EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
-}
-
-// Tests that FloatEq() describes itself properly.
-TEST(FloatEq2Test, CanDescribeSelf) {
-  Matcher<const ::std::tuple<float, float>&> m = FloatEq();
-  EXPECT_EQ("are an almost-equal pair", Describe(m));
-}
-
-// Tests that NanSensitiveFloatEq() matches a 2-tuple where
-// NanSensitiveFloatEq(first field) matches the second field.
-TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) {
-  typedef ::std::tuple<float, float> Tpl;
-  Matcher<const Tpl&> m = NanSensitiveFloatEq();
-  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
-  EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
-                            std::numeric_limits<float>::quiet_NaN())));
-  EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
-  EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
-  EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
-}
-
-// Tests that NanSensitiveFloatEq() describes itself properly.
-TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) {
-  Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatEq();
-  EXPECT_EQ("are an almost-equal pair", Describe(m));
-}
-
-// Tests that DoubleEq() matches a 2-tuple where
-// DoubleEq(first field) matches the second field.
-TEST(DoubleEq2Test, MatchesEqualArguments) {
-  typedef ::std::tuple<double, double> Tpl;
-  Matcher<const Tpl&> m = DoubleEq();
-  EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
-  EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1)));
-  EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0)));
-}
-
-// Tests that DoubleEq() describes itself properly.
-TEST(DoubleEq2Test, CanDescribeSelf) {
-  Matcher<const ::std::tuple<double, double>&> m = DoubleEq();
-  EXPECT_EQ("are an almost-equal pair", Describe(m));
-}
-
-// Tests that NanSensitiveDoubleEq() matches a 2-tuple where
-// NanSensitiveDoubleEq(first field) matches the second field.
-TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) {
-  typedef ::std::tuple<double, double> Tpl;
-  Matcher<const Tpl&> m = NanSensitiveDoubleEq();
-  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
-  EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
-                            std::numeric_limits<double>::quiet_NaN())));
-  EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
-  EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
-  EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
-}
-
-// Tests that DoubleEq() describes itself properly.
-TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) {
-  Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleEq();
-  EXPECT_EQ("are an almost-equal pair", Describe(m));
-}
-
-// Tests that FloatEq() matches a 2-tuple where
-// FloatNear(first field, max_abs_error) matches the second field.
-TEST(FloatNear2Test, MatchesEqualArguments) {
-  typedef ::std::tuple<float, float> Tpl;
-  Matcher<const Tpl&> m = FloatNear(0.5f);
-  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
-  EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f)));
-  EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f)));
-}
-
-// Tests that FloatNear() describes itself properly.
-TEST(FloatNear2Test, CanDescribeSelf) {
-  Matcher<const ::std::tuple<float, float>&> m = FloatNear(0.5f);
-  EXPECT_EQ("are an almost-equal pair", Describe(m));
-}
-
-// Tests that NanSensitiveFloatNear() matches a 2-tuple where
-// NanSensitiveFloatNear(first field) matches the second field.
-TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) {
-  typedef ::std::tuple<float, float> Tpl;
-  Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f);
-  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
-  EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
-  EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
-                            std::numeric_limits<float>::quiet_NaN())));
-  EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
-  EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
-  EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
-}
-
-// Tests that NanSensitiveFloatNear() describes itself properly.
-TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) {
-  Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatNear(0.5f);
-  EXPECT_EQ("are an almost-equal pair", Describe(m));
-}
-
-// Tests that FloatEq() matches a 2-tuple where
-// DoubleNear(first field, max_abs_error) matches the second field.
-TEST(DoubleNear2Test, MatchesEqualArguments) {
-  typedef ::std::tuple<double, double> Tpl;
-  Matcher<const Tpl&> m = DoubleNear(0.5);
-  EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
-  EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0)));
-  EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0)));
-}
-
-// Tests that DoubleNear() describes itself properly.
-TEST(DoubleNear2Test, CanDescribeSelf) {
-  Matcher<const ::std::tuple<double, double>&> m = DoubleNear(0.5);
-  EXPECT_EQ("are an almost-equal pair", Describe(m));
-}
-
-// Tests that NanSensitiveDoubleNear() matches a 2-tuple where
-// NanSensitiveDoubleNear(first field) matches the second field.
-TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) {
-  typedef ::std::tuple<double, double> Tpl;
-  Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f);
-  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
-  EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
-  EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
-                            std::numeric_limits<double>::quiet_NaN())));
-  EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
-  EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
-  EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
-}
-
-// Tests that NanSensitiveDoubleNear() describes itself properly.
-TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {
-  Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleNear(0.5f);
-  EXPECT_EQ("are an almost-equal pair", Describe(m));
-}
-
-// Tests that Not(m) matches any value that doesn't match m.
-TEST(NotTest, NegatesMatcher) {
-  Matcher<int> m;
-  m = Not(Eq(2));
-  EXPECT_TRUE(m.Matches(3));
-  EXPECT_FALSE(m.Matches(2));
-}
-
-// Tests that Not(m) describes itself properly.
-TEST(NotTest, CanDescribeSelf) {
-  Matcher<int> m = Not(Eq(5));
-  EXPECT_EQ("isn't equal to 5", Describe(m));
-}
-
-// Tests that monomorphic matchers are safely cast by the Not matcher.
-TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
-  // greater_than_5 is a monomorphic matcher.
-  Matcher<int> greater_than_5 = Gt(5);
-
-  Matcher<const int&> m = Not(greater_than_5);
-  Matcher<int&> m2 = Not(greater_than_5);
-  Matcher<int&> m3 = Not(m);
-}
-
-// Helper to allow easy testing of AllOf matchers with num parameters.
-void AllOfMatches(int num, const Matcher<int>& m) {
-  SCOPED_TRACE(Describe(m));
-  EXPECT_TRUE(m.Matches(0));
-  for (int i = 1; i <= num; ++i) {
-    EXPECT_FALSE(m.Matches(i));
-  }
-  EXPECT_TRUE(m.Matches(num + 1));
-}
-
-// Tests that AllOf(m1, ..., mn) matches any value that matches all of
-// the given matchers.
-TEST(AllOfTest, MatchesWhenAllMatch) {
-  Matcher<int> m;
-  m = AllOf(Le(2), Ge(1));
-  EXPECT_TRUE(m.Matches(1));
-  EXPECT_TRUE(m.Matches(2));
-  EXPECT_FALSE(m.Matches(0));
-  EXPECT_FALSE(m.Matches(3));
-
-  m = AllOf(Gt(0), Ne(1), Ne(2));
-  EXPECT_TRUE(m.Matches(3));
-  EXPECT_FALSE(m.Matches(2));
-  EXPECT_FALSE(m.Matches(1));
-  EXPECT_FALSE(m.Matches(0));
-
-  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
-  EXPECT_TRUE(m.Matches(4));
-  EXPECT_FALSE(m.Matches(3));
-  EXPECT_FALSE(m.Matches(2));
-  EXPECT_FALSE(m.Matches(1));
-  EXPECT_FALSE(m.Matches(0));
-
-  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
-  EXPECT_TRUE(m.Matches(0));
-  EXPECT_TRUE(m.Matches(1));
-  EXPECT_FALSE(m.Matches(3));
-
-  // The following tests for varying number of sub-matchers. Due to the way
-  // the sub-matchers are handled it is enough to test every sub-matcher once
-  // with sub-matchers using the same matcher type. Varying matcher types are
-  // checked for above.
-  AllOfMatches(2, AllOf(Ne(1), Ne(2)));
-  AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
-  AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
-  AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
-  AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
-  AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
-  AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
-                        Ne(8)));
-  AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
-                        Ne(8), Ne(9)));
-  AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
-                         Ne(9), Ne(10)));
-  AllOfMatches(
-      50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
-                Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17),
-                Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25),
-                Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33),
-                Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41),
-                Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
-                Ne(50)));
-}
-
-
-// Tests that AllOf(m1, ..., mn) describes itself properly.
-TEST(AllOfTest, CanDescribeSelf) {
-  Matcher<int> m;
-  m = AllOf(Le(2), Ge(1));
-  EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
-
-  m = AllOf(Gt(0), Ne(1), Ne(2));
-  std::string expected_descr1 =
-      "(is > 0) and (isn't equal to 1) and (isn't equal to 2)";
-  EXPECT_EQ(expected_descr1, Describe(m));
-
-  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
-  std::string expected_descr2 =
-      "(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal "
-      "to 3)";
-  EXPECT_EQ(expected_descr2, Describe(m));
-
-  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
-  std::string expected_descr3 =
-      "(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) "
-      "and (isn't equal to 7)";
-  EXPECT_EQ(expected_descr3, Describe(m));
-}
-
-// Tests that AllOf(m1, ..., mn) describes its negation properly.
-TEST(AllOfTest, CanDescribeNegation) {
-  Matcher<int> m;
-  m = AllOf(Le(2), Ge(1));
-  std::string expected_descr4 = "(isn't <= 2) or (isn't >= 1)";
-  EXPECT_EQ(expected_descr4, DescribeNegation(m));
-
-  m = AllOf(Gt(0), Ne(1), Ne(2));
-  std::string expected_descr5 =
-      "(isn't > 0) or (is equal to 1) or (is equal to 2)";
-  EXPECT_EQ(expected_descr5, DescribeNegation(m));
-
-  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
-  std::string expected_descr6 =
-      "(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)";
-  EXPECT_EQ(expected_descr6, DescribeNegation(m));
-
-  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
-  std::string expected_desr7 =
-      "(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or "
-      "(is equal to 7)";
-  EXPECT_EQ(expected_desr7, DescribeNegation(m));
-
-  m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
-            Ne(10), Ne(11));
-  AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
-  EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)"));
-  AllOfMatches(11, m);
-}
-
-// Tests that monomorphic matchers are safely cast by the AllOf matcher.
-TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
-  // greater_than_5 and less_than_10 are monomorphic matchers.
-  Matcher<int> greater_than_5 = Gt(5);
-  Matcher<int> less_than_10 = Lt(10);
-
-  Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
-  Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
-  Matcher<int&> m3 = AllOf(greater_than_5, m2);
-
-  // Tests that BothOf works when composing itself.
-  Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
-  Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
-}
-
-TEST(AllOfTest, ExplainsResult) {
-  Matcher<int> m;
-
-  // Successful match.  Both matchers need to explain.  The second
-  // matcher doesn't give an explanation, so only the first matcher's
-  // explanation is printed.
-  m = AllOf(GreaterThan(10), Lt(30));
-  EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
-
-  // Successful match.  Both matchers need to explain.
-  m = AllOf(GreaterThan(10), GreaterThan(20));
-  EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
-            Explain(m, 30));
-
-  // Successful match.  All matchers need to explain.  The second
-  // matcher doesn't given an explanation.
-  m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
-  EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
-            Explain(m, 25));
-
-  // Successful match.  All matchers need to explain.
-  m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
-  EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
-            "and which is 10 more than 30",
-            Explain(m, 40));
-
-  // Failed match.  The first matcher, which failed, needs to
-  // explain.
-  m = AllOf(GreaterThan(10), GreaterThan(20));
-  EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
-
-  // Failed match.  The second matcher, which failed, needs to
-  // explain.  Since it doesn't given an explanation, nothing is
-  // printed.
-  m = AllOf(GreaterThan(10), Lt(30));
-  EXPECT_EQ("", Explain(m, 40));
-
-  // Failed match.  The second matcher, which failed, needs to
-  // explain.
-  m = AllOf(GreaterThan(10), GreaterThan(20));
-  EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
-}
-
-// Helper to allow easy testing of AnyOf matchers with num parameters.
-static void AnyOfMatches(int num, const Matcher<int>& m) {
-  SCOPED_TRACE(Describe(m));
-  EXPECT_FALSE(m.Matches(0));
-  for (int i = 1; i <= num; ++i) {
-    EXPECT_TRUE(m.Matches(i));
-  }
-  EXPECT_FALSE(m.Matches(num + 1));
-}
-
-static void AnyOfStringMatches(int num, const Matcher<std::string>& m) {
-  SCOPED_TRACE(Describe(m));
-  EXPECT_FALSE(m.Matches(std::to_string(0)));
-
-  for (int i = 1; i <= num; ++i) {
-    EXPECT_TRUE(m.Matches(std::to_string(i)));
-  }
-  EXPECT_FALSE(m.Matches(std::to_string(num + 1)));
-}
-
-// Tests that AnyOf(m1, ..., mn) matches any value that matches at
-// least one of the given matchers.
-TEST(AnyOfTest, MatchesWhenAnyMatches) {
-  Matcher<int> m;
-  m = AnyOf(Le(1), Ge(3));
-  EXPECT_TRUE(m.Matches(1));
-  EXPECT_TRUE(m.Matches(4));
-  EXPECT_FALSE(m.Matches(2));
-
-  m = AnyOf(Lt(0), Eq(1), Eq(2));
-  EXPECT_TRUE(m.Matches(-1));
-  EXPECT_TRUE(m.Matches(1));
-  EXPECT_TRUE(m.Matches(2));
-  EXPECT_FALSE(m.Matches(0));
-
-  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
-  EXPECT_TRUE(m.Matches(-1));
-  EXPECT_TRUE(m.Matches(1));
-  EXPECT_TRUE(m.Matches(2));
-  EXPECT_TRUE(m.Matches(3));
-  EXPECT_FALSE(m.Matches(0));
-
-  m = AnyOf(Le(0), Gt(10), 3, 5, 7);
-  EXPECT_TRUE(m.Matches(0));
-  EXPECT_TRUE(m.Matches(11));
-  EXPECT_TRUE(m.Matches(3));
-  EXPECT_FALSE(m.Matches(2));
-
-  // The following tests for varying number of sub-matchers. Due to the way
-  // the sub-matchers are handled it is enough to test every sub-matcher once
-  // with sub-matchers using the same matcher type. Varying matcher types are
-  // checked for above.
-  AnyOfMatches(2, AnyOf(1, 2));
-  AnyOfMatches(3, AnyOf(1, 2, 3));
-  AnyOfMatches(4, AnyOf(1, 2, 3, 4));
-  AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
-  AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
-  AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
-  AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
-  AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
-  AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
-}
-
-// Tests the variadic version of the AnyOfMatcher.
-TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
-  // Also make sure AnyOf is defined in the right namespace and does not depend
-  // on ADL.
-  Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
-
-  EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)"));
-  AnyOfMatches(11, m);
-  AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
-                         11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
-                         21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
-                         31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
-                         41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
-  AnyOfStringMatches(
-      50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
-                "13", "14", "15", "16", "17", "18", "19", "20", "21", "22",
-                "23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
-                "33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
-                "43", "44", "45", "46", "47", "48", "49", "50"));
-}
-
-// Tests the variadic version of the ElementsAreMatcher
-TEST(ElementsAreTest, HugeMatcher) {
-  vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
-
-  EXPECT_THAT(test_vector,
-              ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
-                          Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
-}
-
-// Tests the variadic version of the UnorderedElementsAreMatcher
-TEST(ElementsAreTest, HugeMatcherStr) {
-  vector<std::string> test_vector{
-      "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
-
-  EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
-                                                _, _, _, _, _, _));
-}
-
-// Tests the variadic version of the UnorderedElementsAreMatcher
-TEST(ElementsAreTest, HugeMatcherUnordered) {
-  vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
-
-  EXPECT_THAT(test_vector, UnorderedElementsAre(
-                               Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
-                               Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
-}
-
-
-// Tests that AnyOf(m1, ..., mn) describes itself properly.
-TEST(AnyOfTest, CanDescribeSelf) {
-  Matcher<int> m;
-  m = AnyOf(Le(1), Ge(3));
-
-  EXPECT_EQ("(is <= 1) or (is >= 3)",
-            Describe(m));
-
-  m = AnyOf(Lt(0), Eq(1), Eq(2));
-  EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)", Describe(m));
-
-  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
-  EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)",
-            Describe(m));
-
-  m = AnyOf(Le(0), Gt(10), 3, 5, 7);
-  EXPECT_EQ(
-      "(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is "
-      "equal to 7)",
-      Describe(m));
-}
-
-// Tests that AnyOf(m1, ..., mn) describes its negation properly.
-TEST(AnyOfTest, CanDescribeNegation) {
-  Matcher<int> m;
-  m = AnyOf(Le(1), Ge(3));
-  EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
-            DescribeNegation(m));
-
-  m = AnyOf(Lt(0), Eq(1), Eq(2));
-  EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)",
-            DescribeNegation(m));
-
-  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
-  EXPECT_EQ(
-      "(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't "
-      "equal to 3)",
-      DescribeNegation(m));
-
-  m = AnyOf(Le(0), Gt(10), 3, 5, 7);
-  EXPECT_EQ(
-      "(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal "
-      "to 5) and (isn't equal to 7)",
-      DescribeNegation(m));
-}
-
-// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
-TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
-  // greater_than_5 and less_than_10 are monomorphic matchers.
-  Matcher<int> greater_than_5 = Gt(5);
-  Matcher<int> less_than_10 = Lt(10);
-
-  Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
-  Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
-  Matcher<int&> m3 = AnyOf(greater_than_5, m2);
-
-  // Tests that EitherOf works when composing itself.
-  Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
-  Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
-}
-
-TEST(AnyOfTest, ExplainsResult) {
-  Matcher<int> m;
-
-  // Failed match.  Both matchers need to explain.  The second
-  // matcher doesn't give an explanation, so only the first matcher's
-  // explanation is printed.
-  m = AnyOf(GreaterThan(10), Lt(0));
-  EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
-
-  // Failed match.  Both matchers need to explain.
-  m = AnyOf(GreaterThan(10), GreaterThan(20));
-  EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
-            Explain(m, 5));
-
-  // Failed match.  All matchers need to explain.  The second
-  // matcher doesn't given an explanation.
-  m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
-  EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
-            Explain(m, 5));
-
-  // Failed match.  All matchers need to explain.
-  m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
-  EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
-            "and which is 25 less than 30",
-            Explain(m, 5));
-
-  // Successful match.  The first matcher, which succeeded, needs to
-  // explain.
-  m = AnyOf(GreaterThan(10), GreaterThan(20));
-  EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
-
-  // Successful match.  The second matcher, which succeeded, needs to
-  // explain.  Since it doesn't given an explanation, nothing is
-  // printed.
-  m = AnyOf(GreaterThan(10), Lt(30));
-  EXPECT_EQ("", Explain(m, 0));
-
-  // Successful match.  The second matcher, which succeeded, needs to
-  // explain.
-  m = AnyOf(GreaterThan(30), GreaterThan(20));
-  EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
-}
-
-// The following predicate function and predicate functor are for
-// testing the Truly(predicate) matcher.
-
-// Returns non-zero if the input is positive.  Note that the return
-// type of this function is not bool.  It's OK as Truly() accepts any
-// unary function or functor whose return type can be implicitly
-// converted to bool.
-int IsPositive(double x) {
-  return x > 0 ? 1 : 0;
-}
-
-// This functor returns true if the input is greater than the given
-// number.
-class IsGreaterThan {
- public:
-  explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
-
-  bool operator()(int n) const { return n > threshold_; }
-
- private:
-  int threshold_;
-};
-
-// For testing Truly().
-const int foo = 0;
-
-// This predicate returns true if and only if the argument references foo and
-// has a zero value.
-bool ReferencesFooAndIsZero(const int& n) {
-  return (&n == &foo) && (n == 0);
-}
-
-// Tests that Truly(predicate) matches what satisfies the given
-// predicate.
-TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
-  Matcher<double> m = Truly(IsPositive);
-  EXPECT_TRUE(m.Matches(2.0));
-  EXPECT_FALSE(m.Matches(-1.5));
-}
-
-// Tests that Truly(predicate_functor) works too.
-TEST(TrulyTest, CanBeUsedWithFunctor) {
-  Matcher<int> m = Truly(IsGreaterThan(5));
-  EXPECT_TRUE(m.Matches(6));
-  EXPECT_FALSE(m.Matches(4));
-}
-
-// A class that can be implicitly converted to bool.
-class ConvertibleToBool {
- public:
-  explicit ConvertibleToBool(int number) : number_(number) {}
-  operator bool() const { return number_ != 0; }
-
- private:
-  int number_;
-};
-
-ConvertibleToBool IsNotZero(int number) {
-  return ConvertibleToBool(number);
-}
-
-// Tests that the predicate used in Truly() may return a class that's
-// implicitly convertible to bool, even when the class has no
-// operator!().
-TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
-  Matcher<int> m = Truly(IsNotZero);
-  EXPECT_TRUE(m.Matches(1));
-  EXPECT_FALSE(m.Matches(0));
-}
-
-// Tests that Truly(predicate) can describe itself properly.
-TEST(TrulyTest, CanDescribeSelf) {
-  Matcher<double> m = Truly(IsPositive);
-  EXPECT_EQ("satisfies the given predicate",
-            Describe(m));
-}
-
-// Tests that Truly(predicate) works when the matcher takes its
-// argument by reference.
-TEST(TrulyTest, WorksForByRefArguments) {
-  Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
-  EXPECT_TRUE(m.Matches(foo));
-  int n = 0;
-  EXPECT_FALSE(m.Matches(n));
-}
-
-// Tests that Truly(predicate) provides a helpful reason when it fails.
-TEST(TrulyTest, ExplainsFailures) {
-  StringMatchResultListener listener;
-  EXPECT_FALSE(ExplainMatchResult(Truly(IsPositive), -1, &listener));
-  EXPECT_EQ(listener.str(), "didn't satisfy the given predicate");
-}
-
-// Tests that Matches(m) is a predicate satisfied by whatever that
-// matches matcher m.
-TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
-  EXPECT_TRUE(Matches(Ge(0))(1));
-  EXPECT_FALSE(Matches(Eq('a'))('b'));
-}
-
-// Tests that Matches(m) works when the matcher takes its argument by
-// reference.
-TEST(MatchesTest, WorksOnByRefArguments) {
-  int m = 0, n = 0;
-  EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
-  EXPECT_FALSE(Matches(Ref(m))(n));
-}
-
-// Tests that a Matcher on non-reference type can be used in
-// Matches().
-TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
-  Matcher<int> eq5 = Eq(5);
-  EXPECT_TRUE(Matches(eq5)(5));
-  EXPECT_FALSE(Matches(eq5)(2));
-}
-
-// Tests Value(value, matcher).  Since Value() is a simple wrapper for
-// Matches(), which has been tested already, we don't spend a lot of
-// effort on testing Value().
-TEST(ValueTest, WorksWithPolymorphicMatcher) {
-  EXPECT_TRUE(Value("hi", StartsWith("h")));
-  EXPECT_FALSE(Value(5, Gt(10)));
-}
-
-TEST(ValueTest, WorksWithMonomorphicMatcher) {
-  const Matcher<int> is_zero = Eq(0);
-  EXPECT_TRUE(Value(0, is_zero));
-  EXPECT_FALSE(Value('a', is_zero));
-
-  int n = 0;
-  const Matcher<const int&> ref_n = Ref(n);
-  EXPECT_TRUE(Value(n, ref_n));
-  EXPECT_FALSE(Value(1, ref_n));
-}
-
-TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
-  StringMatchResultListener listener1;
-  EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
-  EXPECT_EQ("% 2 == 0", listener1.str());
-
-  StringMatchResultListener listener2;
-  EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
-  EXPECT_EQ("", listener2.str());
-}
-
-TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
-  const Matcher<int> is_even = PolymorphicIsEven();
-  StringMatchResultListener listener1;
-  EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
-  EXPECT_EQ("% 2 == 0", listener1.str());
-
-  const Matcher<const double&> is_zero = Eq(0);
-  StringMatchResultListener listener2;
-  EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
-  EXPECT_EQ("", listener2.str());
-}
-
-MATCHER(ConstructNoArg, "") { return true; }
-MATCHER_P(Construct1Arg, arg1, "") { return true; }
-MATCHER_P2(Construct2Args, arg1, arg2, "") { return true; }
-
-TEST(MatcherConstruct, ExplicitVsImplicit) {
-  {
-    // No arg constructor can be constructed with empty brace.
-    ConstructNoArgMatcher m = {};
-    (void)m;
-    // And with no args
-    ConstructNoArgMatcher m2;
-    (void)m2;
-  }
-  {
-    // The one arg constructor has an explicit constructor.
-    // This is to prevent the implicit conversion.
-    using M = Construct1ArgMatcherP<int>;
-    EXPECT_TRUE((std::is_constructible<M, int>::value));
-    EXPECT_FALSE((std::is_convertible<int, M>::value));
-  }
-  {
-    // Multiple arg matchers can be constructed with an implicit construction.
-    Construct2ArgsMatcherP2<int, double> m = {1, 2.2};
-    (void)m;
-  }
-}
-
-MATCHER_P(Really, inner_matcher, "") {
-  return ExplainMatchResult(inner_matcher, arg, result_listener);
-}
-
-TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
-  EXPECT_THAT(0, Really(Eq(0)));
-}
-
-TEST(DescribeMatcherTest, WorksWithValue) {
-  EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42));
-  EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true));
-}
-
-TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) {
-  const Matcher<int> monomorphic = Le(0);
-  EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic));
-  EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true));
-}
-
-TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {
-  EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven()));
-  EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true));
-}
-
-TEST(AllArgsTest, WorksForTuple) {
-  EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt()));
-  EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt())));
-}
-
-TEST(AllArgsTest, WorksForNonTuple) {
-  EXPECT_THAT(42, AllArgs(Gt(0)));
-  EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
-}
-
-class AllArgsHelper {
- public:
-  AllArgsHelper() {}
-
-  MOCK_METHOD2(Helper, int(char x, int y));
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
-};
-
-TEST(AllArgsTest, WorksInWithClause) {
-  AllArgsHelper helper;
-  ON_CALL(helper, Helper(_, _))
-      .With(AllArgs(Lt()))
-      .WillByDefault(Return(1));
-  EXPECT_CALL(helper, Helper(_, _));
-  EXPECT_CALL(helper, Helper(_, _))
-      .With(AllArgs(Gt()))
-      .WillOnce(Return(2));
-
-  EXPECT_EQ(1, helper.Helper('\1', 2));
-  EXPECT_EQ(2, helper.Helper('a', 1));
-}
-
-class OptionalMatchersHelper {
- public:
-  OptionalMatchersHelper() {}
-
-  MOCK_METHOD0(NoArgs, int());
-
-  MOCK_METHOD1(OneArg, int(int y));
-
-  MOCK_METHOD2(TwoArgs, int(char x, int y));
-
-  MOCK_METHOD1(Overloaded, int(char x));
-  MOCK_METHOD2(Overloaded, int(char x, int y));
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper);
-};
-
-TEST(AllArgsTest, WorksWithoutMatchers) {
-  OptionalMatchersHelper helper;
-
-  ON_CALL(helper, NoArgs).WillByDefault(Return(10));
-  ON_CALL(helper, OneArg).WillByDefault(Return(20));
-  ON_CALL(helper, TwoArgs).WillByDefault(Return(30));
-
-  EXPECT_EQ(10, helper.NoArgs());
-  EXPECT_EQ(20, helper.OneArg(1));
-  EXPECT_EQ(30, helper.TwoArgs('\1', 2));
-
-  EXPECT_CALL(helper, NoArgs).Times(1);
-  EXPECT_CALL(helper, OneArg).WillOnce(Return(100));
-  EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200));
-  EXPECT_CALL(helper, TwoArgs).Times(0);
-
-  EXPECT_EQ(10, helper.NoArgs());
-  EXPECT_EQ(100, helper.OneArg(1));
-  EXPECT_EQ(200, helper.OneArg(17));
-}
-
-// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
-// matches the matcher.
-TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
-  ASSERT_THAT(5, Ge(2)) << "This should succeed.";
-  ASSERT_THAT("Foo", EndsWith("oo"));
-  EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
-  EXPECT_THAT("Hello", StartsWith("Hell"));
-}
-
-// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
-// doesn't match the matcher.
-TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
-  // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
-  // which cannot reference auto variables.
-  static unsigned short n;  // NOLINT
-  n = 5;
-
-  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)),
-                       "Value of: n\n"
-                       "Expected: is > 10\n"
-                       "  Actual: 5" + OfType("unsigned short"));
-  n = 0;
-  EXPECT_NONFATAL_FAILURE(
-      EXPECT_THAT(n, AllOf(Le(7), Ge(5))),
-      "Value of: n\n"
-      "Expected: (is <= 7) and (is >= 5)\n"
-      "  Actual: 0" + OfType("unsigned short"));
-}
-
-// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
-// has a reference type.
-TEST(MatcherAssertionTest, WorksForByRefArguments) {
-  // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
-  // reference auto variables.
-  static int n;
-  n = 0;
-  EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
-  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
-                       "Value of: n\n"
-                       "Expected: does not reference the variable @");
-  // Tests the "Actual" part.
-  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
-                       "Actual: 0" + OfType("int") + ", which is located @");
-}
-
-// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
-// monomorphic.
-TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
-  Matcher<const char*> starts_with_he = StartsWith("he");
-  ASSERT_THAT("hello", starts_with_he);
-
-  Matcher<const std::string&> ends_with_ok = EndsWith("ok");
-  ASSERT_THAT("book", ends_with_ok);
-  const std::string bad = "bad";
-  EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
-                          "Value of: bad\n"
-                          "Expected: ends with \"ok\"\n"
-                          "  Actual: \"bad\"");
-  Matcher<int> is_greater_than_5 = Gt(5);
-  EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
-                          "Value of: 5\n"
-                          "Expected: is > 5\n"
-                          "  Actual: 5" + OfType("int"));
-}
-
-// Tests floating-point matchers.
-template <typename RawType>
-class FloatingPointTest : public testing::Test {
- protected:
-  typedef testing::internal::FloatingPoint<RawType> Floating;
-  typedef typename Floating::Bits Bits;
-
-  FloatingPointTest()
-      : max_ulps_(Floating::kMaxUlps),
-        zero_bits_(Floating(0).bits()),
-        one_bits_(Floating(1).bits()),
-        infinity_bits_(Floating(Floating::Infinity()).bits()),
-        close_to_positive_zero_(
-            Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
-        close_to_negative_zero_(
-            -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
-        further_from_negative_zero_(-Floating::ReinterpretBits(
-            zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
-        close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
-        further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
-        infinity_(Floating::Infinity()),
-        close_to_infinity_(
-            Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
-        further_from_infinity_(
-            Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
-        max_(Floating::Max()),
-        nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
-        nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
-  }
-
-  void TestSize() {
-    EXPECT_EQ(sizeof(RawType), sizeof(Bits));
-  }
-
-  // A battery of tests for FloatingEqMatcher::Matches.
-  // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
-  void TestMatches(
-      testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
-    Matcher<RawType> m1 = matcher_maker(0.0);
-    EXPECT_TRUE(m1.Matches(-0.0));
-    EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
-    EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
-    EXPECT_FALSE(m1.Matches(1.0));
-
-    Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
-    EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
-
-    Matcher<RawType> m3 = matcher_maker(1.0);
-    EXPECT_TRUE(m3.Matches(close_to_one_));
-    EXPECT_FALSE(m3.Matches(further_from_one_));
-
-    // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
-    EXPECT_FALSE(m3.Matches(0.0));
-
-    Matcher<RawType> m4 = matcher_maker(-infinity_);
-    EXPECT_TRUE(m4.Matches(-close_to_infinity_));
-
-    Matcher<RawType> m5 = matcher_maker(infinity_);
-    EXPECT_TRUE(m5.Matches(close_to_infinity_));
-
-    // This is interesting as the representations of infinity_ and nan1_
-    // are only 1 DLP apart.
-    EXPECT_FALSE(m5.Matches(nan1_));
-
-    // matcher_maker can produce a Matcher<const RawType&>, which is needed in
-    // some cases.
-    Matcher<const RawType&> m6 = matcher_maker(0.0);
-    EXPECT_TRUE(m6.Matches(-0.0));
-    EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
-    EXPECT_FALSE(m6.Matches(1.0));
-
-    // matcher_maker can produce a Matcher<RawType&>, which is needed in some
-    // cases.
-    Matcher<RawType&> m7 = matcher_maker(0.0);
-    RawType x = 0.0;
-    EXPECT_TRUE(m7.Matches(x));
-    x = 0.01f;
-    EXPECT_FALSE(m7.Matches(x));
-  }
-
-  // Pre-calculated numbers to be used by the tests.
-
-  const Bits max_ulps_;
-
-  const Bits zero_bits_;  // The bits that represent 0.0.
-  const Bits one_bits_;  // The bits that represent 1.0.
-  const Bits infinity_bits_;  // The bits that represent +infinity.
-
-  // Some numbers close to 0.0.
-  const RawType close_to_positive_zero_;
-  const RawType close_to_negative_zero_;
-  const RawType further_from_negative_zero_;
-
-  // Some numbers close to 1.0.
-  const RawType close_to_one_;
-  const RawType further_from_one_;
-
-  // Some numbers close to +infinity.
-  const RawType infinity_;
-  const RawType close_to_infinity_;
-  const RawType further_from_infinity_;
-
-  // Maximum representable value that's not infinity.
-  const RawType max_;
-
-  // Some NaNs.
-  const RawType nan1_;
-  const RawType nan2_;
-};
-
-// Tests floating-point matchers with fixed epsilons.
-template <typename RawType>
-class FloatingPointNearTest : public FloatingPointTest<RawType> {
- protected:
-  typedef FloatingPointTest<RawType> ParentType;
-
-  // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
-  // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
-  void TestNearMatches(
-      testing::internal::FloatingEqMatcher<RawType>
-          (*matcher_maker)(RawType, RawType)) {
-    Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
-    EXPECT_TRUE(m1.Matches(0.0));
-    EXPECT_TRUE(m1.Matches(-0.0));
-    EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
-    EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
-    EXPECT_FALSE(m1.Matches(1.0));
-
-    Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
-    EXPECT_TRUE(m2.Matches(0.0));
-    EXPECT_TRUE(m2.Matches(-0.0));
-    EXPECT_TRUE(m2.Matches(1.0));
-    EXPECT_TRUE(m2.Matches(-1.0));
-    EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
-    EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
-
-    // Check that inf matches inf, regardless of the of the specified max
-    // absolute error.
-    Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
-    EXPECT_TRUE(m3.Matches(ParentType::infinity_));
-    EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
-    EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
-
-    Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
-    EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
-    EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
-    EXPECT_FALSE(m4.Matches(ParentType::infinity_));
-
-    // Test various overflow scenarios.
-    Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
-    EXPECT_TRUE(m5.Matches(ParentType::max_));
-    EXPECT_FALSE(m5.Matches(-ParentType::max_));
-
-    Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
-    EXPECT_FALSE(m6.Matches(ParentType::max_));
-    EXPECT_TRUE(m6.Matches(-ParentType::max_));
-
-    Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
-    EXPECT_TRUE(m7.Matches(ParentType::max_));
-    EXPECT_FALSE(m7.Matches(-ParentType::max_));
-
-    Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
-    EXPECT_FALSE(m8.Matches(ParentType::max_));
-    EXPECT_TRUE(m8.Matches(-ParentType::max_));
-
-    // The difference between max() and -max() normally overflows to infinity,
-    // but it should still match if the max_abs_error is also infinity.
-    Matcher<RawType> m9 = matcher_maker(
-        ParentType::max_, ParentType::infinity_);
-    EXPECT_TRUE(m8.Matches(-ParentType::max_));
-
-    // matcher_maker can produce a Matcher<const RawType&>, which is needed in
-    // some cases.
-    Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
-    EXPECT_TRUE(m10.Matches(-0.0));
-    EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
-    EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
-
-    // matcher_maker can produce a Matcher<RawType&>, which is needed in some
-    // cases.
-    Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
-    RawType x = 0.0;
-    EXPECT_TRUE(m11.Matches(x));
-    x = 1.0f;
-    EXPECT_TRUE(m11.Matches(x));
-    x = -1.0f;
-    EXPECT_TRUE(m11.Matches(x));
-    x = 1.1f;
-    EXPECT_FALSE(m11.Matches(x));
-    x = -1.1f;
-    EXPECT_FALSE(m11.Matches(x));
-  }
-};
-
-// Instantiate FloatingPointTest for testing floats.
-typedef FloatingPointTest<float> FloatTest;
-
-TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
-  TestMatches(&FloatEq);
-}
-
-TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
-  TestMatches(&NanSensitiveFloatEq);
-}
-
-TEST_F(FloatTest, FloatEqCannotMatchNaN) {
-  // FloatEq never matches NaN.
-  Matcher<float> m = FloatEq(nan1_);
-  EXPECT_FALSE(m.Matches(nan1_));
-  EXPECT_FALSE(m.Matches(nan2_));
-  EXPECT_FALSE(m.Matches(1.0));
-}
-
-TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
-  // NanSensitiveFloatEq will match NaN.
-  Matcher<float> m = NanSensitiveFloatEq(nan1_);
-  EXPECT_TRUE(m.Matches(nan1_));
-  EXPECT_TRUE(m.Matches(nan2_));
-  EXPECT_FALSE(m.Matches(1.0));
-}
-
-TEST_F(FloatTest, FloatEqCanDescribeSelf) {
-  Matcher<float> m1 = FloatEq(2.0f);
-  EXPECT_EQ("is approximately 2", Describe(m1));
-  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
-
-  Matcher<float> m2 = FloatEq(0.5f);
-  EXPECT_EQ("is approximately 0.5", Describe(m2));
-  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
-
-  Matcher<float> m3 = FloatEq(nan1_);
-  EXPECT_EQ("never matches", Describe(m3));
-  EXPECT_EQ("is anything", DescribeNegation(m3));
-}
-
-TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
-  Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
-  EXPECT_EQ("is approximately 2", Describe(m1));
-  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
-
-  Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
-  EXPECT_EQ("is approximately 0.5", Describe(m2));
-  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
-
-  Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
-  EXPECT_EQ("is NaN", Describe(m3));
-  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
-}
-
-// Instantiate FloatingPointTest for testing floats with a user-specified
-// max absolute error.
-typedef FloatingPointNearTest<float> FloatNearTest;
-
-TEST_F(FloatNearTest, FloatNearMatches) {
-  TestNearMatches(&FloatNear);
-}
-
-TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
-  TestNearMatches(&NanSensitiveFloatNear);
-}
-
-TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
-  Matcher<float> m1 = FloatNear(2.0f, 0.5f);
-  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
-  EXPECT_EQ(
-      "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
-
-  Matcher<float> m2 = FloatNear(0.5f, 0.5f);
-  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
-  EXPECT_EQ(
-      "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
-
-  Matcher<float> m3 = FloatNear(nan1_, 0.0);
-  EXPECT_EQ("never matches", Describe(m3));
-  EXPECT_EQ("is anything", DescribeNegation(m3));
-}
-
-TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
-  Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
-  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
-  EXPECT_EQ(
-      "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
-
-  Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
-  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
-  EXPECT_EQ(
-      "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
-
-  Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
-  EXPECT_EQ("is NaN", Describe(m3));
-  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
-}
-
-TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
-  // FloatNear never matches NaN.
-  Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
-  EXPECT_FALSE(m.Matches(nan1_));
-  EXPECT_FALSE(m.Matches(nan2_));
-  EXPECT_FALSE(m.Matches(1.0));
-}
-
-TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
-  // NanSensitiveFloatNear will match NaN.
-  Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
-  EXPECT_TRUE(m.Matches(nan1_));
-  EXPECT_TRUE(m.Matches(nan2_));
-  EXPECT_FALSE(m.Matches(1.0));
-}
-
-// Instantiate FloatingPointTest for testing doubles.
-typedef FloatingPointTest<double> DoubleTest;
-
-TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
-  TestMatches(&DoubleEq);
-}
-
-TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
-  TestMatches(&NanSensitiveDoubleEq);
-}
-
-TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
-  // DoubleEq never matches NaN.
-  Matcher<double> m = DoubleEq(nan1_);
-  EXPECT_FALSE(m.Matches(nan1_));
-  EXPECT_FALSE(m.Matches(nan2_));
-  EXPECT_FALSE(m.Matches(1.0));
-}
-
-TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
-  // NanSensitiveDoubleEq will match NaN.
-  Matcher<double> m = NanSensitiveDoubleEq(nan1_);
-  EXPECT_TRUE(m.Matches(nan1_));
-  EXPECT_TRUE(m.Matches(nan2_));
-  EXPECT_FALSE(m.Matches(1.0));
-}
-
-TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
-  Matcher<double> m1 = DoubleEq(2.0);
-  EXPECT_EQ("is approximately 2", Describe(m1));
-  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
-
-  Matcher<double> m2 = DoubleEq(0.5);
-  EXPECT_EQ("is approximately 0.5", Describe(m2));
-  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
-
-  Matcher<double> m3 = DoubleEq(nan1_);
-  EXPECT_EQ("never matches", Describe(m3));
-  EXPECT_EQ("is anything", DescribeNegation(m3));
-}
-
-TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
-  Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
-  EXPECT_EQ("is approximately 2", Describe(m1));
-  EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
-
-  Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
-  EXPECT_EQ("is approximately 0.5", Describe(m2));
-  EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
-
-  Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
-  EXPECT_EQ("is NaN", Describe(m3));
-  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
-}
-
-// Instantiate FloatingPointTest for testing floats with a user-specified
-// max absolute error.
-typedef FloatingPointNearTest<double> DoubleNearTest;
-
-TEST_F(DoubleNearTest, DoubleNearMatches) {
-  TestNearMatches(&DoubleNear);
-}
-
-TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
-  TestNearMatches(&NanSensitiveDoubleNear);
-}
-
-TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
-  Matcher<double> m1 = DoubleNear(2.0, 0.5);
-  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
-  EXPECT_EQ(
-      "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
-
-  Matcher<double> m2 = DoubleNear(0.5, 0.5);
-  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
-  EXPECT_EQ(
-      "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
-
-  Matcher<double> m3 = DoubleNear(nan1_, 0.0);
-  EXPECT_EQ("never matches", Describe(m3));
-  EXPECT_EQ("is anything", DescribeNegation(m3));
-}
-
-TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
-  EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
-  EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
-  EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
-
-  const std::string explanation =
-      Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
-  // Different C++ implementations may print floating-point numbers
-  // slightly differently.
-  EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" ||  // GCC
-              explanation == "which is 1.2e-010 from 2.1")   // MSVC
-      << " where explanation is \"" << explanation << "\".";
-}
-
-TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
-  Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
-  EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
-  EXPECT_EQ(
-      "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
-
-  Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
-  EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
-  EXPECT_EQ(
-      "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
-
-  Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
-  EXPECT_EQ("is NaN", Describe(m3));
-  EXPECT_EQ("isn't NaN", DescribeNegation(m3));
-}
-
-TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
-  // DoubleNear never matches NaN.
-  Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
-  EXPECT_FALSE(m.Matches(nan1_));
-  EXPECT_FALSE(m.Matches(nan2_));
-  EXPECT_FALSE(m.Matches(1.0));
-}
-
-TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
-  // NanSensitiveDoubleNear will match NaN.
-  Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
-  EXPECT_TRUE(m.Matches(nan1_));
-  EXPECT_TRUE(m.Matches(nan2_));
-  EXPECT_FALSE(m.Matches(1.0));
-}
-
-TEST(PointeeTest, RawPointer) {
-  const Matcher<int*> m = Pointee(Ge(0));
-
-  int n = 1;
-  EXPECT_TRUE(m.Matches(&n));
-  n = -1;
-  EXPECT_FALSE(m.Matches(&n));
-  EXPECT_FALSE(m.Matches(nullptr));
-}
-
-TEST(PointeeTest, RawPointerToConst) {
-  const Matcher<const double*> m = Pointee(Ge(0));
-
-  double x = 1;
-  EXPECT_TRUE(m.Matches(&x));
-  x = -1;
-  EXPECT_FALSE(m.Matches(&x));
-  EXPECT_FALSE(m.Matches(nullptr));
-}
-
-TEST(PointeeTest, ReferenceToConstRawPointer) {
-  const Matcher<int* const &> m = Pointee(Ge(0));
-
-  int n = 1;
-  EXPECT_TRUE(m.Matches(&n));
-  n = -1;
-  EXPECT_FALSE(m.Matches(&n));
-  EXPECT_FALSE(m.Matches(nullptr));
-}
-
-TEST(PointeeTest, ReferenceToNonConstRawPointer) {
-  const Matcher<double* &> m = Pointee(Ge(0));
-
-  double x = 1.0;
-  double* p = &x;
-  EXPECT_TRUE(m.Matches(p));
-  x = -1;
-  EXPECT_FALSE(m.Matches(p));
-  p = nullptr;
-  EXPECT_FALSE(m.Matches(p));
-}
-
-TEST(PointeeTest, SmartPointer) {
-  const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));
-
-  std::unique_ptr<int> n(new int(1));
-  EXPECT_TRUE(m.Matches(n));
-}
-
-TEST(PointeeTest, SmartPointerToConst) {
-  const Matcher<std::unique_ptr<const int>> m = Pointee(Ge(0));
-
-  // There's no implicit conversion from unique_ptr<int> to const
-  // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
-  // matcher.
-  std::unique_ptr<const int> n(new int(1));
-  EXPECT_TRUE(m.Matches(n));
-}
-
-TEST(PointerTest, RawPointer) {
-  int n = 1;
-  const Matcher<int*> m = Pointer(Eq(&n));
-
-  EXPECT_TRUE(m.Matches(&n));
-
-  int* p = nullptr;
-  EXPECT_FALSE(m.Matches(p));
-  EXPECT_FALSE(m.Matches(nullptr));
-}
-
-TEST(PointerTest, RawPointerToConst) {
-  int n = 1;
-  const Matcher<const int*> m = Pointer(Eq(&n));
-
-  EXPECT_TRUE(m.Matches(&n));
-
-  int* p = nullptr;
-  EXPECT_FALSE(m.Matches(p));
-  EXPECT_FALSE(m.Matches(nullptr));
-}
-
-TEST(PointerTest, SmartPointer) {
-  std::unique_ptr<int> n(new int(10));
-  int* raw_n = n.get();
-  const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n));
-
-  EXPECT_TRUE(m.Matches(n));
-}
-
-TEST(PointerTest, SmartPointerToConst) {
-  std::unique_ptr<const int> n(new int(10));
-  const int* raw_n = n.get();
-  const Matcher<std::unique_ptr<const int>> m = Pointer(Eq(raw_n));
-
-  // There's no implicit conversion from unique_ptr<int> to const
-  // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
-  // matcher.
-  std::unique_ptr<const int> p(new int(10));
-  EXPECT_FALSE(m.Matches(p));
-}
-
-TEST(AddressTest, NonConst) {
-  int n = 1;
-  const Matcher<int> m = Address(Eq(&n));
-
-  EXPECT_TRUE(m.Matches(n));
-
-  int other = 5;
-
-  EXPECT_FALSE(m.Matches(other));
-
-  int& n_ref = n;
-
-  EXPECT_TRUE(m.Matches(n_ref));
-}
-
-TEST(AddressTest, Const) {
-  const int n = 1;
-  const Matcher<int> m = Address(Eq(&n));
-
-  EXPECT_TRUE(m.Matches(n));
-
-  int other = 5;
-
-  EXPECT_FALSE(m.Matches(other));
-}
-
-TEST(AddressTest, MatcherDoesntCopy) {
-  std::unique_ptr<int> n(new int(1));
-  const Matcher<std::unique_ptr<int>> m = Address(Eq(&n));
-
-  EXPECT_TRUE(m.Matches(n));
-}
-
-TEST(AddressTest, Describe) {
-  Matcher<int> matcher = Address(_);
-  EXPECT_EQ("has address that is anything", Describe(matcher));
-  EXPECT_EQ("does not have address that is anything",
-            DescribeNegation(matcher));
-}
-
-MATCHER_P(FieldIIs, inner_matcher, "") {
-  return ExplainMatchResult(inner_matcher, arg.i, result_listener);
-}
-
-#if GTEST_HAS_RTTI
-TEST(WhenDynamicCastToTest, SameType) {
-  Derived derived;
-  derived.i = 4;
-
-  // Right type. A pointer is passed down.
-  Base* as_base_ptr = &derived;
-  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
-  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
-  EXPECT_THAT(as_base_ptr,
-              Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
-}
-
-TEST(WhenDynamicCastToTest, WrongTypes) {
-  Base base;
-  Derived derived;
-  OtherDerived other_derived;
-
-  // Wrong types. NULL is passed.
-  EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
-  EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
-  Base* as_base_ptr = &derived;
-  EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
-  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
-  as_base_ptr = &other_derived;
-  EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
-  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
-}
-
-TEST(WhenDynamicCastToTest, AlreadyNull) {
-  // Already NULL.
-  Base* as_base_ptr = nullptr;
-  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
-}
-
-struct AmbiguousCastTypes {
-  class VirtualDerived : public virtual Base {};
-  class DerivedSub1 : public VirtualDerived {};
-  class DerivedSub2 : public VirtualDerived {};
-  class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
-};
-
-TEST(WhenDynamicCastToTest, AmbiguousCast) {
-  AmbiguousCastTypes::DerivedSub1 sub1;
-  AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
-  // Multiply derived from Base. dynamic_cast<> returns NULL.
-  Base* as_base_ptr =
-      static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
-  EXPECT_THAT(as_base_ptr,
-              WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
-  as_base_ptr = &sub1;
-  EXPECT_THAT(
-      as_base_ptr,
-      WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
-}
-
-TEST(WhenDynamicCastToTest, Describe) {
-  Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
-  const std::string prefix =
-      "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
-  EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
-  EXPECT_EQ(prefix + "does not point to a value that is anything",
-            DescribeNegation(matcher));
-}
-
-TEST(WhenDynamicCastToTest, Explain) {
-  Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
-  Base* null = nullptr;
-  EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
-  Derived derived;
-  EXPECT_TRUE(matcher.Matches(&derived));
-  EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
-
-  // With references, the matcher itself can fail. Test for that one.
-  Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
-  EXPECT_THAT(Explain(ref_matcher, derived),
-              HasSubstr("which cannot be dynamic_cast"));
-}
-
-TEST(WhenDynamicCastToTest, GoodReference) {
-  Derived derived;
-  derived.i = 4;
-  Base& as_base_ref = derived;
-  EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
-  EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
-}
-
-TEST(WhenDynamicCastToTest, BadReference) {
-  Derived derived;
-  Base& as_base_ref = derived;
-  EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
-}
-#endif  // GTEST_HAS_RTTI
-
-// Minimal const-propagating pointer.
-template <typename T>
-class ConstPropagatingPtr {
- public:
-  typedef T element_type;
-
-  ConstPropagatingPtr() : val_() {}
-  explicit ConstPropagatingPtr(T* t) : val_(t) {}
-  ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
-
-  T* get() { return val_; }
-  T& operator*() { return *val_; }
-  // Most smart pointers return non-const T* and T& from the next methods.
-  const T* get() const { return val_; }
-  const T& operator*() const { return *val_; }
-
- private:
-  T* val_;
-};
-
-TEST(PointeeTest, WorksWithConstPropagatingPointers) {
-  const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
-  int three = 3;
-  const ConstPropagatingPtr<int> co(&three);
-  ConstPropagatingPtr<int> o(&three);
-  EXPECT_TRUE(m.Matches(o));
-  EXPECT_TRUE(m.Matches(co));
-  *o = 6;
-  EXPECT_FALSE(m.Matches(o));
-  EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
-}
-
-TEST(PointeeTest, NeverMatchesNull) {
-  const Matcher<const char*> m = Pointee(_);
-  EXPECT_FALSE(m.Matches(nullptr));
-}
-
-// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
-TEST(PointeeTest, MatchesAgainstAValue) {
-  const Matcher<int*> m = Pointee(5);
-
-  int n = 5;
-  EXPECT_TRUE(m.Matches(&n));
-  n = -1;
-  EXPECT_FALSE(m.Matches(&n));
-  EXPECT_FALSE(m.Matches(nullptr));
-}
-
-TEST(PointeeTest, CanDescribeSelf) {
-  const Matcher<int*> m = Pointee(Gt(3));
-  EXPECT_EQ("points to a value that is > 3", Describe(m));
-  EXPECT_EQ("does not point to a value that is > 3",
-            DescribeNegation(m));
-}
-
-TEST(PointeeTest, CanExplainMatchResult) {
-  const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
-
-  EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr)));
-
-  const Matcher<long*> m2 = Pointee(GreaterThan(1));  // NOLINT
-  long n = 3;  // NOLINT
-  EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
-            Explain(m2, &n));
-}
-
-TEST(PointeeTest, AlwaysExplainsPointee) {
-  const Matcher<int*> m = Pointee(0);
-  int n = 42;
-  EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
-}
-
-// An uncopyable class.
-class Uncopyable {
- public:
-  Uncopyable() : value_(-1) {}
-  explicit Uncopyable(int a_value) : value_(a_value) {}
-
-  int value() const { return value_; }
-  void set_value(int i) { value_ = i; }
-
- private:
-  int value_;
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
-};
-
-// Returns true if and only if x.value() is positive.
-bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
-
-MATCHER_P(UncopyableIs, inner_matcher, "") {
-  return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
-}
-
-// A user-defined struct for testing Field().
-struct AStruct {
-  AStruct() : x(0), y(1.0), z(5), p(nullptr) {}
-  AStruct(const AStruct& rhs)
-      : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
-
-  int x;           // A non-const field.
-  const double y;  // A const field.
-  Uncopyable z;    // An uncopyable field.
-  const char* p;   // A pointer field.
-};
-
-// A derived struct for testing Field().
-struct DerivedStruct : public AStruct {
-  char ch;
-};
-
-// Tests that Field(&Foo::field, ...) works when field is non-const.
-TEST(FieldTest, WorksForNonConstField) {
-  Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
-  Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
-
-  AStruct a;
-  EXPECT_TRUE(m.Matches(a));
-  EXPECT_TRUE(m_with_name.Matches(a));
-  a.x = -1;
-  EXPECT_FALSE(m.Matches(a));
-  EXPECT_FALSE(m_with_name.Matches(a));
-}
-
-// Tests that Field(&Foo::field, ...) works when field is const.
-TEST(FieldTest, WorksForConstField) {
-  AStruct a;
-
-  Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
-  Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0));
-  EXPECT_TRUE(m.Matches(a));
-  EXPECT_TRUE(m_with_name.Matches(a));
-  m = Field(&AStruct::y, Le(0.0));
-  m_with_name = Field("y", &AStruct::y, Le(0.0));
-  EXPECT_FALSE(m.Matches(a));
-  EXPECT_FALSE(m_with_name.Matches(a));
-}
-
-// Tests that Field(&Foo::field, ...) works when field is not copyable.
-TEST(FieldTest, WorksForUncopyableField) {
-  AStruct a;
-
-  Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
-  EXPECT_TRUE(m.Matches(a));
-  m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
-  EXPECT_FALSE(m.Matches(a));
-}
-
-// Tests that Field(&Foo::field, ...) works when field is a pointer.
-TEST(FieldTest, WorksForPointerField) {
-  // Matching against NULL.
-  Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));
-  AStruct a;
-  EXPECT_TRUE(m.Matches(a));
-  a.p = "hi";
-  EXPECT_FALSE(m.Matches(a));
-
-  // Matching a pointer that is not NULL.
-  m = Field(&AStruct::p, StartsWith("hi"));
-  a.p = "hill";
-  EXPECT_TRUE(m.Matches(a));
-  a.p = "hole";
-  EXPECT_FALSE(m.Matches(a));
-}
-
-// Tests that Field() works when the object is passed by reference.
-TEST(FieldTest, WorksForByRefArgument) {
-  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
-
-  AStruct a;
-  EXPECT_TRUE(m.Matches(a));
-  a.x = -1;
-  EXPECT_FALSE(m.Matches(a));
-}
-
-// Tests that Field(&Foo::field, ...) works when the argument's type
-// is a sub-type of Foo.
-TEST(FieldTest, WorksForArgumentOfSubType) {
-  // Note that the matcher expects DerivedStruct but we say AStruct
-  // inside Field().
-  Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
-
-  DerivedStruct d;
-  EXPECT_TRUE(m.Matches(d));
-  d.x = -1;
-  EXPECT_FALSE(m.Matches(d));
-}
-
-// Tests that Field(&Foo::field, m) works when field's type and m's
-// argument type are compatible but not the same.
-TEST(FieldTest, WorksForCompatibleMatcherType) {
-  // The field is an int, but the inner matcher expects a signed char.
-  Matcher<const AStruct&> m = Field(&AStruct::x,
-                                    Matcher<signed char>(Ge(0)));
-
-  AStruct a;
-  EXPECT_TRUE(m.Matches(a));
-  a.x = -1;
-  EXPECT_FALSE(m.Matches(a));
-}
-
-// Tests that Field() can describe itself.
-TEST(FieldTest, CanDescribeSelf) {
-  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
-
-  EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
-  EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
-}
-
-TEST(FieldTest, CanDescribeSelfWithFieldName) {
-  Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
-
-  EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
-  EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
-            DescribeNegation(m));
-}
-
-// Tests that Field() can explain the match result.
-TEST(FieldTest, CanExplainMatchResult) {
-  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
-
-  AStruct a;
-  a.x = 1;
-  EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
-
-  m = Field(&AStruct::x, GreaterThan(0));
-  EXPECT_EQ(
-      "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
-      Explain(m, a));
-}
-
-TEST(FieldTest, CanExplainMatchResultWithFieldName) {
-  Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
-
-  AStruct a;
-  a.x = 1;
-  EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
-
-  m = Field("field_name", &AStruct::x, GreaterThan(0));
-  EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +
-                ", which is 1 more than 0",
-            Explain(m, a));
-}
-
-// Tests that Field() works when the argument is a pointer to const.
-TEST(FieldForPointerTest, WorksForPointerToConst) {
-  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
-
-  AStruct a;
-  EXPECT_TRUE(m.Matches(&a));
-  a.x = -1;
-  EXPECT_FALSE(m.Matches(&a));
-}
-
-// Tests that Field() works when the argument is a pointer to non-const.
-TEST(FieldForPointerTest, WorksForPointerToNonConst) {
-  Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
-
-  AStruct a;
-  EXPECT_TRUE(m.Matches(&a));
-  a.x = -1;
-  EXPECT_FALSE(m.Matches(&a));
-}
-
-// Tests that Field() works when the argument is a reference to a const pointer.
-TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
-  Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
-
-  AStruct a;
-  EXPECT_TRUE(m.Matches(&a));
-  a.x = -1;
-  EXPECT_FALSE(m.Matches(&a));
-}
-
-// Tests that Field() does not match the NULL pointer.
-TEST(FieldForPointerTest, DoesNotMatchNull) {
-  Matcher<const AStruct*> m = Field(&AStruct::x, _);
-  EXPECT_FALSE(m.Matches(nullptr));
-}
-
-// Tests that Field(&Foo::field, ...) works when the argument's type
-// is a sub-type of const Foo*.
-TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
-  // Note that the matcher expects DerivedStruct but we say AStruct
-  // inside Field().
-  Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
-
-  DerivedStruct d;
-  EXPECT_TRUE(m.Matches(&d));
-  d.x = -1;
-  EXPECT_FALSE(m.Matches(&d));
-}
-
-// Tests that Field() can describe itself when used to match a pointer.
-TEST(FieldForPointerTest, CanDescribeSelf) {
-  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
-
-  EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
-  EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
-}
-
-TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
-  Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
-
-  EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
-  EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
-            DescribeNegation(m));
-}
-
-// Tests that Field() can explain the result of matching a pointer.
-TEST(FieldForPointerTest, CanExplainMatchResult) {
-  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
-
-  AStruct a;
-  a.x = 1;
-  EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
-  EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
-            Explain(m, &a));
-
-  m = Field(&AStruct::x, GreaterThan(0));
-  EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
-            ", which is 1 more than 0", Explain(m, &a));
-}
-
-TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) {
-  Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
-
-  AStruct a;
-  a.x = 1;
-  EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
-  EXPECT_EQ(
-      "which points to an object whose field `field_name` is 1" + OfType("int"),
-      Explain(m, &a));
-
-  m = Field("field_name", &AStruct::x, GreaterThan(0));
-  EXPECT_EQ("which points to an object whose field `field_name` is 1" +
-                OfType("int") + ", which is 1 more than 0",
-            Explain(m, &a));
-}
-
-// A user-defined class for testing Property().
-class AClass {
- public:
-  AClass() : n_(0) {}
-
-  // A getter that returns a non-reference.
-  int n() const { return n_; }
-
-  void set_n(int new_n) { n_ = new_n; }
-
-  // A getter that returns a reference to const.
-  const std::string& s() const { return s_; }
-
-  const std::string& s_ref() const & { return s_; }
-
-  void set_s(const std::string& new_s) { s_ = new_s; }
-
-  // A getter that returns a reference to non-const.
-  double& x() const { return x_; }
-
- private:
-  int n_;
-  std::string s_;
-
-  static double x_;
-};
-
-double AClass::x_ = 0.0;
-
-// A derived class for testing Property().
-class DerivedClass : public AClass {
- public:
-  int k() const { return k_; }
- private:
-  int k_;
-};
-
-// Tests that Property(&Foo::property, ...) works when property()
-// returns a non-reference.
-TEST(PropertyTest, WorksForNonReferenceProperty) {
-  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
-  Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
-
-  AClass a;
-  a.set_n(1);
-  EXPECT_TRUE(m.Matches(a));
-  EXPECT_TRUE(m_with_name.Matches(a));
-
-  a.set_n(-1);
-  EXPECT_FALSE(m.Matches(a));
-  EXPECT_FALSE(m_with_name.Matches(a));
-}
-
-// Tests that Property(&Foo::property, ...) works when property()
-// returns a reference to const.
-TEST(PropertyTest, WorksForReferenceToConstProperty) {
-  Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
-  Matcher<const AClass&> m_with_name =
-      Property("s", &AClass::s, StartsWith("hi"));
-
-  AClass a;
-  a.set_s("hill");
-  EXPECT_TRUE(m.Matches(a));
-  EXPECT_TRUE(m_with_name.Matches(a));
-
-  a.set_s("hole");
-  EXPECT_FALSE(m.Matches(a));
-  EXPECT_FALSE(m_with_name.Matches(a));
-}
-
-// Tests that Property(&Foo::property, ...) works when property() is
-// ref-qualified.
-TEST(PropertyTest, WorksForRefQualifiedProperty) {
-  Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
-  Matcher<const AClass&> m_with_name =
-      Property("s", &AClass::s_ref, StartsWith("hi"));
-
-  AClass a;
-  a.set_s("hill");
-  EXPECT_TRUE(m.Matches(a));
-  EXPECT_TRUE(m_with_name.Matches(a));
-
-  a.set_s("hole");
-  EXPECT_FALSE(m.Matches(a));
-  EXPECT_FALSE(m_with_name.Matches(a));
-}
-
-// Tests that Property(&Foo::property, ...) works when property()
-// returns a reference to non-const.
-TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
-  double x = 0.0;
-  AClass a;
-
-  Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
-  EXPECT_FALSE(m.Matches(a));
-
-  m = Property(&AClass::x, Not(Ref(x)));
-  EXPECT_TRUE(m.Matches(a));
-}
-
-// Tests that Property(&Foo::property, ...) works when the argument is
-// passed by value.
-TEST(PropertyTest, WorksForByValueArgument) {
-  Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
-
-  AClass a;
-  a.set_s("hill");
-  EXPECT_TRUE(m.Matches(a));
-
-  a.set_s("hole");
-  EXPECT_FALSE(m.Matches(a));
-}
-
-// Tests that Property(&Foo::property, ...) works when the argument's
-// type is a sub-type of Foo.
-TEST(PropertyTest, WorksForArgumentOfSubType) {
-  // The matcher expects a DerivedClass, but inside the Property() we
-  // say AClass.
-  Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
-
-  DerivedClass d;
-  d.set_n(1);
-  EXPECT_TRUE(m.Matches(d));
-
-  d.set_n(-1);
-  EXPECT_FALSE(m.Matches(d));
-}
-
-// Tests that Property(&Foo::property, m) works when property()'s type
-// and m's argument type are compatible but different.
-TEST(PropertyTest, WorksForCompatibleMatcherType) {
-  // n() returns an int but the inner matcher expects a signed char.
-  Matcher<const AClass&> m = Property(&AClass::n,
-                                      Matcher<signed char>(Ge(0)));
-
-  Matcher<const AClass&> m_with_name =
-      Property("n", &AClass::n, Matcher<signed char>(Ge(0)));
-
-  AClass a;
-  EXPECT_TRUE(m.Matches(a));
-  EXPECT_TRUE(m_with_name.Matches(a));
-  a.set_n(-1);
-  EXPECT_FALSE(m.Matches(a));
-  EXPECT_FALSE(m_with_name.Matches(a));
-}
-
-// Tests that Property() can describe itself.
-TEST(PropertyTest, CanDescribeSelf) {
-  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
-
-  EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
-  EXPECT_EQ("is an object whose given property isn't >= 0",
-            DescribeNegation(m));
-}
-
-TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
-  Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
-
-  EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
-  EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
-            DescribeNegation(m));
-}
-
-// Tests that Property() can explain the match result.
-TEST(PropertyTest, CanExplainMatchResult) {
-  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
-
-  AClass a;
-  a.set_n(1);
-  EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
-
-  m = Property(&AClass::n, GreaterThan(0));
-  EXPECT_EQ(
-      "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
-      Explain(m, a));
-}
-
-TEST(PropertyTest, CanExplainMatchResultWithPropertyName) {
-  Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
-
-  AClass a;
-  a.set_n(1);
-  EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
-
-  m = Property("fancy_name", &AClass::n, GreaterThan(0));
-  EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +
-                ", which is 1 more than 0",
-            Explain(m, a));
-}
-
-// Tests that Property() works when the argument is a pointer to const.
-TEST(PropertyForPointerTest, WorksForPointerToConst) {
-  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
-
-  AClass a;
-  a.set_n(1);
-  EXPECT_TRUE(m.Matches(&a));
-
-  a.set_n(-1);
-  EXPECT_FALSE(m.Matches(&a));
-}
-
-// Tests that Property() works when the argument is a pointer to non-const.
-TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
-  Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
-
-  AClass a;
-  a.set_s("hill");
-  EXPECT_TRUE(m.Matches(&a));
-
-  a.set_s("hole");
-  EXPECT_FALSE(m.Matches(&a));
-}
-
-// Tests that Property() works when the argument is a reference to a
-// const pointer.
-TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
-  Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
-
-  AClass a;
-  a.set_s("hill");
-  EXPECT_TRUE(m.Matches(&a));
-
-  a.set_s("hole");
-  EXPECT_FALSE(m.Matches(&a));
-}
-
-// Tests that Property() does not match the NULL pointer.
-TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
-  Matcher<const AClass*> m = Property(&AClass::x, _);
-  EXPECT_FALSE(m.Matches(nullptr));
-}
-
-// Tests that Property(&Foo::property, ...) works when the argument's
-// type is a sub-type of const Foo*.
-TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
-  // The matcher expects a DerivedClass, but inside the Property() we
-  // say AClass.
-  Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
-
-  DerivedClass d;
-  d.set_n(1);
-  EXPECT_TRUE(m.Matches(&d));
-
-  d.set_n(-1);
-  EXPECT_FALSE(m.Matches(&d));
-}
-
-// Tests that Property() can describe itself when used to match a pointer.
-TEST(PropertyForPointerTest, CanDescribeSelf) {
-  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
-
-  EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
-  EXPECT_EQ("is an object whose given property isn't >= 0",
-            DescribeNegation(m));
-}
-
-TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
-  Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
-
-  EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
-  EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
-            DescribeNegation(m));
-}
-
-// Tests that Property() can explain the result of matching a pointer.
-TEST(PropertyForPointerTest, CanExplainMatchResult) {
-  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
-
-  AClass a;
-  a.set_n(1);
-  EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
-  EXPECT_EQ(
-      "which points to an object whose given property is 1" + OfType("int"),
-      Explain(m, &a));
-
-  m = Property(&AClass::n, GreaterThan(0));
-  EXPECT_EQ("which points to an object whose given property is 1" +
-            OfType("int") + ", which is 1 more than 0",
-            Explain(m, &a));
-}
-
-TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) {
-  Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
-
-  AClass a;
-  a.set_n(1);
-  EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
-  EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
-                OfType("int"),
-            Explain(m, &a));
-
-  m = Property("fancy_name", &AClass::n, GreaterThan(0));
-  EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
-                OfType("int") + ", which is 1 more than 0",
-            Explain(m, &a));
-}
-
-// Tests ResultOf.
-
-// Tests that ResultOf(f, ...) compiles and works as expected when f is a
-// function pointer.
-std::string IntToStringFunction(int input) {
-  return input == 1 ? "foo" : "bar";
-}
-
-TEST(ResultOfTest, WorksForFunctionPointers) {
-  Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
-
-  EXPECT_TRUE(matcher.Matches(1));
-  EXPECT_FALSE(matcher.Matches(2));
-}
-
-// Tests that ResultOf() can describe itself.
-TEST(ResultOfTest, CanDescribeItself) {
-  Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
-
-  EXPECT_EQ("is mapped by the given callable to a value that "
-            "is equal to \"foo\"", Describe(matcher));
-  EXPECT_EQ("is mapped by the given callable to a value that "
-            "isn't equal to \"foo\"", DescribeNegation(matcher));
-}
-
-// Tests that ResultOf() can explain the match result.
-int IntFunction(int input) { return input == 42 ? 80 : 90; }
-
-TEST(ResultOfTest, CanExplainMatchResult) {
-  Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
-  EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
-            Explain(matcher, 36));
-
-  matcher = ResultOf(&IntFunction, GreaterThan(85));
-  EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
-            ", which is 5 more than 85", Explain(matcher, 36));
-}
-
-// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
-// returns a non-reference.
-TEST(ResultOfTest, WorksForNonReferenceResults) {
-  Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
-
-  EXPECT_TRUE(matcher.Matches(42));
-  EXPECT_FALSE(matcher.Matches(36));
-}
-
-// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
-// returns a reference to non-const.
-double& DoubleFunction(double& input) { return input; }  // NOLINT
-
-Uncopyable& RefUncopyableFunction(Uncopyable& obj) {  // NOLINT
-  return obj;
-}
-
-TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
-  double x = 3.14;
-  double x2 = x;
-  Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
-
-  EXPECT_TRUE(matcher.Matches(x));
-  EXPECT_FALSE(matcher.Matches(x2));
-
-  // Test that ResultOf works with uncopyable objects
-  Uncopyable obj(0);
-  Uncopyable obj2(0);
-  Matcher<Uncopyable&> matcher2 =
-      ResultOf(&RefUncopyableFunction, Ref(obj));
-
-  EXPECT_TRUE(matcher2.Matches(obj));
-  EXPECT_FALSE(matcher2.Matches(obj2));
-}
-
-// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
-// returns a reference to const.
-const std::string& StringFunction(const std::string& input) { return input; }
-
-TEST(ResultOfTest, WorksForReferenceToConstResults) {
-  std::string s = "foo";
-  std::string s2 = s;
-  Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
-
-  EXPECT_TRUE(matcher.Matches(s));
-  EXPECT_FALSE(matcher.Matches(s2));
-}
-
-// Tests that ResultOf(f, m) works when f(x) and m's
-// argument types are compatible but different.
-TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
-  // IntFunction() returns int but the inner matcher expects a signed char.
-  Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
-
-  EXPECT_TRUE(matcher.Matches(36));
-  EXPECT_FALSE(matcher.Matches(42));
-}
-
-// Tests that the program aborts when ResultOf is passed
-// a NULL function pointer.
-TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
-  EXPECT_DEATH_IF_SUPPORTED(
-      ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
-               Eq(std::string("foo"))),
-      "NULL function pointer is passed into ResultOf\\(\\)\\.");
-}
-
-// Tests that ResultOf(f, ...) compiles and works as expected when f is a
-// function reference.
-TEST(ResultOfTest, WorksForFunctionReferences) {
-  Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
-  EXPECT_TRUE(matcher.Matches(1));
-  EXPECT_FALSE(matcher.Matches(2));
-}
-
-// Tests that ResultOf(f, ...) compiles and works as expected when f is a
-// function object.
-struct Functor {
-  std::string operator()(int input) const {
-    return IntToStringFunction(input);
-  }
-};
-
-TEST(ResultOfTest, WorksForFunctors) {
-  Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
-
-  EXPECT_TRUE(matcher.Matches(1));
-  EXPECT_FALSE(matcher.Matches(2));
-}
-
-// Tests that ResultOf(f, ...) compiles and works as expected when f is a
-// functor with more than one operator() defined. ResultOf() must work
-// for each defined operator().
-struct PolymorphicFunctor {
-  typedef int result_type;
-  int operator()(int n) { return n; }
-  int operator()(const char* s) { return static_cast<int>(strlen(s)); }
-  std::string operator()(int *p) { return p ? "good ptr" : "null"; }
-};
-
-TEST(ResultOfTest, WorksForPolymorphicFunctors) {
-  Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
-
-  EXPECT_TRUE(matcher_int.Matches(10));
-  EXPECT_FALSE(matcher_int.Matches(2));
-
-  Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
-
-  EXPECT_TRUE(matcher_string.Matches("long string"));
-  EXPECT_FALSE(matcher_string.Matches("shrt"));
-}
-
-TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
-  Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");
-
-  int n = 0;
-  EXPECT_TRUE(matcher.Matches(&n));
-  EXPECT_FALSE(matcher.Matches(nullptr));
-}
-
-TEST(ResultOfTest, WorksForLambdas) {
-  Matcher<int> matcher = ResultOf(
-      [](int str_len) {
-        return std::string(static_cast<size_t>(str_len), 'x');
-      },
-      "xxx");
-  EXPECT_TRUE(matcher.Matches(3));
-  EXPECT_FALSE(matcher.Matches(1));
-}
-
-TEST(ResultOfTest, WorksForNonCopyableArguments) {
-  Matcher<std::unique_ptr<int>> matcher = ResultOf(
-      [](const std::unique_ptr<int>& str_len) {
-        return std::string(static_cast<size_t>(*str_len), 'x');
-      },
-      "xxx");
-  EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3))));
-  EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1))));
-}
-
-const int* ReferencingFunction(const int& n) { return &n; }
-
-struct ReferencingFunctor {
-  typedef const int* result_type;
-  result_type operator()(const int& n) { return &n; }
-};
-
-TEST(ResultOfTest, WorksForReferencingCallables) {
-  const int n = 1;
-  const int n2 = 1;
-  Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
-  EXPECT_TRUE(matcher2.Matches(n));
-  EXPECT_FALSE(matcher2.Matches(n2));
-
-  Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
-  EXPECT_TRUE(matcher3.Matches(n));
-  EXPECT_FALSE(matcher3.Matches(n2));
-}
-
-class DivisibleByImpl {
- public:
-  explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
-
-  // For testing using ExplainMatchResultTo() with polymorphic matchers.
-  template <typename T>
-  bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
-    *listener << "which is " << (n % divider_) << " modulo "
-              << divider_;
-    return (n % divider_) == 0;
-  }
-
-  void DescribeTo(ostream* os) const {
-    *os << "is divisible by " << divider_;
-  }
-
-  void DescribeNegationTo(ostream* os) const {
-    *os << "is not divisible by " << divider_;
-  }
-
-  void set_divider(int a_divider) { divider_ = a_divider; }
-  int divider() const { return divider_; }
-
- private:
-  int divider_;
-};
-
-PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
-  return MakePolymorphicMatcher(DivisibleByImpl(n));
-}
-
-// Tests that when AllOf() fails, only the first failing matcher is
-// asked to explain why.
-TEST(ExplainMatchResultTest, AllOf_False_False) {
-  const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
-  EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
-}
-
-// Tests that when AllOf() fails, only the first failing matcher is
-// asked to explain why.
-TEST(ExplainMatchResultTest, AllOf_False_True) {
-  const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
-  EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
-}
-
-// Tests that when AllOf() fails, only the first failing matcher is
-// asked to explain why.
-TEST(ExplainMatchResultTest, AllOf_True_False) {
-  const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
-  EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
-}
-
-// Tests that when AllOf() succeeds, all matchers are asked to explain
-// why.
-TEST(ExplainMatchResultTest, AllOf_True_True) {
-  const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
-  EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
-}
-
-TEST(ExplainMatchResultTest, AllOf_True_True_2) {
-  const Matcher<int> m = AllOf(Ge(2), Le(3));
-  EXPECT_EQ("", Explain(m, 2));
-}
-
-TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
-  const Matcher<int> m = GreaterThan(5);
-  EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
-}
-
-// The following two tests verify that values without a public copy
-// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
-// with the help of ByRef().
-
-class NotCopyable {
- public:
-  explicit NotCopyable(int a_value) : value_(a_value) {}
-
-  int value() const { return value_; }
-
-  bool operator==(const NotCopyable& rhs) const {
-    return value() == rhs.value();
-  }
-
-  bool operator>=(const NotCopyable& rhs) const {
-    return value() >= rhs.value();
-  }
- private:
-  int value_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
-};
-
-TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
-  const NotCopyable const_value1(1);
-  const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
-
-  const NotCopyable n1(1), n2(2);
-  EXPECT_TRUE(m.Matches(n1));
-  EXPECT_FALSE(m.Matches(n2));
-}
-
-TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
-  NotCopyable value2(2);
-  const Matcher<NotCopyable&> m = Ge(ByRef(value2));
-
-  NotCopyable n1(1), n2(2);
-  EXPECT_FALSE(m.Matches(n1));
-  EXPECT_TRUE(m.Matches(n2));
-}
-
-TEST(IsEmptyTest, ImplementsIsEmpty) {
-  vector<int> container;
-  EXPECT_THAT(container, IsEmpty());
-  container.push_back(0);
-  EXPECT_THAT(container, Not(IsEmpty()));
-  container.push_back(1);
-  EXPECT_THAT(container, Not(IsEmpty()));
-}
-
-TEST(IsEmptyTest, WorksWithString) {
-  std::string text;
-  EXPECT_THAT(text, IsEmpty());
-  text = "foo";
-  EXPECT_THAT(text, Not(IsEmpty()));
-  text = std::string("\0", 1);
-  EXPECT_THAT(text, Not(IsEmpty()));
-}
-
-TEST(IsEmptyTest, CanDescribeSelf) {
-  Matcher<vector<int> > m = IsEmpty();
-  EXPECT_EQ("is empty", Describe(m));
-  EXPECT_EQ("isn't empty", DescribeNegation(m));
-}
-
-TEST(IsEmptyTest, ExplainsResult) {
-  Matcher<vector<int> > m = IsEmpty();
-  vector<int> container;
-  EXPECT_EQ("", Explain(m, container));
-  container.push_back(0);
-  EXPECT_EQ("whose size is 1", Explain(m, container));
-}
-
-TEST(IsEmptyTest, WorksWithMoveOnly) {
-  ContainerHelper helper;
-  EXPECT_CALL(helper, Call(IsEmpty()));
-  helper.Call({});
-}
-
-TEST(IsTrueTest, IsTrueIsFalse) {
-  EXPECT_THAT(true, IsTrue());
-  EXPECT_THAT(false, IsFalse());
-  EXPECT_THAT(true, Not(IsFalse()));
-  EXPECT_THAT(false, Not(IsTrue()));
-  EXPECT_THAT(0, Not(IsTrue()));
-  EXPECT_THAT(0, IsFalse());
-  EXPECT_THAT(nullptr, Not(IsTrue()));
-  EXPECT_THAT(nullptr, IsFalse());
-  EXPECT_THAT(-1, IsTrue());
-  EXPECT_THAT(-1, Not(IsFalse()));
-  EXPECT_THAT(1, IsTrue());
-  EXPECT_THAT(1, Not(IsFalse()));
-  EXPECT_THAT(2, IsTrue());
-  EXPECT_THAT(2, Not(IsFalse()));
-  int a = 42;
-  EXPECT_THAT(a, IsTrue());
-  EXPECT_THAT(a, Not(IsFalse()));
-  EXPECT_THAT(&a, IsTrue());
-  EXPECT_THAT(&a, Not(IsFalse()));
-  EXPECT_THAT(false, Not(IsTrue()));
-  EXPECT_THAT(true, Not(IsFalse()));
-  EXPECT_THAT(std::true_type(), IsTrue());
-  EXPECT_THAT(std::true_type(), Not(IsFalse()));
-  EXPECT_THAT(std::false_type(), IsFalse());
-  EXPECT_THAT(std::false_type(), Not(IsTrue()));
-  EXPECT_THAT(nullptr, Not(IsTrue()));
-  EXPECT_THAT(nullptr, IsFalse());
-  std::unique_ptr<int> null_unique;
-  std::unique_ptr<int> nonnull_unique(new int(0));
-  EXPECT_THAT(null_unique, Not(IsTrue()));
-  EXPECT_THAT(null_unique, IsFalse());
-  EXPECT_THAT(nonnull_unique, IsTrue());
-  EXPECT_THAT(nonnull_unique, Not(IsFalse()));
-}
-
-TEST(SizeIsTest, ImplementsSizeIs) {
-  vector<int> container;
-  EXPECT_THAT(container, SizeIs(0));
-  EXPECT_THAT(container, Not(SizeIs(1)));
-  container.push_back(0);
-  EXPECT_THAT(container, Not(SizeIs(0)));
-  EXPECT_THAT(container, SizeIs(1));
-  container.push_back(0);
-  EXPECT_THAT(container, Not(SizeIs(0)));
-  EXPECT_THAT(container, SizeIs(2));
-}
-
-TEST(SizeIsTest, WorksWithMap) {
-  map<std::string, int> container;
-  EXPECT_THAT(container, SizeIs(0));
-  EXPECT_THAT(container, Not(SizeIs(1)));
-  container.insert(make_pair("foo", 1));
-  EXPECT_THAT(container, Not(SizeIs(0)));
-  EXPECT_THAT(container, SizeIs(1));
-  container.insert(make_pair("bar", 2));
-  EXPECT_THAT(container, Not(SizeIs(0)));
-  EXPECT_THAT(container, SizeIs(2));
-}
-
-TEST(SizeIsTest, WorksWithReferences) {
-  vector<int> container;
-  Matcher<const vector<int>&> m = SizeIs(1);
-  EXPECT_THAT(container, Not(m));
-  container.push_back(0);
-  EXPECT_THAT(container, m);
-}
-
-TEST(SizeIsTest, WorksWithMoveOnly) {
-  ContainerHelper helper;
-  EXPECT_CALL(helper, Call(SizeIs(3)));
-  helper.Call(MakeUniquePtrs({1, 2, 3}));
-}
-
-// SizeIs should work for any type that provides a size() member function.
-// For example, a size_type member type should not need to be provided.
-struct MinimalistCustomType {
-  int size() const { return 1; }
-};
-TEST(SizeIsTest, WorksWithMinimalistCustomType) {
-  MinimalistCustomType container;
-  EXPECT_THAT(container, SizeIs(1));
-  EXPECT_THAT(container, Not(SizeIs(0)));
-}
-
-TEST(SizeIsTest, CanDescribeSelf) {
-  Matcher<vector<int> > m = SizeIs(2);
-  EXPECT_EQ("size is equal to 2", Describe(m));
-  EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
-}
-
-TEST(SizeIsTest, ExplainsResult) {
-  Matcher<vector<int> > m1 = SizeIs(2);
-  Matcher<vector<int> > m2 = SizeIs(Lt(2u));
-  Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
-  Matcher<vector<int> > m4 = SizeIs(Gt(1u));
-  vector<int> container;
-  EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
-  EXPECT_EQ("whose size 0 matches", Explain(m2, container));
-  EXPECT_EQ("whose size 0 matches", Explain(m3, container));
-  EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
-  container.push_back(0);
-  container.push_back(0);
-  EXPECT_EQ("whose size 2 matches", Explain(m1, container));
-  EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
-  EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
-  EXPECT_EQ("whose size 2 matches", Explain(m4, container));
-}
-
-#if GTEST_HAS_TYPED_TEST
-// Tests ContainerEq with different container types, and
-// different element types.
-
-template <typename T>
-class ContainerEqTest : public testing::Test {};
-
-typedef testing::Types<
-    set<int>,
-    vector<size_t>,
-    multiset<size_t>,
-    list<int> >
-    ContainerEqTestTypes;
-
-TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes);
-
-// Tests that the filled container is equal to itself.
-TYPED_TEST(ContainerEqTest, EqualsSelf) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  TypeParam my_set(vals, vals + 6);
-  const Matcher<TypeParam> m = ContainerEq(my_set);
-  EXPECT_TRUE(m.Matches(my_set));
-  EXPECT_EQ("", Explain(m, my_set));
-}
-
-// Tests that missing values are reported.
-TYPED_TEST(ContainerEqTest, ValueMissing) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  static const int test_vals[] = {2, 1, 8, 5};
-  TypeParam my_set(vals, vals + 6);
-  TypeParam test_set(test_vals, test_vals + 4);
-  const Matcher<TypeParam> m = ContainerEq(my_set);
-  EXPECT_FALSE(m.Matches(test_set));
-  EXPECT_EQ("which doesn't have these expected elements: 3",
-            Explain(m, test_set));
-}
-
-// Tests that added values are reported.
-TYPED_TEST(ContainerEqTest, ValueAdded) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  static const int test_vals[] = {1, 2, 3, 5, 8, 46};
-  TypeParam my_set(vals, vals + 6);
-  TypeParam test_set(test_vals, test_vals + 6);
-  const Matcher<const TypeParam&> m = ContainerEq(my_set);
-  EXPECT_FALSE(m.Matches(test_set));
-  EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
-}
-
-// Tests that added and missing values are reported together.
-TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  static const int test_vals[] = {1, 2, 3, 8, 46};
-  TypeParam my_set(vals, vals + 6);
-  TypeParam test_set(test_vals, test_vals + 5);
-  const Matcher<TypeParam> m = ContainerEq(my_set);
-  EXPECT_FALSE(m.Matches(test_set));
-  EXPECT_EQ("which has these unexpected elements: 46,\n"
-            "and doesn't have these expected elements: 5",
-            Explain(m, test_set));
-}
-
-// Tests duplicated value -- expect no explanation.
-TYPED_TEST(ContainerEqTest, DuplicateDifference) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  static const int test_vals[] = {1, 2, 3, 5, 8};
-  TypeParam my_set(vals, vals + 6);
-  TypeParam test_set(test_vals, test_vals + 5);
-  const Matcher<const TypeParam&> m = ContainerEq(my_set);
-  // Depending on the container, match may be true or false
-  // But in any case there should be no explanation.
-  EXPECT_EQ("", Explain(m, test_set));
-}
-#endif  // GTEST_HAS_TYPED_TEST
-
-// Tests that multiple missing values are reported.
-// Using just vector here, so order is predictable.
-TEST(ContainerEqExtraTest, MultipleValuesMissing) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  static const int test_vals[] = {2, 1, 5};
-  vector<int> my_set(vals, vals + 6);
-  vector<int> test_set(test_vals, test_vals + 3);
-  const Matcher<vector<int> > m = ContainerEq(my_set);
-  EXPECT_FALSE(m.Matches(test_set));
-  EXPECT_EQ("which doesn't have these expected elements: 3, 8",
-            Explain(m, test_set));
-}
-
-// Tests that added values are reported.
-// Using just vector here, so order is predictable.
-TEST(ContainerEqExtraTest, MultipleValuesAdded) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
-  list<size_t> my_set(vals, vals + 6);
-  list<size_t> test_set(test_vals, test_vals + 7);
-  const Matcher<const list<size_t>&> m = ContainerEq(my_set);
-  EXPECT_FALSE(m.Matches(test_set));
-  EXPECT_EQ("which has these unexpected elements: 92, 46",
-            Explain(m, test_set));
-}
-
-// Tests that added and missing values are reported together.
-TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  static const int test_vals[] = {1, 2, 3, 92, 46};
-  list<size_t> my_set(vals, vals + 6);
-  list<size_t> test_set(test_vals, test_vals + 5);
-  const Matcher<const list<size_t> > m = ContainerEq(my_set);
-  EXPECT_FALSE(m.Matches(test_set));
-  EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
-            "and doesn't have these expected elements: 5, 8",
-            Explain(m, test_set));
-}
-
-// Tests to see that duplicate elements are detected,
-// but (as above) not reported in the explanation.
-TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
-  static const int vals[] = {1, 1, 2, 3, 5, 8};
-  static const int test_vals[] = {1, 2, 3, 5, 8};
-  vector<int> my_set(vals, vals + 6);
-  vector<int> test_set(test_vals, test_vals + 5);
-  const Matcher<vector<int> > m = ContainerEq(my_set);
-  EXPECT_TRUE(m.Matches(my_set));
-  EXPECT_FALSE(m.Matches(test_set));
-  // There is nothing to report when both sets contain all the same values.
-  EXPECT_EQ("", Explain(m, test_set));
-}
-
-// Tests that ContainerEq works for non-trivial associative containers,
-// like maps.
-TEST(ContainerEqExtraTest, WorksForMaps) {
-  map<int, std::string> my_map;
-  my_map[0] = "a";
-  my_map[1] = "b";
-
-  map<int, std::string> test_map;
-  test_map[0] = "aa";
-  test_map[1] = "b";
-
-  const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
-  EXPECT_TRUE(m.Matches(my_map));
-  EXPECT_FALSE(m.Matches(test_map));
-
-  EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
-            "and doesn't have these expected elements: (0, \"a\")",
-            Explain(m, test_map));
-}
-
-TEST(ContainerEqExtraTest, WorksForNativeArray) {
-  int a1[] = {1, 2, 3};
-  int a2[] = {1, 2, 3};
-  int b[] = {1, 2, 4};
-
-  EXPECT_THAT(a1, ContainerEq(a2));
-  EXPECT_THAT(a1, Not(ContainerEq(b)));
-}
-
-TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
-  const char a1[][3] = {"hi", "lo"};
-  const char a2[][3] = {"hi", "lo"};
-  const char b[][3] = {"lo", "hi"};
-
-  // Tests using ContainerEq() in the first dimension.
-  EXPECT_THAT(a1, ContainerEq(a2));
-  EXPECT_THAT(a1, Not(ContainerEq(b)));
-
-  // Tests using ContainerEq() in the second dimension.
-  EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
-  EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
-}
-
-TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
-  const int a1[] = {1, 2, 3};
-  const int a2[] = {1, 2, 3};
-  const int b[] = {1, 2, 3, 4};
-
-  const int* const p1 = a1;
-  EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2));
-  EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b)));
-
-  const int c[] = {1, 3, 2};
-  EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c)));
-}
-
-TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
-  std::string a1[][3] = {
-    {"hi", "hello", "ciao"},
-    {"bye", "see you", "ciao"}
-  };
-
-  std::string a2[][3] = {
-    {"hi", "hello", "ciao"},
-    {"bye", "see you", "ciao"}
-  };
-
-  const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
-  EXPECT_THAT(a1, m);
-
-  a2[0][0] = "ha";
-  EXPECT_THAT(a1, m);
-}
-
-TEST(WhenSortedByTest, WorksForEmptyContainer) {
-  const vector<int> numbers;
-  EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
-  EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
-}
-
-TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
-  vector<unsigned> numbers;
-  numbers.push_back(3);
-  numbers.push_back(1);
-  numbers.push_back(2);
-  numbers.push_back(2);
-  EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
-                                    ElementsAre(3, 2, 2, 1)));
-  EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
-                                        ElementsAre(1, 2, 2, 3))));
-}
-
-TEST(WhenSortedByTest, WorksForNonVectorContainer) {
-  list<std::string> words;
-  words.push_back("say");
-  words.push_back("hello");
-  words.push_back("world");
-  EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
-                                  ElementsAre("hello", "say", "world")));
-  EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
-                                      ElementsAre("say", "hello", "world"))));
-}
-
-TEST(WhenSortedByTest, WorksForNativeArray) {
-  const int numbers[] = {1, 3, 2, 4};
-  const int sorted_numbers[] = {1, 2, 3, 4};
-  EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
-  EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
-                                    ElementsAreArray(sorted_numbers)));
-  EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
-}
-
-TEST(WhenSortedByTest, CanDescribeSelf) {
-  const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
-  EXPECT_EQ("(when sorted) has 2 elements where\n"
-            "element #0 is equal to 1,\n"
-            "element #1 is equal to 2",
-            Describe(m));
-  EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
-            "element #0 isn't equal to 1, or\n"
-            "element #1 isn't equal to 2",
-            DescribeNegation(m));
-}
-
-TEST(WhenSortedByTest, ExplainsMatchResult) {
-  const int a[] = {2, 1};
-  EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
-            Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
-  EXPECT_EQ("which is { 1, 2 } when sorted",
-            Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
-}
-
-// WhenSorted() is a simple wrapper on WhenSortedBy().  Hence we don't
-// need to test it as exhaustively as we test the latter.
-
-TEST(WhenSortedTest, WorksForEmptyContainer) {
-  const vector<int> numbers;
-  EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
-  EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
-}
-
-TEST(WhenSortedTest, WorksForNonEmptyContainer) {
-  list<std::string> words;
-  words.push_back("3");
-  words.push_back("1");
-  words.push_back("2");
-  words.push_back("2");
-  EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
-  EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
-}
-
-TEST(WhenSortedTest, WorksForMapTypes) {
-  map<std::string, int> word_counts;
-  word_counts["and"] = 1;
-  word_counts["the"] = 1;
-  word_counts["buffalo"] = 2;
-  EXPECT_THAT(word_counts,
-              WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
-                                     Pair("the", 1))));
-  EXPECT_THAT(word_counts,
-              Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
-                                         Pair("buffalo", 2)))));
-}
-
-TEST(WhenSortedTest, WorksForMultiMapTypes) {
-    multimap<int, int> ifib;
-    ifib.insert(make_pair(8, 6));
-    ifib.insert(make_pair(2, 3));
-    ifib.insert(make_pair(1, 1));
-    ifib.insert(make_pair(3, 4));
-    ifib.insert(make_pair(1, 2));
-    ifib.insert(make_pair(5, 5));
-    EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
-                                             Pair(1, 2),
-                                             Pair(2, 3),
-                                             Pair(3, 4),
-                                             Pair(5, 5),
-                                             Pair(8, 6))));
-    EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
-                                                 Pair(2, 3),
-                                                 Pair(1, 1),
-                                                 Pair(3, 4),
-                                                 Pair(1, 2),
-                                                 Pair(5, 5)))));
-}
-
-TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
-    std::deque<int> d;
-    d.push_back(2);
-    d.push_back(1);
-    EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
-    EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
-}
-
-TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
-    std::deque<int> d;
-    d.push_back(2);
-    d.push_back(1);
-    Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
-    EXPECT_THAT(d, WhenSorted(vector_match));
-    Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
-    EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
-}
-
-// Deliberately bare pseudo-container.
-// Offers only begin() and end() accessors, yielding InputIterator.
-template <typename T>
-class Streamlike {
- private:
-  class ConstIter;
- public:
-  typedef ConstIter const_iterator;
-  typedef T value_type;
-
-  template <typename InIter>
-  Streamlike(InIter first, InIter last) : remainder_(first, last) {}
-
-  const_iterator begin() const {
-    return const_iterator(this, remainder_.begin());
-  }
-  const_iterator end() const {
-    return const_iterator(this, remainder_.end());
-  }
-
- private:
-  class ConstIter : public std::iterator<std::input_iterator_tag,
-                                         value_type,
-                                         ptrdiff_t,
-                                         const value_type*,
-                                         const value_type&> {
-   public:
-    ConstIter(const Streamlike* s,
-              typename std::list<value_type>::iterator pos)
-        : s_(s), pos_(pos) {}
-
-    const value_type& operator*() const { return *pos_; }
-    const value_type* operator->() const { return &*pos_; }
-    ConstIter& operator++() {
-      s_->remainder_.erase(pos_++);
-      return *this;
-    }
-
-    // *iter++ is required to work (see std::istreambuf_iterator).
-    // (void)iter++ is also required to work.
-    class PostIncrProxy {
-     public:
-      explicit PostIncrProxy(const value_type& value) : value_(value) {}
-      value_type operator*() const { return value_; }
-     private:
-      value_type value_;
-    };
-    PostIncrProxy operator++(int) {
-      PostIncrProxy proxy(**this);
-      ++(*this);
-      return proxy;
-    }
-
-    friend bool operator==(const ConstIter& a, const ConstIter& b) {
-      return a.s_ == b.s_ && a.pos_ == b.pos_;
-    }
-    friend bool operator!=(const ConstIter& a, const ConstIter& b) {
-      return !(a == b);
-    }
-
-   private:
-    const Streamlike* s_;
-    typename std::list<value_type>::iterator pos_;
-  };
-
-  friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
-    os << "[";
-    typedef typename std::list<value_type>::const_iterator Iter;
-    const char* sep = "";
-    for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
-      os << sep << *it;
-      sep = ",";
-    }
-    os << "]";
-    return os;
-  }
-
-  mutable std::list<value_type> remainder_;  // modified by iteration
-};
-
-TEST(StreamlikeTest, Iteration) {
-  const int a[5] = {2, 1, 4, 5, 3};
-  Streamlike<int> s(a, a + 5);
-  Streamlike<int>::const_iterator it = s.begin();
-  const int* ip = a;
-  while (it != s.end()) {
-    SCOPED_TRACE(ip - a);
-    EXPECT_EQ(*ip++, *it++);
-  }
-}
-
-TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
-  std::forward_list<int> container;
-  EXPECT_THAT(container, BeginEndDistanceIs(0));
-  EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
-  container.push_front(0);
-  EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
-  EXPECT_THAT(container, BeginEndDistanceIs(1));
-  container.push_front(0);
-  EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
-  EXPECT_THAT(container, BeginEndDistanceIs(2));
-}
-
-TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
-  const int a[5] = {1, 2, 3, 4, 5};
-  Streamlike<int> s(a, a + 5);
-  EXPECT_THAT(s, BeginEndDistanceIs(5));
-}
-
-TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
-  Matcher<vector<int> > m = BeginEndDistanceIs(2);
-  EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
-  EXPECT_EQ("distance between begin() and end() isn't equal to 2",
-            DescribeNegation(m));
-}
-
-TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
-  ContainerHelper helper;
-  EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));
-  helper.Call(MakeUniquePtrs({1, 2}));
-}
-
-TEST(BeginEndDistanceIsTest, ExplainsResult) {
-  Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
-  Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
-  Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
-  Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
-  vector<int> container;
-  EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
-            Explain(m1, container));
-  EXPECT_EQ("whose distance between begin() and end() 0 matches",
-            Explain(m2, container));
-  EXPECT_EQ("whose distance between begin() and end() 0 matches",
-            Explain(m3, container));
-  EXPECT_EQ(
-      "whose distance between begin() and end() 0 doesn't match, which is 1 "
-      "less than 1",
-      Explain(m4, container));
-  container.push_back(0);
-  container.push_back(0);
-  EXPECT_EQ("whose distance between begin() and end() 2 matches",
-            Explain(m1, container));
-  EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
-            Explain(m2, container));
-  EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
-            Explain(m3, container));
-  EXPECT_EQ(
-      "whose distance between begin() and end() 2 matches, which is 1 more "
-      "than 1",
-      Explain(m4, container));
-}
-
-TEST(WhenSortedTest, WorksForStreamlike) {
-  // Streamlike 'container' provides only minimal iterator support.
-  // Its iterators are tagged with input_iterator_tag.
-  const int a[5] = {2, 1, 4, 5, 3};
-  Streamlike<int> s(std::begin(a), std::end(a));
-  EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
-  EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
-}
-
-TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
-  const int a[] = {2, 1, 4, 5, 3};
-  Streamlike<int> s(std::begin(a), std::end(a));
-  Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
-  EXPECT_THAT(s, WhenSorted(vector_match));
-  EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
-}
-
-TEST(IsSupersetOfTest, WorksForNativeArray) {
-  const int subset[] = {1, 4};
-  const int superset[] = {1, 2, 4};
-  const int disjoint[] = {1, 0, 3};
-  EXPECT_THAT(subset, IsSupersetOf(subset));
-  EXPECT_THAT(subset, Not(IsSupersetOf(superset)));
-  EXPECT_THAT(superset, IsSupersetOf(subset));
-  EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));
-  EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));
-}
-
-TEST(IsSupersetOfTest, WorksWithDuplicates) {
-  const int not_enough[] = {1, 2};
-  const int enough[] = {1, 1, 2};
-  const int expected[] = {1, 1};
-  EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));
-  EXPECT_THAT(enough, IsSupersetOf(expected));
-}
-
-TEST(IsSupersetOfTest, WorksForEmpty) {
-  vector<int> numbers;
-  vector<int> expected;
-  EXPECT_THAT(numbers, IsSupersetOf(expected));
-  expected.push_back(1);
-  EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
-  expected.clear();
-  numbers.push_back(1);
-  numbers.push_back(2);
-  EXPECT_THAT(numbers, IsSupersetOf(expected));
-  expected.push_back(1);
-  EXPECT_THAT(numbers, IsSupersetOf(expected));
-  expected.push_back(2);
-  EXPECT_THAT(numbers, IsSupersetOf(expected));
-  expected.push_back(3);
-  EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
-}
-
-TEST(IsSupersetOfTest, WorksForStreamlike) {
-  const int a[5] = {1, 2, 3, 4, 5};
-  Streamlike<int> s(std::begin(a), std::end(a));
-
-  vector<int> expected;
-  expected.push_back(1);
-  expected.push_back(2);
-  expected.push_back(5);
-  EXPECT_THAT(s, IsSupersetOf(expected));
-
-  expected.push_back(0);
-  EXPECT_THAT(s, Not(IsSupersetOf(expected)));
-}
-
-TEST(IsSupersetOfTest, TakesStlContainer) {
-  const int actual[] = {3, 1, 2};
-
-  ::std::list<int> expected;
-  expected.push_back(1);
-  expected.push_back(3);
-  EXPECT_THAT(actual, IsSupersetOf(expected));
-
-  expected.push_back(4);
-  EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
-}
-
-TEST(IsSupersetOfTest, Describe) {
-  typedef std::vector<int> IntVec;
-  IntVec expected;
-  expected.push_back(111);
-  expected.push_back(222);
-  expected.push_back(333);
-  EXPECT_THAT(
-      Describe<IntVec>(IsSupersetOf(expected)),
-      Eq("a surjection from elements to requirements exists such that:\n"
-         " - an element is equal to 111\n"
-         " - an element is equal to 222\n"
-         " - an element is equal to 333"));
-}
-
-TEST(IsSupersetOfTest, DescribeNegation) {
-  typedef std::vector<int> IntVec;
-  IntVec expected;
-  expected.push_back(111);
-  expected.push_back(222);
-  expected.push_back(333);
-  EXPECT_THAT(
-      DescribeNegation<IntVec>(IsSupersetOf(expected)),
-      Eq("no surjection from elements to requirements exists such that:\n"
-         " - an element is equal to 111\n"
-         " - an element is equal to 222\n"
-         " - an element is equal to 333"));
-}
-
-TEST(IsSupersetOfTest, MatchAndExplain) {
-  std::vector<int> v;
-  v.push_back(2);
-  v.push_back(3);
-  std::vector<int> expected;
-  expected.push_back(1);
-  expected.push_back(2);
-  StringMatchResultListener listener;
-  ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
-      << listener.str();
-  EXPECT_THAT(listener.str(),
-              Eq("where the following matchers don't match any elements:\n"
-                 "matcher #0: is equal to 1"));
-
-  v.push_back(1);
-  listener.Clear();
-  ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
-      << listener.str();
-  EXPECT_THAT(listener.str(), Eq("where:\n"
-                                 " - element #0 is matched by matcher #1,\n"
-                                 " - element #2 is matched by matcher #0"));
-}
-
-TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
-  const int numbers[] = {1, 3, 6, 2, 4, 5};
-  EXPECT_THAT(numbers, IsSupersetOf({1, 2}));
-  EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));
-}
-
-TEST(IsSupersetOfTest, WorksWithMoveOnly) {
-  ContainerHelper helper;
-  EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));
-  helper.Call(MakeUniquePtrs({1, 2}));
-  EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));
-  helper.Call(MakeUniquePtrs({2}));
-}
-
-TEST(IsSubsetOfTest, WorksForNativeArray) {
-  const int subset[] = {1, 4};
-  const int superset[] = {1, 2, 4};
-  const int disjoint[] = {1, 0, 3};
-  EXPECT_THAT(subset, IsSubsetOf(subset));
-  EXPECT_THAT(subset, IsSubsetOf(superset));
-  EXPECT_THAT(superset, Not(IsSubsetOf(subset)));
-  EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));
-  EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));
-}
-
-TEST(IsSubsetOfTest, WorksWithDuplicates) {
-  const int not_enough[] = {1, 2};
-  const int enough[] = {1, 1, 2};
-  const int actual[] = {1, 1};
-  EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));
-  EXPECT_THAT(actual, IsSubsetOf(enough));
-}
-
-TEST(IsSubsetOfTest, WorksForEmpty) {
-  vector<int> numbers;
-  vector<int> expected;
-  EXPECT_THAT(numbers, IsSubsetOf(expected));
-  expected.push_back(1);
-  EXPECT_THAT(numbers, IsSubsetOf(expected));
-  expected.clear();
-  numbers.push_back(1);
-  numbers.push_back(2);
-  EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
-  expected.push_back(1);
-  EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
-  expected.push_back(2);
-  EXPECT_THAT(numbers, IsSubsetOf(expected));
-  expected.push_back(3);
-  EXPECT_THAT(numbers, IsSubsetOf(expected));
-}
-
-TEST(IsSubsetOfTest, WorksForStreamlike) {
-  const int a[5] = {1, 2};
-  Streamlike<int> s(std::begin(a), std::end(a));
-
-  vector<int> expected;
-  expected.push_back(1);
-  EXPECT_THAT(s, Not(IsSubsetOf(expected)));
-  expected.push_back(2);
-  expected.push_back(5);
-  EXPECT_THAT(s, IsSubsetOf(expected));
-}
-
-TEST(IsSubsetOfTest, TakesStlContainer) {
-  const int actual[] = {3, 1, 2};
-
-  ::std::list<int> expected;
-  expected.push_back(1);
-  expected.push_back(3);
-  EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
-
-  expected.push_back(2);
-  expected.push_back(4);
-  EXPECT_THAT(actual, IsSubsetOf(expected));
-}
-
-TEST(IsSubsetOfTest, Describe) {
-  typedef std::vector<int> IntVec;
-  IntVec expected;
-  expected.push_back(111);
-  expected.push_back(222);
-  expected.push_back(333);
-
-  EXPECT_THAT(
-      Describe<IntVec>(IsSubsetOf(expected)),
-      Eq("an injection from elements to requirements exists such that:\n"
-         " - an element is equal to 111\n"
-         " - an element is equal to 222\n"
-         " - an element is equal to 333"));
-}
-
-TEST(IsSubsetOfTest, DescribeNegation) {
-  typedef std::vector<int> IntVec;
-  IntVec expected;
-  expected.push_back(111);
-  expected.push_back(222);
-  expected.push_back(333);
-  EXPECT_THAT(
-      DescribeNegation<IntVec>(IsSubsetOf(expected)),
-      Eq("no injection from elements to requirements exists such that:\n"
-         " - an element is equal to 111\n"
-         " - an element is equal to 222\n"
-         " - an element is equal to 333"));
-}
-
-TEST(IsSubsetOfTest, MatchAndExplain) {
-  std::vector<int> v;
-  v.push_back(2);
-  v.push_back(3);
-  std::vector<int> expected;
-  expected.push_back(1);
-  expected.push_back(2);
-  StringMatchResultListener listener;
-  ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
-      << listener.str();
-  EXPECT_THAT(listener.str(),
-              Eq("where the following elements don't match any matchers:\n"
-                 "element #1: 3"));
-
-  expected.push_back(3);
-  listener.Clear();
-  ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
-      << listener.str();
-  EXPECT_THAT(listener.str(), Eq("where:\n"
-                                 " - element #0 is matched by matcher #1,\n"
-                                 " - element #1 is matched by matcher #2"));
-}
-
-TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
-  const int numbers[] = {1, 2, 3};
-  EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));
-  EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));
-}
-
-TEST(IsSubsetOfTest, WorksWithMoveOnly) {
-  ContainerHelper helper;
-  EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));
-  helper.Call(MakeUniquePtrs({1}));
-  EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));
-  helper.Call(MakeUniquePtrs({2}));
-}
-
-// Tests using ElementsAre() and ElementsAreArray() with stream-like
-// "containers".
-
-TEST(ElemensAreStreamTest, WorksForStreamlike) {
-  const int a[5] = {1, 2, 3, 4, 5};
-  Streamlike<int> s(std::begin(a), std::end(a));
-  EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
-  EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
-}
-
-TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
-  const int a[5] = {1, 2, 3, 4, 5};
-  Streamlike<int> s(std::begin(a), std::end(a));
-
-  vector<int> expected;
-  expected.push_back(1);
-  expected.push_back(2);
-  expected.push_back(3);
-  expected.push_back(4);
-  expected.push_back(5);
-  EXPECT_THAT(s, ElementsAreArray(expected));
-
-  expected[3] = 0;
-  EXPECT_THAT(s, Not(ElementsAreArray(expected)));
-}
-
-TEST(ElementsAreTest, WorksWithUncopyable) {
-  Uncopyable objs[2];
-  objs[0].set_value(-3);
-  objs[1].set_value(1);
-  EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
-}
-
-TEST(ElementsAreTest, WorksWithMoveOnly) {
-  ContainerHelper helper;
-  EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));
-  helper.Call(MakeUniquePtrs({1, 2}));
-
-  EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));
-  helper.Call(MakeUniquePtrs({3, 4}));
-}
-
-TEST(ElementsAreTest, TakesStlContainer) {
-  const int actual[] = {3, 1, 2};
-
-  ::std::list<int> expected;
-  expected.push_back(3);
-  expected.push_back(1);
-  expected.push_back(2);
-  EXPECT_THAT(actual, ElementsAreArray(expected));
-
-  expected.push_back(4);
-  EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
-}
-
-// Tests for UnorderedElementsAreArray()
-
-TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
-  const int a[] = {0, 1, 2, 3, 4};
-  std::vector<int> s(std::begin(a), std::end(a));
-  do {
-    StringMatchResultListener listener;
-    EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
-                                   s, &listener)) << listener.str();
-  } while (std::next_permutation(s.begin(), s.end()));
-}
-
-TEST(UnorderedElementsAreArrayTest, VectorBool) {
-  const bool a[] = {0, 1, 0, 1, 1};
-  const bool b[] = {1, 0, 1, 1, 0};
-  std::vector<bool> expected(std::begin(a), std::end(a));
-  std::vector<bool> actual(std::begin(b), std::end(b));
-  StringMatchResultListener listener;
-  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
-                                 actual, &listener)) << listener.str();
-}
-
-TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
-  // Streamlike 'container' provides only minimal iterator support.
-  // Its iterators are tagged with input_iterator_tag, and it has no
-  // size() or empty() methods.
-  const int a[5] = {2, 1, 4, 5, 3};
-  Streamlike<int> s(std::begin(a), std::end(a));
-
-  ::std::vector<int> expected;
-  expected.push_back(1);
-  expected.push_back(2);
-  expected.push_back(3);
-  expected.push_back(4);
-  expected.push_back(5);
-  EXPECT_THAT(s, UnorderedElementsAreArray(expected));
-
-  expected.push_back(6);
-  EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
-}
-
-TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
-  const int actual[] = {3, 1, 2};
-
-  ::std::list<int> expected;
-  expected.push_back(1);
-  expected.push_back(2);
-  expected.push_back(3);
-  EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
-
-  expected.push_back(4);
-  EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
-}
-
-
-TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
-  const int a[5] = {2, 1, 4, 5, 3};
-  EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
-  EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
-}
-
-TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
-  const std::string a[5] = {"a", "b", "c", "d", "e"};
-  EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
-  EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
-}
-
-TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
-  const int a[5] = {2, 1, 4, 5, 3};
-  EXPECT_THAT(a, UnorderedElementsAreArray(
-      {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
-  EXPECT_THAT(a, Not(UnorderedElementsAreArray(
-      {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
-}
-
-TEST(UnorderedElementsAreArrayTest,
-     TakesInitializerListOfDifferentTypedMatchers) {
-  const int a[5] = {2, 1, 4, 5, 3};
-  // The compiler cannot infer the type of the initializer list if its
-  // elements have different types.  We must explicitly specify the
-  // unified element type in this case.
-  EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
-      {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
-  EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
-      {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
-}
-
-
-TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
-  ContainerHelper helper;
-  EXPECT_CALL(helper,
-              Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
-  helper.Call(MakeUniquePtrs({2, 1}));
-}
-
-class UnorderedElementsAreTest : public testing::Test {
- protected:
-  typedef std::vector<int> IntVec;
-};
-
-TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
-  Uncopyable objs[2];
-  objs[0].set_value(-3);
-  objs[1].set_value(1);
-  EXPECT_THAT(objs,
-              UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
-}
-
-TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
-  const int a[] = {1, 2, 3};
-  std::vector<int> s(std::begin(a), std::end(a));
-  do {
-    StringMatchResultListener listener;
-    EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
-                                   s, &listener)) << listener.str();
-  } while (std::next_permutation(s.begin(), s.end()));
-}
-
-TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
-  const int a[] = {1, 2, 3};
-  std::vector<int> s(std::begin(a), std::end(a));
-  std::vector<Matcher<int> > mv;
-  mv.push_back(1);
-  mv.push_back(2);
-  mv.push_back(2);
-  // The element with value '3' matches nothing: fail fast.
-  StringMatchResultListener listener;
-  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
-                                  s, &listener)) << listener.str();
-}
-
-TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
-  // Streamlike 'container' provides only minimal iterator support.
-  // Its iterators are tagged with input_iterator_tag, and it has no
-  // size() or empty() methods.
-  const int a[5] = {2, 1, 4, 5, 3};
-  Streamlike<int> s(std::begin(a), std::end(a));
-
-  EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
-  EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
-}
-
-TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
-  ContainerHelper helper;
-  EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
-  helper.Call(MakeUniquePtrs({2, 1}));
-}
-
-// One naive implementation of the matcher runs in O(N!) time, which is too
-// slow for many real-world inputs. This test shows that our matcher can match
-// 100 inputs very quickly (a few milliseconds).  An O(100!) is 10^158
-// iterations and obviously effectively incomputable.
-// [ RUN      ] UnorderedElementsAreTest.Performance
-// [       OK ] UnorderedElementsAreTest.Performance (4 ms)
-TEST_F(UnorderedElementsAreTest, Performance) {
-  std::vector<int> s;
-  std::vector<Matcher<int> > mv;
-  for (int i = 0; i < 100; ++i) {
-    s.push_back(i);
-    mv.push_back(_);
-  }
-  mv[50] = Eq(0);
-  StringMatchResultListener listener;
-  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
-                                 s, &listener)) << listener.str();
-}
-
-// Another variant of 'Performance' with similar expectations.
-// [ RUN      ] UnorderedElementsAreTest.PerformanceHalfStrict
-// [       OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
-TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
-  std::vector<int> s;
-  std::vector<Matcher<int> > mv;
-  for (int i = 0; i < 100; ++i) {
-    s.push_back(i);
-    if (i & 1) {
-      mv.push_back(_);
-    } else {
-      mv.push_back(i);
-    }
-  }
-  StringMatchResultListener listener;
-  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
-                                 s, &listener)) << listener.str();
-}
-
-TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
-  std::vector<int> v;
-  v.push_back(4);
-  StringMatchResultListener listener;
-  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
-                                  v, &listener)) << listener.str();
-  EXPECT_THAT(listener.str(), Eq("which has 1 element"));
-}
-
-TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
-  std::vector<int> v;
-  StringMatchResultListener listener;
-  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
-                                  v, &listener)) << listener.str();
-  EXPECT_THAT(listener.str(), Eq(""));
-}
-
-TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
-  std::vector<int> v;
-  v.push_back(1);
-  v.push_back(1);
-  StringMatchResultListener listener;
-  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
-                                  v, &listener)) << listener.str();
-  EXPECT_THAT(
-      listener.str(),
-      Eq("where the following matchers don't match any elements:\n"
-         "matcher #1: is equal to 2"));
-}
-
-TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
-  std::vector<int> v;
-  v.push_back(1);
-  v.push_back(2);
-  StringMatchResultListener listener;
-  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
-                                  v, &listener)) << listener.str();
-  EXPECT_THAT(
-      listener.str(),
-      Eq("where the following elements don't match any matchers:\n"
-         "element #1: 2"));
-}
-
-TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
-  std::vector<int> v;
-  v.push_back(2);
-  v.push_back(3);
-  StringMatchResultListener listener;
-  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
-                                  v, &listener)) << listener.str();
-  EXPECT_THAT(
-      listener.str(),
-      Eq("where"
-         " the following matchers don't match any elements:\n"
-         "matcher #0: is equal to 1\n"
-         "and"
-         " where"
-         " the following elements don't match any matchers:\n"
-         "element #1: 3"));
-}
-
-// Test helper for formatting element, matcher index pairs in expectations.
-static std::string EMString(int element, int matcher) {
-  stringstream ss;
-  ss << "(element #" << element << ", matcher #" << matcher << ")";
-  return ss.str();
-}
-
-TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
-  // A situation where all elements and matchers have a match
-  // associated with them, but the max matching is not perfect.
-  std::vector<std::string> v;
-  v.push_back("a");
-  v.push_back("b");
-  v.push_back("c");
-  StringMatchResultListener listener;
-  EXPECT_FALSE(ExplainMatchResult(
-      UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
-      << listener.str();
-
-  std::string prefix =
-      "where no permutation of the elements can satisfy all matchers, "
-      "and the closest match is 2 of 3 matchers with the "
-      "pairings:\n";
-
-  // We have to be a bit loose here, because there are 4 valid max matches.
-  EXPECT_THAT(
-      listener.str(),
-      AnyOf(prefix + "{\n  " + EMString(0, 0) +
-                     ",\n  " + EMString(1, 2) + "\n}",
-            prefix + "{\n  " + EMString(0, 1) +
-                     ",\n  " + EMString(1, 2) + "\n}",
-            prefix + "{\n  " + EMString(0, 0) +
-                     ",\n  " + EMString(2, 2) + "\n}",
-            prefix + "{\n  " + EMString(0, 1) +
-                     ",\n  " + EMString(2, 2) + "\n}"));
-}
-
-TEST_F(UnorderedElementsAreTest, Describe) {
-  EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
-              Eq("is empty"));
-  EXPECT_THAT(
-      Describe<IntVec>(UnorderedElementsAre(345)),
-      Eq("has 1 element and that element is equal to 345"));
-  EXPECT_THAT(
-      Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
-      Eq("has 3 elements and there exists some permutation "
-         "of elements such that:\n"
-         " - element #0 is equal to 111, and\n"
-         " - element #1 is equal to 222, and\n"
-         " - element #2 is equal to 333"));
-}
-
-TEST_F(UnorderedElementsAreTest, DescribeNegation) {
-  EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
-              Eq("isn't empty"));
-  EXPECT_THAT(
-      DescribeNegation<IntVec>(UnorderedElementsAre(345)),
-      Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
-  EXPECT_THAT(
-      DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
-      Eq("doesn't have 3 elements, or there exists no permutation "
-         "of elements such that:\n"
-         " - element #0 is equal to 123, and\n"
-         " - element #1 is equal to 234, and\n"
-         " - element #2 is equal to 345"));
-}
-
-namespace {
-
-// Used as a check on the more complex max flow method used in the
-// real testing::internal::FindMaxBipartiteMatching. This method is
-// compatible but runs in worst-case factorial time, so we only
-// use it in testing for small problem sizes.
-template <typename Graph>
-class BacktrackingMaxBPMState {
- public:
-  // Does not take ownership of 'g'.
-  explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
-
-  ElementMatcherPairs Compute() {
-    if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
-      return best_so_far_;
-    }
-    lhs_used_.assign(graph_->LhsSize(), kUnused);
-    rhs_used_.assign(graph_->RhsSize(), kUnused);
-    for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
-      matches_.clear();
-      RecurseInto(irhs);
-      if (best_so_far_.size() == graph_->RhsSize())
-        break;
-    }
-    return best_so_far_;
-  }
-
- private:
-  static const size_t kUnused = static_cast<size_t>(-1);
-
-  void PushMatch(size_t lhs, size_t rhs) {
-    matches_.push_back(ElementMatcherPair(lhs, rhs));
-    lhs_used_[lhs] = rhs;
-    rhs_used_[rhs] = lhs;
-    if (matches_.size() > best_so_far_.size()) {
-      best_so_far_ = matches_;
-    }
-  }
-
-  void PopMatch() {
-    const ElementMatcherPair& back = matches_.back();
-    lhs_used_[back.first] = kUnused;
-    rhs_used_[back.second] = kUnused;
-    matches_.pop_back();
-  }
-
-  bool RecurseInto(size_t irhs) {
-    if (rhs_used_[irhs] != kUnused) {
-      return true;
-    }
-    for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
-      if (lhs_used_[ilhs] != kUnused) {
-        continue;
-      }
-      if (!graph_->HasEdge(ilhs, irhs)) {
-        continue;
-      }
-      PushMatch(ilhs, irhs);
-      if (best_so_far_.size() == graph_->RhsSize()) {
-        return false;
-      }
-      for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
-        if (!RecurseInto(mi)) return false;
-      }
-      PopMatch();
-    }
-    return true;
-  }
-
-  const Graph* graph_;  // not owned
-  std::vector<size_t> lhs_used_;
-  std::vector<size_t> rhs_used_;
-  ElementMatcherPairs matches_;
-  ElementMatcherPairs best_so_far_;
-};
-
-template <typename Graph>
-const size_t BacktrackingMaxBPMState<Graph>::kUnused;
-
-}  // namespace
-
-// Implement a simple backtracking algorithm to determine if it is possible
-// to find one element per matcher, without reusing elements.
-template <typename Graph>
-ElementMatcherPairs
-FindBacktrackingMaxBPM(const Graph& g) {
-  return BacktrackingMaxBPMState<Graph>(&g).Compute();
-}
-
-class BacktrackingBPMTest : public ::testing::Test { };
-
-// Tests the MaxBipartiteMatching algorithm with square matrices.
-// The single int param is the # of nodes on each of the left and right sides.
-class BipartiteTest : public ::testing::TestWithParam<size_t> {};
-
-// Verify all match graphs up to some moderate number of edges.
-TEST_P(BipartiteTest, Exhaustive) {
-  size_t nodes = GetParam();
-  MatchMatrix graph(nodes, nodes);
-  do {
-    ElementMatcherPairs matches =
-        internal::FindMaxBipartiteMatching(graph);
-    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
-        << "graph: " << graph.DebugString();
-    // Check that all elements of matches are in the graph.
-    // Check that elements of first and second are unique.
-    std::vector<bool> seen_element(graph.LhsSize());
-    std::vector<bool> seen_matcher(graph.RhsSize());
-    SCOPED_TRACE(PrintToString(matches));
-    for (size_t i = 0; i < matches.size(); ++i) {
-      size_t ilhs = matches[i].first;
-      size_t irhs = matches[i].second;
-      EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
-      EXPECT_FALSE(seen_element[ilhs]);
-      EXPECT_FALSE(seen_matcher[irhs]);
-      seen_element[ilhs] = true;
-      seen_matcher[irhs] = true;
-    }
-  } while (graph.NextGraph());
-}
-
-INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest,
-                         ::testing::Range(size_t{0}, size_t{5}));
-
-// Parameterized by a pair interpreted as (LhsSize, RhsSize).
-class BipartiteNonSquareTest
-    : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
-};
-
-TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
-  //   .......
-  // 0:-----\ :
-  // 1:---\ | :
-  // 2:---\ | :
-  // 3:-\ | | :
-  //  :.......:
-  //    0 1 2
-  MatchMatrix g(4, 3);
-  constexpr std::array<std::array<size_t, 2>, 4> kEdges = {
-      {{{0, 2}}, {{1, 1}}, {{2, 1}}, {{3, 0}}}};
-  for (size_t i = 0; i < kEdges.size(); ++i) {
-    g.SetEdge(kEdges[i][0], kEdges[i][1], true);
-  }
-  EXPECT_THAT(FindBacktrackingMaxBPM(g),
-              ElementsAre(Pair(3, 0),
-                          Pair(AnyOf(1, 2), 1),
-                          Pair(0, 2))) << g.DebugString();
-}
-
-// Verify a few nonsquare matrices.
-TEST_P(BipartiteNonSquareTest, Exhaustive) {
-  size_t nlhs = GetParam().first;
-  size_t nrhs = GetParam().second;
-  MatchMatrix graph(nlhs, nrhs);
-  do {
-    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
-              internal::FindMaxBipartiteMatching(graph).size())
-        << "graph: " << graph.DebugString()
-        << "\nbacktracking: "
-        << PrintToString(FindBacktrackingMaxBPM(graph))
-        << "\nmax flow: "
-        << PrintToString(internal::FindMaxBipartiteMatching(graph));
-  } while (graph.NextGraph());
-}
-
-INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteNonSquareTest,
-    testing::Values(
-        std::make_pair(1, 2),
-        std::make_pair(2, 1),
-        std::make_pair(3, 2),
-        std::make_pair(2, 3),
-        std::make_pair(4, 1),
-        std::make_pair(1, 4),
-        std::make_pair(4, 3),
-        std::make_pair(3, 4)));
-
-class BipartiteRandomTest
-    : public ::testing::TestWithParam<std::pair<int, int> > {
-};
-
-// Verifies a large sample of larger graphs.
-TEST_P(BipartiteRandomTest, LargerNets) {
-  int nodes = GetParam().first;
-  int iters = GetParam().second;
-  MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes));
-
-  auto seed = static_cast<uint32_t>(GTEST_FLAG(random_seed));
-  if (seed == 0) {
-    seed = static_cast<uint32_t>(time(nullptr));
-  }
-
-  for (; iters > 0; --iters, ++seed) {
-    srand(static_cast<unsigned int>(seed));
-    graph.Randomize();
-    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
-              internal::FindMaxBipartiteMatching(graph).size())
-        << " graph: " << graph.DebugString()
-        << "\nTo reproduce the failure, rerun the test with the flag"
-           " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
-  }
-}
-
-// Test argument is a std::pair<int, int> representing (nodes, iters).
-INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest,
-    testing::Values(
-        std::make_pair(5, 10000),
-        std::make_pair(6, 5000),
-        std::make_pair(7, 2000),
-        std::make_pair(8, 500),
-        std::make_pair(9, 100)));
-
-// Tests IsReadableTypeName().
-
-TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
-  EXPECT_TRUE(IsReadableTypeName("int"));
-  EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
-  EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
-  EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
-}
-
-TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
-  EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
-  EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
-  EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
-}
-
-TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
-  EXPECT_FALSE(
-      IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
-  EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
-}
-
-TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
-  EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
-}
-
-// Tests FormatMatcherDescription().
-
-TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
-  EXPECT_EQ("is even",
-            FormatMatcherDescription(false, "IsEven", Strings()));
-  EXPECT_EQ("not (is even)",
-            FormatMatcherDescription(true, "IsEven", Strings()));
-
-  const char* params[] = {"5"};
-  EXPECT_EQ("equals 5",
-            FormatMatcherDescription(false, "Equals",
-                                     Strings(params, params + 1)));
-
-  const char* params2[] = {"5", "8"};
-  EXPECT_EQ("is in range (5, 8)",
-            FormatMatcherDescription(false, "IsInRange",
-                                     Strings(params2, params2 + 2)));
-}
-
-// Tests PolymorphicMatcher::mutable_impl().
-TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
-  PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
-  DivisibleByImpl& impl = m.mutable_impl();
-  EXPECT_EQ(42, impl.divider());
-
-  impl.set_divider(0);
-  EXPECT_EQ(0, m.mutable_impl().divider());
-}
-
-// Tests PolymorphicMatcher::impl().
-TEST(PolymorphicMatcherTest, CanAccessImpl) {
-  const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
-  const DivisibleByImpl& impl = m.impl();
-  EXPECT_EQ(42, impl.divider());
-}
-
-TEST(MatcherTupleTest, ExplainsMatchFailure) {
-  stringstream ss1;
-  ExplainMatchFailureTupleTo(
-      std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
-      std::make_tuple('a', 10), &ss1);
-  EXPECT_EQ("", ss1.str());  // Successful match.
-
-  stringstream ss2;
-  ExplainMatchFailureTupleTo(
-      std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
-      std::make_tuple(2, 'b'), &ss2);
-  EXPECT_EQ("  Expected arg #0: is > 5\n"
-            "           Actual: 2, which is 3 less than 5\n"
-            "  Expected arg #1: is equal to 'a' (97, 0x61)\n"
-            "           Actual: 'b' (98, 0x62)\n",
-            ss2.str());  // Failed match where both arguments need explanation.
-
-  stringstream ss3;
-  ExplainMatchFailureTupleTo(
-      std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
-      std::make_tuple(2, 'a'), &ss3);
-  EXPECT_EQ("  Expected arg #0: is > 5\n"
-            "           Actual: 2, which is 3 less than 5\n",
-            ss3.str());  // Failed match where only one argument needs
-                         // explanation.
-}
-
-// Tests Each().
-
-TEST(EachTest, ExplainsMatchResultCorrectly) {
-  set<int> a;  // empty
-
-  Matcher<set<int> > m = Each(2);
-  EXPECT_EQ("", Explain(m, a));
-
-  Matcher<const int(&)[1]> n = Each(1);  // NOLINT
-
-  const int b[1] = {1};
-  EXPECT_EQ("", Explain(n, b));
-
-  n = Each(3);
-  EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
-
-  a.insert(1);
-  a.insert(2);
-  a.insert(3);
-  m = Each(GreaterThan(0));
-  EXPECT_EQ("", Explain(m, a));
-
-  m = Each(GreaterThan(10));
-  EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
-            Explain(m, a));
-}
-
-TEST(EachTest, DescribesItselfCorrectly) {
-  Matcher<vector<int> > m = Each(1);
-  EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
-
-  Matcher<vector<int> > m2 = Not(m);
-  EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
-}
-
-TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
-  vector<int> some_vector;
-  EXPECT_THAT(some_vector, Each(1));
-  some_vector.push_back(3);
-  EXPECT_THAT(some_vector, Not(Each(1)));
-  EXPECT_THAT(some_vector, Each(3));
-  some_vector.push_back(1);
-  some_vector.push_back(2);
-  EXPECT_THAT(some_vector, Not(Each(3)));
-  EXPECT_THAT(some_vector, Each(Lt(3.5)));
-
-  vector<std::string> another_vector;
-  another_vector.push_back("fee");
-  EXPECT_THAT(another_vector, Each(std::string("fee")));
-  another_vector.push_back("fie");
-  another_vector.push_back("foe");
-  another_vector.push_back("fum");
-  EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
-}
-
-TEST(EachTest, MatchesMapWhenAllElementsMatch) {
-  map<const char*, int> my_map;
-  const char* bar = "a string";
-  my_map[bar] = 2;
-  EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
-
-  map<std::string, int> another_map;
-  EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
-  another_map["fee"] = 1;
-  EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
-  another_map["fie"] = 2;
-  another_map["foe"] = 3;
-  another_map["fum"] = 4;
-  EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
-  EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
-  EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
-}
-
-TEST(EachTest, AcceptsMatcher) {
-  const int a[] = {1, 2, 3};
-  EXPECT_THAT(a, Each(Gt(0)));
-  EXPECT_THAT(a, Not(Each(Gt(1))));
-}
-
-TEST(EachTest, WorksForNativeArrayAsTuple) {
-  const int a[] = {1, 2};
-  const int* const pointer = a;
-  EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));
-  EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));
-}
-
-TEST(EachTest, WorksWithMoveOnly) {
-  ContainerHelper helper;
-  EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));
-  helper.Call(MakeUniquePtrs({1, 2}));
-}
-
-// For testing Pointwise().
-class IsHalfOfMatcher {
- public:
-  template <typename T1, typename T2>
-  bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,
-                       MatchResultListener* listener) const {
-    if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {
-      *listener << "where the second is " << std::get<1>(a_pair);
-      return true;
-    } else {
-      *listener << "where the second/2 is " << std::get<1>(a_pair) / 2;
-      return false;
-    }
-  }
-
-  void DescribeTo(ostream* os) const {
-    *os << "are a pair where the first is half of the second";
-  }
-
-  void DescribeNegationTo(ostream* os) const {
-    *os << "are a pair where the first isn't half of the second";
-  }
-};
-
-PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
-  return MakePolymorphicMatcher(IsHalfOfMatcher());
-}
-
-TEST(PointwiseTest, DescribesSelf) {
-  vector<int> rhs;
-  rhs.push_back(1);
-  rhs.push_back(2);
-  rhs.push_back(3);
-  const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
-  EXPECT_EQ("contains 3 values, where each value and its corresponding value "
-            "in { 1, 2, 3 } are a pair where the first is half of the second",
-            Describe(m));
-  EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
-            "index i where x and the i-th value of { 1, 2, 3 } are a pair "
-            "where the first isn't half of the second",
-            DescribeNegation(m));
-}
-
-TEST(PointwiseTest, MakesCopyOfRhs) {
-  list<signed char> rhs;
-  rhs.push_back(2);
-  rhs.push_back(4);
-
-  int lhs[] = {1, 2};
-  const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
-  EXPECT_THAT(lhs, m);
-
-  // Changing rhs now shouldn't affect m, which made a copy of rhs.
-  rhs.push_back(6);
-  EXPECT_THAT(lhs, m);
-}
-
-TEST(PointwiseTest, WorksForLhsNativeArray) {
-  const int lhs[] = {1, 2, 3};
-  vector<int> rhs;
-  rhs.push_back(2);
-  rhs.push_back(4);
-  rhs.push_back(6);
-  EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
-  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
-}
-
-TEST(PointwiseTest, WorksForRhsNativeArray) {
-  const int rhs[] = {1, 2, 3};
-  vector<int> lhs;
-  lhs.push_back(2);
-  lhs.push_back(4);
-  lhs.push_back(6);
-  EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
-  EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
-}
-
-// Test is effective only with sanitizers.
-TEST(PointwiseTest, WorksForVectorOfBool) {
-  vector<bool> rhs(3, false);
-  rhs[1] = true;
-  vector<bool> lhs = rhs;
-  EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
-  rhs[0] = true;
-  EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
-}
-
-
-TEST(PointwiseTest, WorksForRhsInitializerList) {
-  const vector<int> lhs{2, 4, 6};
-  EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
-  EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
-}
-
-
-TEST(PointwiseTest, RejectsWrongSize) {
-  const double lhs[2] = {1, 2};
-  const int rhs[1] = {0};
-  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
-  EXPECT_EQ("which contains 2 values",
-            Explain(Pointwise(Gt(), rhs), lhs));
-
-  const int rhs2[3] = {0, 1, 2};
-  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
-}
-
-TEST(PointwiseTest, RejectsWrongContent) {
-  const double lhs[3] = {1, 2, 3};
-  const int rhs[3] = {2, 6, 4};
-  EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
-  EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
-            "where the second/2 is 3",
-            Explain(Pointwise(IsHalfOf(), rhs), lhs));
-}
-
-TEST(PointwiseTest, AcceptsCorrectContent) {
-  const double lhs[3] = {1, 2, 3};
-  const int rhs[3] = {2, 4, 6};
-  EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
-  EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
-}
-
-TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
-  const double lhs[3] = {1, 2, 3};
-  const int rhs[3] = {2, 4, 6};
-  const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
-  EXPECT_THAT(lhs, Pointwise(m1, rhs));
-  EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
-
-  // This type works as a std::tuple<const double&, const int&> can be
-  // implicitly cast to std::tuple<double, int>.
-  const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
-  EXPECT_THAT(lhs, Pointwise(m2, rhs));
-  EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
-}
-
-MATCHER(PointeeEquals, "Points to an equal value") {
-  return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
-                            ::testing::get<0>(arg), result_listener);
-}
-
-TEST(PointwiseTest, WorksWithMoveOnly) {
-  ContainerHelper helper;
-  EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
-  helper.Call(MakeUniquePtrs({1, 2}));
-}
-
-TEST(UnorderedPointwiseTest, DescribesSelf) {
-  vector<int> rhs;
-  rhs.push_back(1);
-  rhs.push_back(2);
-  rhs.push_back(3);
-  const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
-  EXPECT_EQ(
-      "has 3 elements and there exists some permutation of elements such "
-      "that:\n"
-      " - element #0 and 1 are a pair where the first is half of the second, "
-      "and\n"
-      " - element #1 and 2 are a pair where the first is half of the second, "
-      "and\n"
-      " - element #2 and 3 are a pair where the first is half of the second",
-      Describe(m));
-  EXPECT_EQ(
-      "doesn't have 3 elements, or there exists no permutation of elements "
-      "such that:\n"
-      " - element #0 and 1 are a pair where the first is half of the second, "
-      "and\n"
-      " - element #1 and 2 are a pair where the first is half of the second, "
-      "and\n"
-      " - element #2 and 3 are a pair where the first is half of the second",
-      DescribeNegation(m));
-}
-
-TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
-  list<signed char> rhs;
-  rhs.push_back(2);
-  rhs.push_back(4);
-
-  int lhs[] = {2, 1};
-  const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
-  EXPECT_THAT(lhs, m);
-
-  // Changing rhs now shouldn't affect m, which made a copy of rhs.
-  rhs.push_back(6);
-  EXPECT_THAT(lhs, m);
-}
-
-TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
-  const int lhs[] = {1, 2, 3};
-  vector<int> rhs;
-  rhs.push_back(4);
-  rhs.push_back(6);
-  rhs.push_back(2);
-  EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
-  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
-}
-
-TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
-  const int rhs[] = {1, 2, 3};
-  vector<int> lhs;
-  lhs.push_back(4);
-  lhs.push_back(2);
-  lhs.push_back(6);
-  EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
-  EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
-}
-
-
-TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
-  const vector<int> lhs{2, 4, 6};
-  EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
-  EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
-}
-
-
-TEST(UnorderedPointwiseTest, RejectsWrongSize) {
-  const double lhs[2] = {1, 2};
-  const int rhs[1] = {0};
-  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
-  EXPECT_EQ("which has 2 elements",
-            Explain(UnorderedPointwise(Gt(), rhs), lhs));
-
-  const int rhs2[3] = {0, 1, 2};
-  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
-}
-
-TEST(UnorderedPointwiseTest, RejectsWrongContent) {
-  const double lhs[3] = {1, 2, 3};
-  const int rhs[3] = {2, 6, 6};
-  EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
-  EXPECT_EQ("where the following elements don't match any matchers:\n"
-            "element #1: 2",
-            Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
-}
-
-TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
-  const double lhs[3] = {1, 2, 3};
-  const int rhs[3] = {2, 4, 6};
-  EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
-}
-
-TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
-  const double lhs[3] = {1, 2, 3};
-  const int rhs[3] = {6, 4, 2};
-  EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
-}
-
-TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
-  const double lhs[3] = {1, 2, 3};
-  const int rhs[3] = {4, 6, 2};
-  const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
-  EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
-
-  // This type works as a std::tuple<const double&, const int&> can be
-  // implicitly cast to std::tuple<double, int>.
-  const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
-  EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
-}
-
-TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
-  ContainerHelper helper;
-  EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
-                                              std::vector<int>{1, 2})));
-  helper.Call(MakeUniquePtrs({2, 1}));
-}
-
-// Sample optional type implementation with minimal requirements for use with
-// Optional matcher.
-template <typename T>
-class SampleOptional {
- public:
-  using value_type = T;
-  explicit SampleOptional(T value)
-      : value_(std::move(value)), has_value_(true) {}
-  SampleOptional() : value_(), has_value_(false) {}
-  operator bool() const { return has_value_; }
-  const T& operator*() const { return value_; }
-
- private:
-  T value_;
-  bool has_value_;
-};
-
-TEST(OptionalTest, DescribesSelf) {
-  const Matcher<SampleOptional<int>> m = Optional(Eq(1));
-  EXPECT_EQ("value is equal to 1", Describe(m));
-}
-
-TEST(OptionalTest, ExplainsSelf) {
-  const Matcher<SampleOptional<int>> m = Optional(Eq(1));
-  EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional<int>(1)));
-  EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional<int>(2)));
-}
-
-TEST(OptionalTest, MatchesNonEmptyOptional) {
-  const Matcher<SampleOptional<int>> m1 = Optional(1);
-  const Matcher<SampleOptional<int>> m2 = Optional(Eq(2));
-  const Matcher<SampleOptional<int>> m3 = Optional(Lt(3));
-  SampleOptional<int> opt(1);
-  EXPECT_TRUE(m1.Matches(opt));
-  EXPECT_FALSE(m2.Matches(opt));
-  EXPECT_TRUE(m3.Matches(opt));
-}
-
-TEST(OptionalTest, DoesNotMatchNullopt) {
-  const Matcher<SampleOptional<int>> m = Optional(1);
-  SampleOptional<int> empty;
-  EXPECT_FALSE(m.Matches(empty));
-}
-
-TEST(OptionalTest, WorksWithMoveOnly) {
-  Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr));
-  EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr)));
-}
-
-class SampleVariantIntString {
- public:
-  SampleVariantIntString(int i) : i_(i), has_int_(true) {}
-  SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}
-
-  template <typename T>
-  friend bool holds_alternative(const SampleVariantIntString& value) {
-    return value.has_int_ == std::is_same<T, int>::value;
-  }
-
-  template <typename T>
-  friend const T& get(const SampleVariantIntString& value) {
-    return value.get_impl(static_cast<T*>(nullptr));
-  }
-
- private:
-  const int& get_impl(int*) const { return i_; }
-  const std::string& get_impl(std::string*) const { return s_; }
-
-  int i_;
-  std::string s_;
-  bool has_int_;
-};
-
-TEST(VariantTest, DescribesSelf) {
-  const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
-  EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "
-                                         "'.*' and the value is equal to 1"));
-}
-
-TEST(VariantTest, ExplainsSelf) {
-  const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
-  EXPECT_THAT(Explain(m, SampleVariantIntString(1)),
-              ContainsRegex("whose value 1"));
-  EXPECT_THAT(Explain(m, SampleVariantIntString("A")),
-              HasSubstr("whose value is not of type '"));
-  EXPECT_THAT(Explain(m, SampleVariantIntString(2)),
-              "whose value 2 doesn't match");
-}
-
-TEST(VariantTest, FullMatch) {
-  Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
-  EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));
-
-  m = VariantWith<std::string>(Eq("1"));
-  EXPECT_TRUE(m.Matches(SampleVariantIntString("1")));
-}
-
-TEST(VariantTest, TypeDoesNotMatch) {
-  Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
-  EXPECT_FALSE(m.Matches(SampleVariantIntString("1")));
-
-  m = VariantWith<std::string>(Eq("1"));
-  EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));
-}
-
-TEST(VariantTest, InnerDoesNotMatch) {
-  Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
-  EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));
-
-  m = VariantWith<std::string>(Eq("1"));
-  EXPECT_FALSE(m.Matches(SampleVariantIntString("2")));
-}
-
-class SampleAnyType {
- public:
-  explicit SampleAnyType(int i) : index_(0), i_(i) {}
-  explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}
-
-  template <typename T>
-  friend const T* any_cast(const SampleAnyType* any) {
-    return any->get_impl(static_cast<T*>(nullptr));
-  }
-
- private:
-  int index_;
-  int i_;
-  std::string s_;
-
-  const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; }
-  const std::string* get_impl(std::string*) const {
-    return index_ == 1 ? &s_ : nullptr;
-  }
-};
-
-TEST(AnyWithTest, FullMatch) {
-  Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));
-  EXPECT_TRUE(m.Matches(SampleAnyType(1)));
-}
-
-TEST(AnyWithTest, TestBadCastType) {
-  Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail"));
-  EXPECT_FALSE(m.Matches(SampleAnyType(1)));
-}
-
-TEST(AnyWithTest, TestUseInContainers) {
-  std::vector<SampleAnyType> a;
-  a.emplace_back(1);
-  a.emplace_back(2);
-  a.emplace_back(3);
-  EXPECT_THAT(
-      a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)}));
-
-  std::vector<SampleAnyType> b;
-  b.emplace_back("hello");
-  b.emplace_back("merhaba");
-  b.emplace_back("salut");
-  EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"),
-                                   AnyWith<std::string>("merhaba"),
-                                   AnyWith<std::string>("salut")}));
-}
-TEST(AnyWithTest, TestCompare) {
-  EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));
-}
-
-TEST(AnyWithTest, DescribesSelf) {
-  const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
-  EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type "
-                                         "'.*' and the value is equal to 1"));
-}
-
-TEST(AnyWithTest, ExplainsSelf) {
-  const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
-
-  EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1"));
-  EXPECT_THAT(Explain(m, SampleAnyType("A")),
-              HasSubstr("whose value is not of type '"));
-  EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match");
-}
-
-TEST(PointeeTest, WorksOnMoveOnlyType) {
-  std::unique_ptr<int> p(new int(3));
-  EXPECT_THAT(p, Pointee(Eq(3)));
-  EXPECT_THAT(p, Not(Pointee(Eq(2))));
-}
-
-TEST(NotTest, WorksOnMoveOnlyType) {
-  std::unique_ptr<int> p(new int(3));
-  EXPECT_THAT(p, Pointee(Eq(3)));
-  EXPECT_THAT(p, Not(Pointee(Eq(2))));
-}
-
-// Tests Args<k0, ..., kn>(m).
-
-TEST(ArgsTest, AcceptsZeroTemplateArg) {
-  const std::tuple<int, bool> t(5, true);
-  EXPECT_THAT(t, Args<>(Eq(std::tuple<>())));
-  EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>()))));
-}
-
-TEST(ArgsTest, AcceptsOneTemplateArg) {
-  const std::tuple<int, bool> t(5, true);
-  EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5))));
-  EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true))));
-  EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false)))));
-}
-
-TEST(ArgsTest, AcceptsTwoTemplateArgs) {
-  const std::tuple<short, int, long> t(4, 5, 6L);  // NOLINT
-
-  EXPECT_THAT(t, (Args<0, 1>(Lt())));
-  EXPECT_THAT(t, (Args<1, 2>(Lt())));
-  EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
-}
-
-TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
-  const std::tuple<short, int, long> t(4, 5, 6L);  // NOLINT
-  EXPECT_THAT(t, (Args<0, 0>(Eq())));
-  EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
-}
-
-TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
-  const std::tuple<short, int, long> t(4, 5, 6L);  // NOLINT
-  EXPECT_THAT(t, (Args<2, 0>(Gt())));
-  EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
-}
-
-MATCHER(SumIsZero, "") {
-  return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0;
-}
-
-TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
-  EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));
-  EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));
-}
-
-TEST(ArgsTest, CanBeNested) {
-  const std::tuple<short, int, long, int> t(4, 5, 6L, 6);  // NOLINT
-  EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
-  EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
-}
-
-TEST(ArgsTest, CanMatchTupleByValue) {
-  typedef std::tuple<char, int, int> Tuple3;
-  const Matcher<Tuple3> m = Args<1, 2>(Lt());
-  EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));
-  EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));
-}
-
-TEST(ArgsTest, CanMatchTupleByReference) {
-  typedef std::tuple<char, char, int> Tuple3;
-  const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
-  EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));
-  EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));
-}
-
-// Validates that arg is printed as str.
-MATCHER_P(PrintsAs, str, "") {
-  return testing::PrintToString(arg) == str;
-}
-
-TEST(ArgsTest, AcceptsTenTemplateArgs) {
-  EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
-              (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
-                  PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
-  EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
-              Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
-                  PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
-}
-
-TEST(ArgsTest, DescirbesSelfCorrectly) {
-  const Matcher<std::tuple<int, bool, char> > m = Args<2, 0>(Lt());
-  EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where "
-            "the first < the second",
-            Describe(m));
-}
-
-TEST(ArgsTest, DescirbesNestedArgsCorrectly) {
-  const Matcher<const std::tuple<int, bool, char, int>&> m =
-      Args<0, 2, 3>(Args<2, 0>(Lt()));
-  EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple "
-            "whose fields (#2, #0) are a pair where the first < the second",
-            Describe(m));
-}
-
-TEST(ArgsTest, DescribesNegationCorrectly) {
-  const Matcher<std::tuple<int, char> > m = Args<1, 0>(Gt());
-  EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair "
-            "where the first > the second",
-            DescribeNegation(m));
-}
-
-TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {
-  const Matcher<std::tuple<bool, int, int> > m = Args<1, 2>(Eq());
-  EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
-            Explain(m, std::make_tuple(false, 42, 42)));
-  EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
-            Explain(m, std::make_tuple(false, 42, 43)));
-}
-
-// For testing Args<>'s explanation.
-class LessThanMatcher : public MatcherInterface<std::tuple<char, int> > {
- public:
-  void DescribeTo(::std::ostream* /*os*/) const override {}
-
-  bool MatchAndExplain(std::tuple<char, int> value,
-                       MatchResultListener* listener) const override {
-    const int diff = std::get<0>(value) - std::get<1>(value);
-    if (diff > 0) {
-      *listener << "where the first value is " << diff
-                << " more than the second";
-    }
-    return diff < 0;
-  }
-};
-
-Matcher<std::tuple<char, int> > LessThan() {
-  return MakeMatcher(new LessThanMatcher);
-}
-
-TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {
-  const Matcher<std::tuple<char, int, int> > m = Args<0, 2>(LessThan());
-  EXPECT_EQ(
-      "whose fields (#0, #2) are ('a' (97, 0x61), 42), "
-      "where the first value is 55 more than the second",
-      Explain(m, std::make_tuple('a', 42, 42)));
-  EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
-            Explain(m, std::make_tuple('\0', 42, 43)));
-}
-
-class PredicateFormatterFromMatcherTest : public ::testing::Test {
- protected:
-  enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
-
-  // A matcher that can return different results when used multiple times on the
-  // same input. No real matcher should do this; but this lets us test that we
-  // detect such behavior and fail appropriately.
-  class MockMatcher : public MatcherInterface<Behavior> {
-   public:
-    bool MatchAndExplain(Behavior behavior,
-                         MatchResultListener* listener) const override {
-      *listener << "[MatchAndExplain]";
-      switch (behavior) {
-        case kInitialSuccess:
-          // The first call to MatchAndExplain should use a "not interested"
-          // listener; so this is expected to return |true|. There should be no
-          // subsequent calls.
-          return !listener->IsInterested();
-
-        case kAlwaysFail:
-          return false;
-
-        case kFlaky:
-          // The first call to MatchAndExplain should use a "not interested"
-          // listener; so this will return |false|. Subsequent calls should have
-          // an "interested" listener; so this will return |true|, thus
-          // simulating a flaky matcher.
-          return listener->IsInterested();
-      }
-
-      GTEST_LOG_(FATAL) << "This should never be reached";
-      return false;
-    }
-
-    void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }
-
-    void DescribeNegationTo(ostream* os) const override {
-      *os << "[DescribeNegationTo]";
-    }
-  };
-
-  AssertionResult RunPredicateFormatter(Behavior behavior) {
-    auto matcher = MakeMatcher(new MockMatcher);
-    PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(
-        matcher);
-    return predicate_formatter("dummy-name", behavior);
-  }
-};
-
-TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
-  AssertionResult result = RunPredicateFormatter(kInitialSuccess);
-  EXPECT_TRUE(result);  // Implicit cast to bool.
-  std::string expect;
-  EXPECT_EQ(expect, result.message());
-}
-
-TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
-  AssertionResult result = RunPredicateFormatter(kAlwaysFail);
-  EXPECT_FALSE(result);  // Implicit cast to bool.
-  std::string expect =
-      "Value of: dummy-name\nExpected: [DescribeTo]\n"
-      "  Actual: 1" +
-      OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
-  EXPECT_EQ(expect, result.message());
-}
-
-TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
-  AssertionResult result = RunPredicateFormatter(kFlaky);
-  EXPECT_FALSE(result);  // Implicit cast to bool.
-  std::string expect =
-      "Value of: dummy-name\nExpected: [DescribeTo]\n"
-      "  The matcher failed on the initial attempt; but passed when rerun to "
-      "generate the explanation.\n"
-      "  Actual: 2" +
-      OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
-  EXPECT_EQ(expect, result.message());
-}
-
-// Tests for ElementsAre().
-
-TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
-  Matcher<const vector<int>&> m = ElementsAre();
-  EXPECT_EQ("is empty", Describe(m));
-}
-
-TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
-  Matcher<vector<int>> m = ElementsAre(Gt(5));
-  EXPECT_EQ("has 1 element that is > 5", Describe(m));
-}
-
-TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
-  Matcher<list<std::string>> m = ElementsAre(StrEq("one"), "two");
-  EXPECT_EQ(
-      "has 2 elements where\n"
-      "element #0 is equal to \"one\",\n"
-      "element #1 is equal to \"two\"",
-      Describe(m));
-}
-
-TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
-  Matcher<vector<int>> m = ElementsAre();
-  EXPECT_EQ("isn't empty", DescribeNegation(m));
-}
-
-TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) {
-  Matcher<const list<int>&> m = ElementsAre(Gt(5));
-  EXPECT_EQ(
-      "doesn't have 1 element, or\n"
-      "element #0 isn't > 5",
-      DescribeNegation(m));
-}
-
-TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
-  Matcher<const list<std::string>&> m = ElementsAre("one", "two");
-  EXPECT_EQ(
-      "doesn't have 2 elements, or\n"
-      "element #0 isn't equal to \"one\", or\n"
-      "element #1 isn't equal to \"two\"",
-      DescribeNegation(m));
-}
-
-TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
-  Matcher<const list<int>&> m = ElementsAre(1, Ne(2));
-
-  list<int> test_list;
-  test_list.push_back(1);
-  test_list.push_back(3);
-  EXPECT_EQ("", Explain(m, test_list));  // No need to explain anything.
-}
-
-TEST(ElementsAreTest, ExplainsNonTrivialMatch) {
-  Matcher<const vector<int>&> m =
-      ElementsAre(GreaterThan(1), 0, GreaterThan(2));
-
-  const int a[] = {10, 0, 100};
-  vector<int> test_vector(std::begin(a), std::end(a));
-  EXPECT_EQ(
-      "whose element #0 matches, which is 9 more than 1,\n"
-      "and whose element #2 matches, which is 98 more than 2",
-      Explain(m, test_vector));
-}
-
-TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
-  Matcher<const list<int>&> m = ElementsAre(1, 3);
-
-  list<int> test_list;
-  // No need to explain when the container is empty.
-  EXPECT_EQ("", Explain(m, test_list));
-
-  test_list.push_back(1);
-  EXPECT_EQ("which has 1 element", Explain(m, test_list));
-}
-
-TEST(ElementsAreTest, CanExplainMismatchRightSize) {
-  Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5));
-
-  vector<int> v;
-  v.push_back(2);
-  v.push_back(1);
-  EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
-
-  v[0] = 1;
-  EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
-            Explain(m, v));
-}
-
-TEST(ElementsAreTest, MatchesOneElementVector) {
-  vector<std::string> test_vector;
-  test_vector.push_back("test string");
-
-  EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
-}
-
-TEST(ElementsAreTest, MatchesOneElementList) {
-  list<std::string> test_list;
-  test_list.push_back("test string");
-
-  EXPECT_THAT(test_list, ElementsAre("test string"));
-}
-
-TEST(ElementsAreTest, MatchesThreeElementVector) {
-  vector<std::string> test_vector;
-  test_vector.push_back("one");
-  test_vector.push_back("two");
-  test_vector.push_back("three");
-
-  EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
-}
-
-TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
-  vector<int> test_vector;
-  test_vector.push_back(4);
-
-  EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
-}
-
-TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
-  vector<int> test_vector;
-  test_vector.push_back(4);
-
-  EXPECT_THAT(test_vector, ElementsAre(_));
-}
-
-TEST(ElementsAreTest, MatchesOneElementValue) {
-  vector<int> test_vector;
-  test_vector.push_back(4);
-
-  EXPECT_THAT(test_vector, ElementsAre(4));
-}
-
-TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
-  vector<int> test_vector;
-  test_vector.push_back(1);
-  test_vector.push_back(2);
-  test_vector.push_back(3);
-
-  EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
-}
-
-TEST(ElementsAreTest, MatchesTenElementVector) {
-  const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
-  vector<int> test_vector(std::begin(a), std::end(a));
-
-  EXPECT_THAT(test_vector,
-              // The element list can contain values and/or matchers
-              // of different types.
-              ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
-}
-
-TEST(ElementsAreTest, DoesNotMatchWrongSize) {
-  vector<std::string> test_vector;
-  test_vector.push_back("test string");
-  test_vector.push_back("test string");
-
-  Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
-  EXPECT_FALSE(m.Matches(test_vector));
-}
-
-TEST(ElementsAreTest, DoesNotMatchWrongValue) {
-  vector<std::string> test_vector;
-  test_vector.push_back("other string");
-
-  Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
-  EXPECT_FALSE(m.Matches(test_vector));
-}
-
-TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
-  vector<std::string> test_vector;
-  test_vector.push_back("one");
-  test_vector.push_back("three");
-  test_vector.push_back("two");
-
-  Matcher<vector<std::string>> m =
-      ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
-  EXPECT_FALSE(m.Matches(test_vector));
-}
-
-TEST(ElementsAreTest, WorksForNestedContainer) {
-  constexpr std::array<const char*, 2> strings = {{"Hi", "world"}};
-
-  vector<list<char>> nested;
-  for (const auto& s : strings) {
-    nested.emplace_back(s, s + strlen(s));
-  }
-
-  EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
-                                  ElementsAre('w', 'o', _, _, 'd')));
-  EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
-                                      ElementsAre('w', 'o', _, _, 'd'))));
-}
-
-TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
-  int a[] = {0, 1, 2};
-  vector<int> v(std::begin(a), std::end(a));
-
-  EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
-  EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
-}
-
-TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
-  int a[] = {0, 1, 2};
-  vector<int> v(std::begin(a), std::end(a));
-
-  EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
-  EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
-}
-
-TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
-  int array[] = {0, 1, 2};
-  EXPECT_THAT(array, ElementsAre(0, 1, _));
-  EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
-  EXPECT_THAT(array, Not(ElementsAre(0, _)));
-}
-
-class NativeArrayPassedAsPointerAndSize {
- public:
-  NativeArrayPassedAsPointerAndSize() {}
-
-  MOCK_METHOD(void, Helper, (int* array, int size));
-
- private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(NativeArrayPassedAsPointerAndSize);
-};
-
-TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
-  int array[] = {0, 1};
-  ::std::tuple<int*, size_t> array_as_tuple(array, 2);
-  EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
-  EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
-
-  NativeArrayPassedAsPointerAndSize helper;
-  EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));
-  helper.Helper(array, 2);
-}
-
-TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
-  const char a2[][3] = {"hi", "lo"};
-  EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
-                              ElementsAre('l', 'o', '\0')));
-  EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
-  EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
-                              ElementsAre('l', 'o', '\0')));
-}
-
-TEST(ElementsAreTest, AcceptsStringLiteral) {
-  std::string array[] = {"hi", "one", "two"};
-  EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
-  EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
-}
-
-// Declared here with the size unknown.  Defined AFTER the following test.
-extern const char kHi[];
-
-TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
-  // The size of kHi is not known in this test, but ElementsAre() should
-  // still accept it.
-
-  std::string array1[] = {"hi"};
-  EXPECT_THAT(array1, ElementsAre(kHi));
-
-  std::string array2[] = {"ho"};
-  EXPECT_THAT(array2, Not(ElementsAre(kHi)));
-}
-
-const char kHi[] = "hi";
-
-TEST(ElementsAreTest, MakesCopyOfArguments) {
-  int x = 1;
-  int y = 2;
-  // This should make a copy of x and y.
-  ::testing::internal::ElementsAreMatcher<std::tuple<int, int>>
-      polymorphic_matcher = ElementsAre(x, y);
-  // Changing x and y now shouldn't affect the meaning of the above matcher.
-  x = y = 0;
-  const int array1[] = {1, 2};
-  EXPECT_THAT(array1, polymorphic_matcher);
-  const int array2[] = {0, 0};
-  EXPECT_THAT(array2, Not(polymorphic_matcher));
-}
-
-// Tests for ElementsAreArray().  Since ElementsAreArray() shares most
-// of the implementation with ElementsAre(), we don't test it as
-// thoroughly here.
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
-  const int a[] = {1, 2, 3};
-
-  vector<int> test_vector(std::begin(a), std::end(a));
-  EXPECT_THAT(test_vector, ElementsAreArray(a));
-
-  test_vector[2] = 0;
-  EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
-  std::array<const char*, 3> a = {{"one", "two", "three"}};
-
-  vector<std::string> test_vector(std::begin(a), std::end(a));
-  EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));
-
-  const char** p = a.data();
-  test_vector[0] = "1";
-  EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
-  const char* a[] = {"one", "two", "three"};
-
-  vector<std::string> test_vector(std::begin(a), std::end(a));
-  EXPECT_THAT(test_vector, ElementsAreArray(a));
-
-  test_vector[0] = "1";
-  EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
-  const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
-                                                StrEq("three")};
-
-  vector<std::string> test_vector;
-  test_vector.push_back("one");
-  test_vector.push_back("two");
-  test_vector.push_back("three");
-  EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
-
-  test_vector.push_back("three");
-  EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
-  const int a[] = {1, 2, 3};
-  vector<int> test_vector(std::begin(a), std::end(a));
-  const vector<int> expected(std::begin(a), std::end(a));
-  EXPECT_THAT(test_vector, ElementsAreArray(expected));
-  test_vector.push_back(4);
-  EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
-}
-
-TEST(ElementsAreArrayTest, TakesInitializerList) {
-  const int a[5] = {1, 2, 3, 4, 5};
-  EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5}));
-  EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4})));
-  EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6})));
-}
-
-TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
-  const std::string a[5] = {"a", "b", "c", "d", "e"};
-  EXPECT_THAT(a, ElementsAreArray({"a", "b", "c", "d", "e"}));
-  EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "e", "d"})));
-  EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "d", "ef"})));
-}
-
-TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
-  const int a[5] = {1, 2, 3, 4, 5};
-  EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
-  EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
-}
-
-TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {
-  const int a[5] = {1, 2, 3, 4, 5};
-  // The compiler cannot infer the type of the initializer list if its
-  // elements have different types.  We must explicitly specify the
-  // unified element type in this case.
-  EXPECT_THAT(
-      a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
-  EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>(
-                     {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
-  const int a[] = {1, 2, 3};
-  const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)};
-  vector<int> test_vector(std::begin(a), std::end(a));
-  const vector<Matcher<int>> expected(std::begin(kMatchers),
-                                      std::end(kMatchers));
-  EXPECT_THAT(test_vector, ElementsAreArray(expected));
-  test_vector.push_back(4);
-  EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
-  const int a[] = {1, 2, 3};
-  const vector<int> test_vector(std::begin(a), std::end(a));
-  const vector<int> expected(std::begin(a), std::end(a));
-  EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
-  // Pointers are iterators, too.
-  EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));
-  // The empty range of NULL pointers should also be okay.
-  int* const null_int = nullptr;
-  EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
-  EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
-}
-
-// Since ElementsAre() and ElementsAreArray() share much of the
-// implementation, we only do a sanity test for native arrays here.
-TEST(ElementsAreArrayTest, WorksWithNativeArray) {
-  ::std::string a[] = {"hi", "ho"};
-  ::std::string b[] = {"hi", "ho"};
-
-  EXPECT_THAT(a, ElementsAreArray(b));
-  EXPECT_THAT(a, ElementsAreArray(b, 2));
-  EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
-}
-
-TEST(ElementsAreArrayTest, SourceLifeSpan) {
-  const int a[] = {1, 2, 3};
-  vector<int> test_vector(std::begin(a), std::end(a));
-  vector<int> expect(std::begin(a), std::end(a));
-  ElementsAreArrayMatcher<int> matcher_maker =
-      ElementsAreArray(expect.begin(), expect.end());
-  EXPECT_THAT(test_vector, matcher_maker);
-  // Changing in place the values that initialized matcher_maker should not
-  // affect matcher_maker anymore. It should have made its own copy of them.
-  for (int& i : expect) {
-    i += 10;
-  }
-  EXPECT_THAT(test_vector, matcher_maker);
-  test_vector.push_back(3);
-  EXPECT_THAT(test_vector, Not(matcher_maker));
-}
-
-// Tests for the MATCHER*() macro family.
-
-// Tests that a simple MATCHER() definition works.
-
-MATCHER(IsEven, "") { return (arg % 2) == 0; }
-
-TEST(MatcherMacroTest, Works) {
-  const Matcher<int> m = IsEven();
-  EXPECT_TRUE(m.Matches(6));
-  EXPECT_FALSE(m.Matches(7));
-
-  EXPECT_EQ("is even", Describe(m));
-  EXPECT_EQ("not (is even)", DescribeNegation(m));
-  EXPECT_EQ("", Explain(m, 6));
-  EXPECT_EQ("", Explain(m, 7));
-}
-
-// This also tests that the description string can reference 'negation'.
-MATCHER(IsEven2, negation ? "is odd" : "is even") {
-  if ((arg % 2) == 0) {
-    // Verifies that we can stream to result_listener, a listener
-    // supplied by the MATCHER macro implicitly.
-    *result_listener << "OK";
-    return true;
-  } else {
-    *result_listener << "% 2 == " << (arg % 2);
-    return false;
-  }
-}
-
-// This also tests that the description string can reference matcher
-// parameters.
-MATCHER_P2(EqSumOf, x, y,
-           std::string(negation ? "doesn't equal" : "equals") + " the sum of " +
-               PrintToString(x) + " and " + PrintToString(y)) {
-  if (arg == (x + y)) {
-    *result_listener << "OK";
-    return true;
-  } else {
-    // Verifies that we can stream to the underlying stream of
-    // result_listener.
-    if (result_listener->stream() != nullptr) {
-      *result_listener->stream() << "diff == " << (x + y - arg);
-    }
-    return false;
-  }
-}
-
-// Tests that the matcher description can reference 'negation' and the
-// matcher parameters.
-TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {
-  const Matcher<int> m1 = IsEven2();
-  EXPECT_EQ("is even", Describe(m1));
-  EXPECT_EQ("is odd", DescribeNegation(m1));
-
-  const Matcher<int> m2 = EqSumOf(5, 9);
-  EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));
-  EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));
-}
-
-// Tests explaining match result in a MATCHER* macro.
-TEST(MatcherMacroTest, CanExplainMatchResult) {
-  const Matcher<int> m1 = IsEven2();
-  EXPECT_EQ("OK", Explain(m1, 4));
-  EXPECT_EQ("% 2 == 1", Explain(m1, 5));
-
-  const Matcher<int> m2 = EqSumOf(1, 2);
-  EXPECT_EQ("OK", Explain(m2, 3));
-  EXPECT_EQ("diff == -1", Explain(m2, 4));
-}
-
-// Tests that the body of MATCHER() can reference the type of the
-// value being matched.
-
-MATCHER(IsEmptyString, "") {
-  StaticAssertTypeEq<::std::string, arg_type>();
-  return arg.empty();
-}
-
-MATCHER(IsEmptyStringByRef, "") {
-  StaticAssertTypeEq<const ::std::string&, arg_type>();
-  return arg.empty();
-}
-
-TEST(MatcherMacroTest, CanReferenceArgType) {
-  const Matcher<::std::string> m1 = IsEmptyString();
-  EXPECT_TRUE(m1.Matches(""));
-
-  const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();
-  EXPECT_TRUE(m2.Matches(""));
-}
-
-// Tests that MATCHER() can be used in a namespace.
-
-namespace matcher_test {
-MATCHER(IsOdd, "") { return (arg % 2) != 0; }
-}  // namespace matcher_test
-
-TEST(MatcherMacroTest, WorksInNamespace) {
-  Matcher<int> m = matcher_test::IsOdd();
-  EXPECT_FALSE(m.Matches(4));
-  EXPECT_TRUE(m.Matches(5));
-}
-
-// Tests that Value() can be used to compose matchers.
-MATCHER(IsPositiveOdd, "") {
-  return Value(arg, matcher_test::IsOdd()) && arg > 0;
-}
-
-TEST(MatcherMacroTest, CanBeComposedUsingValue) {
-  EXPECT_THAT(3, IsPositiveOdd());
-  EXPECT_THAT(4, Not(IsPositiveOdd()));
-  EXPECT_THAT(-1, Not(IsPositiveOdd()));
-}
-
-// Tests that a simple MATCHER_P() definition works.
-
-MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }
-
-TEST(MatcherPMacroTest, Works) {
-  const Matcher<int> m = IsGreaterThan32And(5);
-  EXPECT_TRUE(m.Matches(36));
-  EXPECT_FALSE(m.Matches(5));
-
-  EXPECT_EQ("is greater than 32 and 5", Describe(m));
-  EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
-  EXPECT_EQ("", Explain(m, 36));
-  EXPECT_EQ("", Explain(m, 5));
-}
-
-// Tests that the description is calculated correctly from the matcher name.
-MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }
-
-TEST(MatcherPMacroTest, GeneratesCorrectDescription) {
-  const Matcher<int> m = _is_Greater_Than32and_(5);
-
-  EXPECT_EQ("is greater than 32 and 5", Describe(m));
-  EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
-  EXPECT_EQ("", Explain(m, 36));
-  EXPECT_EQ("", Explain(m, 5));
-}
-
-// Tests that a MATCHER_P matcher can be explicitly instantiated with
-// a reference parameter type.
-
-class UncopyableFoo {
- public:
-  explicit UncopyableFoo(char value) : value_(value) { (void)value_; }
-
-  UncopyableFoo(const UncopyableFoo&) = delete;
-  void operator=(const UncopyableFoo&) = delete;
-
- private:
-  char value_;
-};
-
-MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }
-
-TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {
-  UncopyableFoo foo1('1'), foo2('2');
-  const Matcher<const UncopyableFoo&> m =
-      ReferencesUncopyable<const UncopyableFoo&>(foo1);
-
-  EXPECT_TRUE(m.Matches(foo1));
-  EXPECT_FALSE(m.Matches(foo2));
-
-  // We don't want the address of the parameter printed, as most
-  // likely it will just annoy the user.  If the address is
-  // interesting, the user should consider passing the parameter by
-  // pointer instead.
-  EXPECT_EQ("references uncopyable 1-byte object <31>", Describe(m));
-}
-
-// Tests that the body of MATCHER_Pn() can reference the parameter
-// types.
-
-MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {
-  StaticAssertTypeEq<int, foo_type>();
-  StaticAssertTypeEq<long, bar_type>();  // NOLINT
-  StaticAssertTypeEq<char, baz_type>();
-  return arg == 0;
-}
-
-TEST(MatcherPnMacroTest, CanReferenceParamTypes) {
-  EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));
-}
-
-// Tests that a MATCHER_Pn matcher can be explicitly instantiated with
-// reference parameter types.
-
-MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {
-  return &arg == &variable1 || &arg == &variable2;
-}
-
-TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {
-  UncopyableFoo foo1('1'), foo2('2'), foo3('3');
-  const Matcher<const UncopyableFoo&> const_m =
-      ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
-
-  EXPECT_TRUE(const_m.Matches(foo1));
-  EXPECT_TRUE(const_m.Matches(foo2));
-  EXPECT_FALSE(const_m.Matches(foo3));
-
-  const Matcher<UncopyableFoo&> m =
-      ReferencesAnyOf<UncopyableFoo&, UncopyableFoo&>(foo1, foo2);
-
-  EXPECT_TRUE(m.Matches(foo1));
-  EXPECT_TRUE(m.Matches(foo2));
-  EXPECT_FALSE(m.Matches(foo3));
-}
-
-TEST(MatcherPnMacroTest,
-     GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
-  UncopyableFoo foo1('1'), foo2('2');
-  const Matcher<const UncopyableFoo&> m =
-      ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
-
-  // We don't want the addresses of the parameters printed, as most
-  // likely they will just annoy the user.  If the addresses are
-  // interesting, the user should consider passing the parameters by
-  // pointers instead.
-  EXPECT_EQ("references any of (1-byte object <31>, 1-byte object <32>)",
-            Describe(m));
-}
-
-// Tests that a simple MATCHER_P2() definition works.
-
-MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }
-
-TEST(MatcherPnMacroTest, Works) {
-  const Matcher<const long&> m = IsNotInClosedRange(10, 20);  // NOLINT
-  EXPECT_TRUE(m.Matches(36L));
-  EXPECT_FALSE(m.Matches(15L));
-
-  EXPECT_EQ("is not in closed range (10, 20)", Describe(m));
-  EXPECT_EQ("not (is not in closed range (10, 20))", DescribeNegation(m));
-  EXPECT_EQ("", Explain(m, 36L));
-  EXPECT_EQ("", Explain(m, 15L));
-}
-
-// Tests that MATCHER*() definitions can be overloaded on the number
-// of parameters; also tests MATCHER_Pn() where n >= 3.
-
-MATCHER(EqualsSumOf, "") { return arg == 0; }
-MATCHER_P(EqualsSumOf, a, "") { return arg == a; }
-MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }
-MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }
-MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }
-MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }
-MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {
-  return arg == a + b + c + d + e + f;
-}
-MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {
-  return arg == a + b + c + d + e + f + g;
-}
-MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {
-  return arg == a + b + c + d + e + f + g + h;
-}
-MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {
-  return arg == a + b + c + d + e + f + g + h + i;
-}
-MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {
-  return arg == a + b + c + d + e + f + g + h + i + j;
-}
-
-TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
-  EXPECT_THAT(0, EqualsSumOf());
-  EXPECT_THAT(1, EqualsSumOf(1));
-  EXPECT_THAT(12, EqualsSumOf(10, 2));
-  EXPECT_THAT(123, EqualsSumOf(100, 20, 3));
-  EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));
-  EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
-  EXPECT_THAT("abcdef",
-              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));
-  EXPECT_THAT("abcdefg",
-              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));
-  EXPECT_THAT("abcdefgh", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
-                                      'f', 'g', "h"));
-  EXPECT_THAT("abcdefghi", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
-                                       'f', 'g', "h", 'i'));
-  EXPECT_THAT("abcdefghij",
-              EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', "h",
-                          'i', ::std::string("j")));
-
-  EXPECT_THAT(1, Not(EqualsSumOf()));
-  EXPECT_THAT(-1, Not(EqualsSumOf(1)));
-  EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));
-  EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));
-  EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
-  EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
-  EXPECT_THAT("abcdef ",
-              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));
-  EXPECT_THAT("abcdefg ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
-                                          "e", 'f', 'g')));
-  EXPECT_THAT("abcdefgh ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
-                                           "e", 'f', 'g', "h")));
-  EXPECT_THAT("abcdefghi ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
-                                            "e", 'f', 'g', "h", 'i')));
-  EXPECT_THAT("abcdefghij ",
-              Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
-                              "h", 'i', ::std::string("j"))));
-}
-
-// Tests that a MATCHER_Pn() definition can be instantiated with any
-// compatible parameter types.
-TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {
-  EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));
-  EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));
-
-  EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));
-  EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));
-}
-
-// Tests that the matcher body can promote the parameter types.
-
-MATCHER_P2(EqConcat, prefix, suffix, "") {
-  // The following lines promote the two parameters to desired types.
-  std::string prefix_str(prefix);
-  char suffix_char = static_cast<char>(suffix);
-  return arg == prefix_str + suffix_char;
-}
-
-TEST(MatcherPnMacroTest, SimpleTypePromotion) {
-  Matcher<std::string> no_promo = EqConcat(std::string("foo"), 't');
-  Matcher<const std::string&> promo = EqConcat("foo", static_cast<int>('t'));
-  EXPECT_FALSE(no_promo.Matches("fool"));
-  EXPECT_FALSE(promo.Matches("fool"));
-  EXPECT_TRUE(no_promo.Matches("foot"));
-  EXPECT_TRUE(promo.Matches("foot"));
-}
-
-// Verifies the type of a MATCHER*.
-
-TEST(MatcherPnMacroTest, TypesAreCorrect) {
-  // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.
-  EqualsSumOfMatcher a0 = EqualsSumOf();
-
-  // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.
-  EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
-
-  // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk
-  // variable, and so on.
-  EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');
-  EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');
-  EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');
-  EqualsSumOfMatcherP5<int, int, int, int, char> a5 =
-      EqualsSumOf(1, 2, 3, 4, '5');
-  EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =
-      EqualsSumOf(1, 2, 3, 4, 5, '6');
-  EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =
-      EqualsSumOf(1, 2, 3, 4, 5, 6, '7');
-  EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =
-      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');
-  EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =
-      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
-  EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
-      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
-
-  // Avoid "unused variable" warnings.
-  (void)a0;
-  (void)a1;
-  (void)a2;
-  (void)a3;
-  (void)a4;
-  (void)a5;
-  (void)a6;
-  (void)a7;
-  (void)a8;
-  (void)a9;
-  (void)a10;
-}
-
-// Tests that matcher-typed parameters can be used in Value() inside a
-// MATCHER_Pn definition.
-
-// Succeeds if arg matches exactly 2 of the 3 matchers.
-MATCHER_P3(TwoOf, m1, m2, m3, "") {
-  const int count = static_cast<int>(Value(arg, m1)) +
-                    static_cast<int>(Value(arg, m2)) +
-                    static_cast<int>(Value(arg, m3));
-  return count == 2;
-}
-
-TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
-  EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));
-  EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));
-}
-
-// Tests Contains().
-
-TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
-  list<int> some_list;
-  some_list.push_back(3);
-  some_list.push_back(1);
-  some_list.push_back(2);
-  EXPECT_THAT(some_list, Contains(1));
-  EXPECT_THAT(some_list, Contains(Gt(2.5)));
-  EXPECT_THAT(some_list, Contains(Eq(2.0f)));
-
-  list<std::string> another_list;
-  another_list.push_back("fee");
-  another_list.push_back("fie");
-  another_list.push_back("foe");
-  another_list.push_back("fum");
-  EXPECT_THAT(another_list, Contains(std::string("fee")));
-}
-
-TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
-  list<int> some_list;
-  some_list.push_back(3);
-  some_list.push_back(1);
-  EXPECT_THAT(some_list, Not(Contains(4)));
-}
-
-TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
-  set<int> some_set;
-  some_set.insert(3);
-  some_set.insert(1);
-  some_set.insert(2);
-  EXPECT_THAT(some_set, Contains(Eq(1.0)));
-  EXPECT_THAT(some_set, Contains(Eq(3.0f)));
-  EXPECT_THAT(some_set, Contains(2));
-
-  set<std::string> another_set;
-  another_set.insert("fee");
-  another_set.insert("fie");
-  another_set.insert("foe");
-  another_set.insert("fum");
-  EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
-}
-
-TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
-  set<int> some_set;
-  some_set.insert(3);
-  some_set.insert(1);
-  EXPECT_THAT(some_set, Not(Contains(4)));
-
-  set<std::string> c_string_set;
-  c_string_set.insert("hello");
-  EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye"))));
-}
-
-TEST(ContainsTest, ExplainsMatchResultCorrectly) {
-  const int a[2] = {1, 2};
-  Matcher<const int(&)[2]> m = Contains(2);
-  EXPECT_EQ("whose element #1 matches", Explain(m, a));
-
-  m = Contains(3);
-  EXPECT_EQ("", Explain(m, a));
-
-  m = Contains(GreaterThan(0));
-  EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
-
-  m = Contains(GreaterThan(10));
-  EXPECT_EQ("", Explain(m, a));
-}
-
-TEST(ContainsTest, DescribesItselfCorrectly) {
-  Matcher<vector<int>> m = Contains(1);
-  EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
-
-  Matcher<vector<int>> m2 = Not(m);
-  EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
-}
-
-TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
-  map<std::string, int> my_map;
-  const char* bar = "a string";
-  my_map[bar] = 2;
-  EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
-
-  map<std::string, int> another_map;
-  another_map["fee"] = 1;
-  another_map["fie"] = 2;
-  another_map["foe"] = 3;
-  another_map["fum"] = 4;
-  EXPECT_THAT(another_map,
-              Contains(pair<const std::string, int>(std::string("fee"), 1)));
-  EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
-}
-
-TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
-  map<int, int> some_map;
-  some_map[1] = 11;
-  some_map[2] = 22;
-  EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
-}
-
-TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
-  const char* string_array[] = {"fee", "fie", "foe", "fum"};
-  EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
-}
-
-TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
-  int int_array[] = {1, 2, 3, 4};
-  EXPECT_THAT(int_array, Not(Contains(5)));
-}
-
-TEST(ContainsTest, AcceptsMatcher) {
-  const int a[] = {1, 2, 3};
-  EXPECT_THAT(a, Contains(Gt(2)));
-  EXPECT_THAT(a, Not(Contains(Gt(4))));
-}
-
-TEST(ContainsTest, WorksForNativeArrayAsTuple) {
-  const int a[] = {1, 2};
-  const int* const pointer = a;
-  EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));
-  EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));
-}
-
-TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
-  int a[][3] = {{1, 2, 3}, {4, 5, 6}};
-  EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
-  EXPECT_THAT(a, Contains(Contains(5)));
-  EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
-  EXPECT_THAT(a, Contains(Not(Contains(5))));
-}
-
-TEST(AllOfArrayTest, BasicForms) {
-  // Iterator
-  std::vector<int> v0{};
-  std::vector<int> v1{1};
-  std::vector<int> v2{2, 3};
-  std::vector<int> v3{4, 4, 4};
-  EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end()));
-  EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end()));
-  EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));
-  EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));
-  EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end()));
-  // Pointer +  size
-  int ar[6] = {1, 2, 3, 4, 4, 4};
-  EXPECT_THAT(0, AllOfArray(ar, 0));
-  EXPECT_THAT(1, AllOfArray(ar, 1));
-  EXPECT_THAT(2, Not(AllOfArray(ar, 1)));
-  EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3)));
-  EXPECT_THAT(4, AllOfArray(ar + 3, 3));
-  // Array
-  // int ar0[0];  Not usable
-  int ar1[1] = {1};
-  int ar2[2] = {2, 3};
-  int ar3[3] = {4, 4, 4};
-  // EXPECT_THAT(0, Not(AllOfArray(ar0)));  // Cannot work
-  EXPECT_THAT(1, AllOfArray(ar1));
-  EXPECT_THAT(2, Not(AllOfArray(ar1)));
-  EXPECT_THAT(3, Not(AllOfArray(ar2)));
-  EXPECT_THAT(4, AllOfArray(ar3));
-  // Container
-  EXPECT_THAT(0, AllOfArray(v0));
-  EXPECT_THAT(1, AllOfArray(v1));
-  EXPECT_THAT(2, Not(AllOfArray(v1)));
-  EXPECT_THAT(3, Not(AllOfArray(v2)));
-  EXPECT_THAT(4, AllOfArray(v3));
-  // Initializer
-  EXPECT_THAT(0, AllOfArray<int>({}));  // Requires template arg.
-  EXPECT_THAT(1, AllOfArray({1}));
-  EXPECT_THAT(2, Not(AllOfArray({1})));
-  EXPECT_THAT(3, Not(AllOfArray({2, 3})));
-  EXPECT_THAT(4, AllOfArray({4, 4, 4}));
-}
-
-TEST(AllOfArrayTest, Matchers) {
-  // vector
-  std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};
-  EXPECT_THAT(0, Not(AllOfArray(matchers)));
-  EXPECT_THAT(1, AllOfArray(matchers));
-  EXPECT_THAT(2, Not(AllOfArray(matchers)));
-  // initializer_list
-  EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)})));
-  EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)}));
-}
-
-TEST(AnyOfArrayTest, BasicForms) {
-  // Iterator
-  std::vector<int> v0{};
-  std::vector<int> v1{1};
-  std::vector<int> v2{2, 3};
-  EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end())));
-  EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end()));
-  EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));
-  EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end()));
-  EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));
-  // Pointer +  size
-  int ar[3] = {1, 2, 3};
-  EXPECT_THAT(0, Not(AnyOfArray(ar, 0)));
-  EXPECT_THAT(1, AnyOfArray(ar, 1));
-  EXPECT_THAT(2, Not(AnyOfArray(ar, 1)));
-  EXPECT_THAT(3, AnyOfArray(ar + 1, 2));
-  EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2)));
-  // Array
-  // int ar0[0];  Not usable
-  int ar1[1] = {1};
-  int ar2[2] = {2, 3};
-  // EXPECT_THAT(0, Not(AnyOfArray(ar0)));  // Cannot work
-  EXPECT_THAT(1, AnyOfArray(ar1));
-  EXPECT_THAT(2, Not(AnyOfArray(ar1)));
-  EXPECT_THAT(3, AnyOfArray(ar2));
-  EXPECT_THAT(4, Not(AnyOfArray(ar2)));
-  // Container
-  EXPECT_THAT(0, Not(AnyOfArray(v0)));
-  EXPECT_THAT(1, AnyOfArray(v1));
-  EXPECT_THAT(2, Not(AnyOfArray(v1)));
-  EXPECT_THAT(3, AnyOfArray(v2));
-  EXPECT_THAT(4, Not(AnyOfArray(v2)));
-  // Initializer
-  EXPECT_THAT(0, Not(AnyOfArray<int>({})));  // Requires template arg.
-  EXPECT_THAT(1, AnyOfArray({1}));
-  EXPECT_THAT(2, Not(AnyOfArray({1})));
-  EXPECT_THAT(3, AnyOfArray({2, 3}));
-  EXPECT_THAT(4, Not(AnyOfArray({2, 3})));
-}
-
-TEST(AnyOfArrayTest, Matchers) {
-  // We negate test AllOfArrayTest.Matchers.
-  // vector
-  std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};
-  EXPECT_THAT(0, AnyOfArray(matchers));
-  EXPECT_THAT(1, Not(AnyOfArray(matchers)));
-  EXPECT_THAT(2, AnyOfArray(matchers));
-  // initializer_list
-  EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)}));
-  EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)})));
-}
-
-TEST(AnyOfArrayTest, ExplainsMatchResultCorrectly) {
-  // AnyOfArray and AllOfArry use the same underlying template-template,
-  // thus it is sufficient to test one here.
-  const std::vector<int> v0{};
-  const std::vector<int> v1{1};
-  const std::vector<int> v2{2, 3};
-  const Matcher<int> m0 = AnyOfArray(v0);
-  const Matcher<int> m1 = AnyOfArray(v1);
-  const Matcher<int> m2 = AnyOfArray(v2);
-  EXPECT_EQ("", Explain(m0, 0));
-  EXPECT_EQ("", Explain(m1, 1));
-  EXPECT_EQ("", Explain(m1, 2));
-  EXPECT_EQ("", Explain(m2, 3));
-  EXPECT_EQ("", Explain(m2, 4));
-  EXPECT_EQ("()", Describe(m0));
-  EXPECT_EQ("(is equal to 1)", Describe(m1));
-  EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));
-  EXPECT_EQ("()", DescribeNegation(m0));
-  EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1));
-  EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2));
-  // Explain with matchers
-  const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});
-  const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});
-  // Explains the first positiv match and all prior negative matches...
-  EXPECT_EQ("which is 1 less than 1", Explain(g1, 0));
-  EXPECT_EQ("which is the same as 1", Explain(g1, 1));
-  EXPECT_EQ("which is 1 more than 1", Explain(g1, 2));
-  EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2",
-            Explain(g2, 0));
-  EXPECT_EQ("which is the same as 1, and which is 1 less than 2",
-            Explain(g2, 1));
-  EXPECT_EQ("which is 1 more than 1",  // Only the first
-            Explain(g2, 2));
-}
-
-TEST(AllOfTest, HugeMatcher) {
-  // Verify that using AllOf with many arguments doesn't cause
-  // the compiler to exceed template instantiation depth limit.
-  EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
-                                testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
-}
-
-TEST(AnyOfTest, HugeMatcher) {
-  // Verify that using AnyOf with many arguments doesn't cause
-  // the compiler to exceed template instantiation depth limit.
-  EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
-                                testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
-}
-
-namespace adl_test {
-
-// Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf
-// don't issue unqualified recursive calls.  If they do, the argument dependent
-// name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found
-// as a candidate and the compilation will break due to an ambiguous overload.
-
-// The matcher must be in the same namespace as AllOf/AnyOf to make argument
-// dependent lookup find those.
-MATCHER(M, "") {
-  (void)arg;
-  return true;
-}
-
-template <typename T1, typename T2>
-bool AllOf(const T1& /*t1*/, const T2& /*t2*/) {
-  return true;
-}
-
-TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
-  EXPECT_THAT(42,
-              testing::AllOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
-}
-
-template <typename T1, typename T2>
-bool AnyOf(const T1&, const T2&) {
-  return true;
-}
-
-TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
-  EXPECT_THAT(42,
-              testing::AnyOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
-}
-
-}  // namespace adl_test
-
-TEST(AllOfTest, WorksOnMoveOnlyType) {
-  std::unique_ptr<int> p(new int(3));
-  EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));
-  EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
-}
-
-TEST(AnyOfTest, WorksOnMoveOnlyType) {
-  std::unique_ptr<int> p(new int(3));
-  EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));
-  EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
-}
-
-MATCHER(IsNotNull, "") { return arg != nullptr; }
-
-// Verifies that a matcher defined using MATCHER() can work on
-// move-only types.
-TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
-  std::unique_ptr<int> p(new int(3));
-  EXPECT_THAT(p, IsNotNull());
-  EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
-}
-
-MATCHER_P(UniquePointee, pointee, "") { return *arg == pointee; }
-
-// Verifies that a matcher defined using MATCHER_P*() can work on
-// move-only types.
-TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
-  std::unique_ptr<int> p(new int(3));
-  EXPECT_THAT(p, UniquePointee(3));
-  EXPECT_THAT(p, Not(UniquePointee(2)));
-}
-
-#if GTEST_HAS_EXCEPTIONS
-
-// std::function<void()> is used below for compatibility with older copies of
-// GCC. Normally, a raw lambda is all that is needed.
-
-// Test that examples from documentation compile
-TEST(ThrowsTest, Examples) {
-  EXPECT_THAT(
-      std::function<void()>([]() { throw std::runtime_error("message"); }),
-      Throws<std::runtime_error>());
-
-  EXPECT_THAT(
-      std::function<void()>([]() { throw std::runtime_error("message"); }),
-      ThrowsMessage<std::runtime_error>(HasSubstr("message")));
-}
-
-TEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) {
-  EXPECT_THAT(std::function<void()>([]() { throw std::exception(); }),
-              Throws<std::exception>());
-}
-
-TEST(ThrowsTest, CallableExecutedExactlyOnce) {
-  size_t a = 0;
-
-  EXPECT_THAT(std::function<void()>([&a]() {
-                a++;
-                throw 10;
-              }),
-              Throws<int>());
-  EXPECT_EQ(a, 1u);
-
-  EXPECT_THAT(std::function<void()>([&a]() {
-                a++;
-                throw std::runtime_error("message");
-              }),
-              Throws<std::runtime_error>());
-  EXPECT_EQ(a, 2u);
-
-  EXPECT_THAT(std::function<void()>([&a]() {
-                a++;
-                throw std::runtime_error("message");
-              }),
-              ThrowsMessage<std::runtime_error>(HasSubstr("message")));
-  EXPECT_EQ(a, 3u);
-
-  EXPECT_THAT(std::function<void()>([&a]() {
-                a++;
-                throw std::runtime_error("message");
-              }),
-              Throws<std::runtime_error>(
-                  Property(&std::runtime_error::what, HasSubstr("message"))));
-  EXPECT_EQ(a, 4u);
-}
-
-TEST(ThrowsTest, Describe) {
-  Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
-  std::stringstream ss;
-  matcher.DescribeTo(&ss);
-  auto explanation = ss.str();
-  EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
-}
-
-TEST(ThrowsTest, Success) {
-  Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
-  StringMatchResultListener listener;
-  EXPECT_TRUE(matcher.MatchAndExplain(
-      []() { throw std::runtime_error("error message"); }, &listener));
-  EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
-}
-
-TEST(ThrowsTest, FailWrongType) {
-  Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
-  StringMatchResultListener listener;
-  EXPECT_FALSE(matcher.MatchAndExplain(
-      []() { throw std::logic_error("error message"); }, &listener));
-  EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
-  EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
-}
-
-TEST(ThrowsTest, FailWrongTypeNonStd) {
-  Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
-  StringMatchResultListener listener;
-  EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
-  EXPECT_THAT(listener.str(),
-              HasSubstr("throws an exception of an unknown type"));
-}
-
-TEST(ThrowsTest, FailNoThrow) {
-  Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
-  StringMatchResultListener listener;
-  EXPECT_FALSE(matcher.MatchAndExplain([]() { (void)0; }, &listener));
-  EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
-}
-
-class ThrowsPredicateTest
-    : public TestWithParam<Matcher<std::function<void()>>> {};
-
-TEST_P(ThrowsPredicateTest, Describe) {
-  Matcher<std::function<void()>> matcher = GetParam();
-  std::stringstream ss;
-  matcher.DescribeTo(&ss);
-  auto explanation = ss.str();
-  EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
-  EXPECT_THAT(explanation, HasSubstr("error message"));
-}
-
-TEST_P(ThrowsPredicateTest, Success) {
-  Matcher<std::function<void()>> matcher = GetParam();
-  StringMatchResultListener listener;
-  EXPECT_TRUE(matcher.MatchAndExplain(
-      []() { throw std::runtime_error("error message"); }, &listener));
-  EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
-}
-
-TEST_P(ThrowsPredicateTest, FailWrongType) {
-  Matcher<std::function<void()>> matcher = GetParam();
-  StringMatchResultListener listener;
-  EXPECT_FALSE(matcher.MatchAndExplain(
-      []() { throw std::logic_error("error message"); }, &listener));
-  EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
-  EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
-}
-
-TEST_P(ThrowsPredicateTest, FailWrongTypeNonStd) {
-  Matcher<std::function<void()>> matcher = GetParam();
-  StringMatchResultListener listener;
-  EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
-  EXPECT_THAT(listener.str(),
-              HasSubstr("throws an exception of an unknown type"));
-}
-
-TEST_P(ThrowsPredicateTest, FailWrongMessage) {
-  Matcher<std::function<void()>> matcher = GetParam();
-  StringMatchResultListener listener;
-  EXPECT_FALSE(matcher.MatchAndExplain(
-      []() { throw std::runtime_error("wrong message"); }, &listener));
-  EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
-  EXPECT_THAT(listener.str(), Not(HasSubstr("wrong message")));
-}
-
-TEST_P(ThrowsPredicateTest, FailNoThrow) {
-  Matcher<std::function<void()>> matcher = GetParam();
-  StringMatchResultListener listener;
-  EXPECT_FALSE(matcher.MatchAndExplain([]() {}, &listener));
-  EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
-}
-
-INSTANTIATE_TEST_SUITE_P(
-    AllMessagePredicates, ThrowsPredicateTest,
-    Values(Matcher<std::function<void()>>(
-        ThrowsMessage<std::runtime_error>(HasSubstr("error message")))));
-
-// Tests that Throws<E1>(Matcher<E2>{}) compiles even when E2 != const E1&.
-TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) {
-  {
-    Matcher<std::function<void()>> matcher =
-        ThrowsMessage<std::runtime_error>(HasSubstr("error message"));
-    EXPECT_TRUE(
-        matcher.Matches([]() { throw std::runtime_error("error message"); }));
-    EXPECT_FALSE(
-        matcher.Matches([]() { throw std::runtime_error("wrong message"); }));
-  }
-
-  {
-    Matcher<uint64_t> inner = Eq(10);
-    Matcher<std::function<void()>> matcher = Throws<uint32_t>(inner);
-    EXPECT_TRUE(matcher.Matches([]() { throw(uint32_t) 10; }));
-    EXPECT_FALSE(matcher.Matches([]() { throw(uint32_t) 11; }));
-  }
-}
-
-// Tests that ThrowsMessage("message") is equivalent
-// to ThrowsMessage(Eq<std::string>("message")).
-TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {
-  Matcher<std::function<void()>> matcher =
-      ThrowsMessage<std::runtime_error>("error message");
-  EXPECT_TRUE(
-      matcher.Matches([]() { throw std::runtime_error("error message"); }));
-  EXPECT_FALSE(matcher.Matches(
-      []() { throw std::runtime_error("wrong error message"); }));
-}
-
-#endif  // GTEST_HAS_EXCEPTIONS
-
-}  // namespace
-}  // namespace gmock_matchers_test
-}  // namespace testing
-
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
diff --git a/googlemock/test/gmock-matchers_test.h b/googlemock/test/gmock-matchers_test.h
new file mode 100644 (file)
index 0000000..6c986e9
--- /dev/null
@@ -0,0 +1,192 @@
+// Copyright 2007, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Google Mock - a framework for writing C++ mock classes.
+//
+// This file tests some commonly used argument matchers.
+
+#ifndef GOOGLEMOCK_TEST_GMOCK_MATCHERS_TEST_H_
+#define GOOGLEMOCK_TEST_GMOCK_MATCHERS_TEST_H_
+
+#include <string.h>
+#include <time.h>
+
+#include <array>
+#include <cstdint>
+#include <deque>
+#include <forward_list>
+#include <functional>
+#include <iostream>
+#include <iterator>
+#include <limits>
+#include <list>
+#include <map>
+#include <memory>
+#include <set>
+#include <sstream>
+#include <string>
+#include <type_traits>
+#include <unordered_map>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+#include "gmock/gmock-matchers.h"
+#include "gmock/gmock-more-matchers.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest-spi.h"
+#include "gtest/gtest.h"
+
+namespace testing {
+namespace gmock_matchers_test {
+
+using std::greater;
+using std::less;
+using std::list;
+using std::make_pair;
+using std::map;
+using std::multimap;
+using std::multiset;
+using std::ostream;
+using std::pair;
+using std::set;
+using std::stringstream;
+using std::vector;
+using testing::internal::DummyMatchResultListener;
+using testing::internal::ElementMatcherPair;
+using testing::internal::ElementMatcherPairs;
+using testing::internal::ElementsAreArrayMatcher;
+using testing::internal::ExplainMatchFailureTupleTo;
+using testing::internal::FloatingEqMatcher;
+using testing::internal::FormatMatcherDescription;
+using testing::internal::IsReadableTypeName;
+using testing::internal::MatchMatrix;
+using testing::internal::PredicateFormatterFromMatcher;
+using testing::internal::RE;
+using testing::internal::StreamMatchResultListener;
+using testing::internal::Strings;
+
+// Helper for testing container-valued matchers in mock method context. It is
+// important to test matchers in this context, since it requires additional type
+// deduction beyond what EXPECT_THAT does, thus making it more restrictive.
+struct ContainerHelper {
+  MOCK_METHOD1(Call, void(std::vector<std::unique_ptr<int>>));
+};
+
+// For testing ExplainMatchResultTo().
+template <typename T>
+struct GtestGreaterThanMatcher {
+  using is_gtest_matcher = void;
+
+  void DescribeTo(ostream* os) const { *os << "is > " << rhs; }
+  void DescribeNegationTo(ostream* os) const { *os << "is <= " << rhs; }
+
+  bool MatchAndExplain(T lhs, MatchResultListener* listener) const {
+    if (lhs > rhs) {
+      *listener << "which is " << (lhs - rhs) << " more than " << rhs;
+    } else if (lhs == rhs) {
+      *listener << "which is the same as " << rhs;
+    } else {
+      *listener << "which is " << (rhs - lhs) << " less than " << rhs;
+    }
+
+    return lhs > rhs;
+  }
+
+  T rhs;
+};
+
+template <typename T>
+GtestGreaterThanMatcher<typename std::decay<T>::type> GtestGreaterThan(
+    T&& rhs) {
+  return {rhs};
+}
+
+// As the matcher above, but using the base class with virtual functions.
+template <typename T>
+class GreaterThanMatcher : public MatcherInterface<T> {
+ public:
+  explicit GreaterThanMatcher(T rhs) : impl_{rhs} {}
+
+  void DescribeTo(ostream* os) const override { impl_.DescribeTo(os); }
+  void DescribeNegationTo(ostream* os) const override {
+    impl_.DescribeNegationTo(os);
+  }
+
+  bool MatchAndExplain(T lhs, MatchResultListener* listener) const override {
+    return impl_.MatchAndExplain(lhs, listener);
+  }
+
+ private:
+  const GtestGreaterThanMatcher<T> impl_;
+};
+
+// Names and instantiates a new instance of GTestMatcherTestP.
+#define INSTANTIATE_GTEST_MATCHER_TEST_P(TestSuite)                         \
+  using TestSuite##P = GTestMatcherTestP;                                   \
+  INSTANTIATE_TEST_SUITE_P(MatcherInterface, TestSuite##P, Values(false));  \
+  INSTANTIATE_TEST_SUITE_P(GtestMatcher, TestSuite##P, Values(true))
+
+class GTestMatcherTestP : public testing::TestWithParam<bool> {
+ public:
+  template <typename T>
+  Matcher<T> GreaterThan(T n) {
+    if (use_gtest_matcher_) {
+      return GtestGreaterThan(n);
+    } else {
+      return MakeMatcher(new GreaterThanMatcher<T>(n));
+    }
+  }
+  const bool use_gtest_matcher_ = GetParam();
+};
+
+// Returns the description of the given matcher.
+template <typename T>
+std::string Describe(const Matcher<T>& m) {
+  return DescribeMatcher<T>(m);
+}
+
+// Returns the description of the negation of the given matcher.
+template <typename T>
+std::string DescribeNegation(const Matcher<T>& m) {
+  return DescribeMatcher<T>(m, true);
+}
+
+// Returns the reason why x matches, or doesn't match, m.
+template <typename MatcherType, typename Value>
+std::string Explain(const MatcherType& m, const Value& x) {
+  StringMatchResultListener listener;
+  ExplainMatchResult(m, x, &listener);
+  return listener.str();
+}
+
+}  // namespace gmock_matchers_test
+}  // namespace testing
+
+#endif  // GOOGLEMOCK_TEST_GMOCK_MATCHERS_TEST_H_
index 53bb029f45c97b8e75ebbc3a5fd47bd03989248e..b9b66bf9000068bcc4ac803fba9c8d7aff5ddacb 100644 (file)
@@ -145,7 +145,7 @@ class Foo {
 
   std::string Binary(const std::string& str, char c) const { return str + c; }
 
-  int Ternary(int x, bool y, char z) { return value_ + x + y*z; }
+  int Ternary(int x, bool y, char z) { return value_ + x + y * z; }
 
   int SumOf4(int a, int b, int c, int d) const {
     return a + b + c + d + value_;
@@ -291,8 +291,7 @@ TEST(InvokeTest, FunctionWithUnusedParameters) {
       std::make_tuple(10, 2, 5.6, std::string("hi"));
   EXPECT_EQ(12, a1.Perform(dummy));
 
-  Action<int(int, int, bool, int*)> a2 =
-      Invoke(SumOfFirst2);
+  Action<int(int, int, bool, int*)> a2 = Invoke(SumOfFirst2);
   EXPECT_EQ(
       23, a2.Perform(std::make_tuple(20, 3, true, static_cast<int*>(nullptr))));
 }
@@ -303,8 +302,7 @@ TEST(InvokeTest, MethodWithUnusedParameters) {
   Action<int(std::string, bool, int, int)> a1 = Invoke(&foo, &Foo::SumOfLast2);
   EXPECT_EQ(12, a1.Perform(std::make_tuple(CharPtr("hi"), true, 10, 2)));
 
-  Action<int(char, double, int, int)> a2 =
-      Invoke(&foo, &Foo::SumOfLast2);
+  Action<int(char, double, int, int)> a2 = Invoke(&foo, &Foo::SumOfLast2);
   EXPECT_EQ(23, a2.Perform(std::make_tuple('a', 2.5, 20, 3)));
 }
 
@@ -362,7 +360,8 @@ TEST(InvokeMethodTest, MethodThatTakes4Arguments) {
 // Tests using Invoke() with a 5-argument method.
 TEST(InvokeMethodTest, MethodThatTakes5Arguments) {
   Foo foo;
-  Action<int(int, int, int, int, int)> a = Invoke(&foo, &Foo::SumOf5);  // NOLINT
+  Action<int(int, int, int, int, int)> a =
+      Invoke(&foo, &Foo::SumOf5);  // NOLINT
   EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5)));
 }
 
@@ -462,6 +461,12 @@ TEST(ReturnArgActionTest, WorksForMultiArgStringArg2) {
   EXPECT_EQ("seven", a.Perform(std::make_tuple(5, 6, std::string("seven"), 8)));
 }
 
+TEST(ReturnArgActionTest, WorksForNonConstRefArg0) {
+  const Action<std::string&(std::string&)> a = ReturnArg<0>();
+  std::string s = "12345";
+  EXPECT_EQ(&s, &a.Perform(std::forward_as_tuple(s)));
+}
+
 TEST(SaveArgActionTest, WorksForSameType) {
   int result = 0;
   const Action<void(int n)> a1 = SaveArg<0>(&result);
@@ -517,15 +522,12 @@ TEST(SetArgRefereeActionTest, WorksWithExtraArguments) {
 // the bool provided to the constructor to true when destroyed.
 class DeletionTester {
  public:
-  explicit DeletionTester(bool* is_deleted)
-    : is_deleted_(is_deleted) {
+  explicit DeletionTester(bool* is_deleted) : is_deleted_(is_deleted) {
     // Make sure the bit is set to false.
     *is_deleted_ = false;
   }
 
-  ~DeletionTester() {
-    *is_deleted_ = true;
-  }
+  ~DeletionTester() { *is_deleted_ = true; }
 
  private:
   bool* is_deleted_;
@@ -534,7 +536,7 @@ class DeletionTester {
 TEST(DeleteArgActionTest, OneArg) {
   bool is_deleted = false;
   DeletionTester* t = new DeletionTester(&is_deleted);
-  const Action<void(DeletionTester*)> a1 = DeleteArg<0>();      // NOLINT
+  const Action<void(DeletionTester*)> a1 = DeleteArg<0>();  // NOLINT
   EXPECT_FALSE(is_deleted);
   a1.Perform(std::make_tuple(t));
   EXPECT_TRUE(is_deleted);
@@ -543,8 +545,9 @@ TEST(DeleteArgActionTest, OneArg) {
 TEST(DeleteArgActionTest, TenArgs) {
   bool is_deleted = false;
   DeletionTester* t = new DeletionTester(&is_deleted);
-  const Action<void(bool, int, int, const char*, bool,
-                    int, int, int, int, DeletionTester*)> a1 = DeleteArg<9>();
+  const Action<void(bool, int, int, const char*, bool, int, int, int, int,
+                    DeletionTester*)>
+      a1 = DeleteArg<9>();
   EXPECT_FALSE(is_deleted);
   a1.Perform(std::make_tuple(true, 5, 6, CharPtr("hi"), false, 7, 8, 9, 10, t));
   EXPECT_TRUE(is_deleted);
@@ -602,7 +605,7 @@ TEST(ThrowActionTest, Times0) {
 // pointed to by the N-th (0-based) argument to values in range [first, last).
 TEST(SetArrayArgumentTest, SetsTheNthArray) {
   using MyFunction = void(bool, int*, char*);
-  int numbers[] = { 1, 2, 3 };
+  int numbers[] = {1, 2, 3};
   Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers + 3);
 
   int n[4] = {};
@@ -638,7 +641,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArray) {
 // Tests SetArrayArgument<N>(first, last) where first == last.
 TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) {
   using MyFunction = void(bool, int*);
-  int numbers[] = { 1, 2, 3 };
+  int numbers[] = {1, 2, 3};
   Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers);
 
   int n[4] = {};
@@ -654,10 +657,10 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) {
 // (but not equal) to the argument type.
 TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) {
   using MyFunction = void(bool, int*);
-  char chars[] = { 97, 98, 99 };
+  char chars[] = {97, 98, 99};
   Action<MyFunction> a = SetArrayArgument<1>(chars, chars + 3);
 
-  int codes[4] = { 111, 222, 333, 444 };
+  int codes[4] = {111, 222, 333, 444};
   int* pcodes = codes;
   a.Perform(std::make_tuple(true, pcodes));
   EXPECT_EQ(97, codes[0]);
index 25558ebffe766bb09ab6d06aabc698947932f69c..08254e1acdd077a31034dd40b7d36efde855d960 100644 (file)
@@ -31,6 +31,7 @@
 
 #include <string>
 #include <utility>
+
 #include "gmock/gmock.h"
 #include "gtest/gtest-spi.h"
 #include "gtest/gtest.h"
@@ -44,13 +45,13 @@ class Mock {
   MOCK_METHOD0(DoThis, void());
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(Mock);
+  Mock(const Mock&) = delete;
+  Mock& operator=(const Mock&) = delete;
 };
 
 namespace testing {
 namespace gmock_nice_strict_test {
 
-using testing::GMOCK_FLAG(verbose);
 using testing::HasSubstr;
 using testing::NaggyMock;
 using testing::NiceMock;
@@ -93,7 +94,8 @@ class MockFoo : public Foo {
   MOCK_METHOD0(ReturnNonDefaultConstructible, NotDefaultConstructible());
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
+  MockFoo(const MockFoo&) = delete;
+  MockFoo& operator=(const MockFoo&) = delete;
 };
 
 class MockBar {
@@ -103,7 +105,8 @@ class MockBar {
   MockBar(char a1, char a2, std::string a3, std::string a4, int a5, int a6,
           const std::string& a7, const std::string& a8, bool a9, bool a10) {
     str_ = std::string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) +
-        static_cast<char>(a6) + a7 + a8 + (a9 ? 'T' : 'F') + (a10 ? 'T' : 'F');
+           static_cast<char>(a6) + a7 + a8 + (a9 ? 'T' : 'F') +
+           (a10 ? 'T' : 'F');
   }
 
   virtual ~MockBar() {}
@@ -116,10 +119,10 @@ class MockBar {
  private:
   std::string str_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockBar);
+  MockBar(const MockBar&) = delete;
+  MockBar& operator=(const MockBar&) = delete;
 };
 
-
 class MockBaz {
  public:
   class MoveOnly {
@@ -140,8 +143,8 @@ class MockBaz {
 
 // Tests that a raw mock generates warnings for uninteresting calls.
 TEST(RawMockTest, WarningForUninterestingCall) {
-  const std::string saved_flag = GMOCK_FLAG(verbose);
-  GMOCK_FLAG(verbose) = "warning";
+  const std::string saved_flag = GMOCK_FLAG_GET(verbose);
+  GMOCK_FLAG_SET(verbose, "warning");
 
   MockFoo raw_foo;
 
@@ -151,26 +154,25 @@ TEST(RawMockTest, WarningForUninterestingCall) {
   EXPECT_THAT(GetCapturedStdout(),
               HasSubstr("Uninteresting mock function call"));
 
-  GMOCK_FLAG(verbose) = saved_flag;
+  GMOCK_FLAG_SET(verbose, saved_flag);
 }
 
 // Tests that a raw mock generates warnings for uninteresting calls
 // that delete the mock object.
 TEST(RawMockTest, WarningForUninterestingCallAfterDeath) {
-  const std::string saved_flag = GMOCK_FLAG(verbose);
-  GMOCK_FLAG(verbose) = "warning";
+  const std::string saved_flag = GMOCK_FLAG_GET(verbose);
+  GMOCK_FLAG_SET(verbose, "warning");
 
   MockFoo* const raw_foo = new MockFoo;
 
-  ON_CALL(*raw_foo, DoThis())
-      .WillByDefault(Invoke(raw_foo, &MockFoo::Delete));
+  ON_CALL(*raw_foo, DoThis()).WillByDefault(Invoke(raw_foo, &MockFoo::Delete));
 
   CaptureStdout();
   raw_foo->DoThis();
   EXPECT_THAT(GetCapturedStdout(),
               HasSubstr("Uninteresting mock function call"));
 
-  GMOCK_FLAG(verbose) = saved_flag;
+  GMOCK_FLAG_SET(verbose, saved_flag);
 }
 
 // Tests that a raw mock generates informational logs for
@@ -178,14 +180,14 @@ TEST(RawMockTest, WarningForUninterestingCallAfterDeath) {
 TEST(RawMockTest, InfoForUninterestingCall) {
   MockFoo raw_foo;
 
-  const std::string saved_flag = GMOCK_FLAG(verbose);
-  GMOCK_FLAG(verbose) = "info";
+  const std::string saved_flag = GMOCK_FLAG_GET(verbose);
+  GMOCK_FLAG_SET(verbose, "info");
   CaptureStdout();
   raw_foo.DoThis();
   EXPECT_THAT(GetCapturedStdout(),
               HasSubstr("Uninteresting mock function call"));
 
-  GMOCK_FLAG(verbose) = saved_flag;
+  GMOCK_FLAG_SET(verbose, saved_flag);
 }
 
 TEST(RawMockTest, IsNaggy_IsNice_IsStrict) {
@@ -223,14 +225,14 @@ TEST(NiceMockTest, NoWarningForUninterestingCallAfterDeath) {
 TEST(NiceMockTest, InfoForUninterestingCall) {
   NiceMock<MockFoo> nice_foo;
 
-  const std::string saved_flag = GMOCK_FLAG(verbose);
-  GMOCK_FLAG(verbose) = "info";
+  const std::string saved_flag = GMOCK_FLAG_GET(verbose);
+  GMOCK_FLAG_SET(verbose, "info");
   CaptureStdout();
   nice_foo.DoThis();
   EXPECT_THAT(GetCapturedStdout(),
               HasSubstr("Uninteresting mock function call"));
 
-  GMOCK_FLAG(verbose) = saved_flag;
+  GMOCK_FLAG_SET(verbose, saved_flag);
 }
 
 #endif  // GTEST_HAS_STREAM_REDIRECTION
@@ -281,8 +283,8 @@ TEST(NiceMockTest, NonDefaultConstructor) {
 // Tests that NiceMock works with a mock class that has a 10-ary
 // non-default constructor.
 TEST(NiceMockTest, NonDefaultConstructor10) {
-  NiceMock<MockBar> nice_bar('a', 'b', "c", "d", 'e', 'f',
-                             "g", "h", true, false);
+  NiceMock<MockBar> nice_bar('a', 'b', "c", "d", 'e', 'f', "g", "h", true,
+                             false);
   EXPECT_EQ("abcdefghTF", nice_bar.str());
 
   nice_bar.This();
@@ -326,8 +328,8 @@ TEST(NiceMockTest, IsNaggy_IsNice_IsStrict) {
 
 // Tests that a naggy mock generates warnings for uninteresting calls.
 TEST(NaggyMockTest, WarningForUninterestingCall) {
-  const std::string saved_flag = GMOCK_FLAG(verbose);
-  GMOCK_FLAG(verbose) = "warning";
+  const std::string saved_flag = GMOCK_FLAG_GET(verbose);
+  GMOCK_FLAG_SET(verbose, "warning");
 
   NaggyMock<MockFoo> naggy_foo;
 
@@ -337,14 +339,14 @@ TEST(NaggyMockTest, WarningForUninterestingCall) {
   EXPECT_THAT(GetCapturedStdout(),
               HasSubstr("Uninteresting mock function call"));
 
-  GMOCK_FLAG(verbose) = saved_flag;
+  GMOCK_FLAG_SET(verbose, saved_flag);
 }
 
 // Tests that a naggy mock generates a warning for an uninteresting call
 // that deletes the mock object.
 TEST(NaggyMockTest, WarningForUninterestingCallAfterDeath) {
-  const std::string saved_flag = GMOCK_FLAG(verbose);
-  GMOCK_FLAG(verbose) = "warning";
+  const std::string saved_flag = GMOCK_FLAG_GET(verbose);
+  GMOCK_FLAG_SET(verbose, "warning");
 
   NaggyMock<MockFoo>* const naggy_foo = new NaggyMock<MockFoo>;
 
@@ -356,7 +358,7 @@ TEST(NaggyMockTest, WarningForUninterestingCallAfterDeath) {
   EXPECT_THAT(GetCapturedStdout(),
               HasSubstr("Uninteresting mock function call"));
 
-  GMOCK_FLAG(verbose) = saved_flag;
+  GMOCK_FLAG_SET(verbose, saved_flag);
 }
 
 #endif  // GTEST_HAS_STREAM_REDIRECTION
@@ -391,8 +393,8 @@ TEST(NaggyMockTest, NonDefaultConstructor) {
 // Tests that NaggyMock works with a mock class that has a 10-ary
 // non-default constructor.
 TEST(NaggyMockTest, NonDefaultConstructor10) {
-  NaggyMock<MockBar> naggy_bar('0', '1', "2", "3", '4', '5',
-                               "6", "7", true, false);
+  NaggyMock<MockBar> naggy_bar('0', '1', "2", "3", '4', '5', "6", "7", true,
+                               false);
   EXPECT_EQ("01234567TF", naggy_bar.str());
 
   naggy_bar.This();
@@ -419,8 +421,8 @@ TEST(NaggyMockTest, AcceptsClassNamedMock) {
 }
 
 TEST(NaggyMockTest, IsNaggyInDestructor) {
-  const std::string saved_flag = GMOCK_FLAG(verbose);
-  GMOCK_FLAG(verbose) = "warning";
+  const std::string saved_flag = GMOCK_FLAG_GET(verbose);
+  GMOCK_FLAG_SET(verbose, "warning");
   CaptureStdout();
 
   {
@@ -431,7 +433,7 @@ TEST(NaggyMockTest, IsNaggyInDestructor) {
   EXPECT_THAT(GetCapturedStdout(),
               HasSubstr("Uninteresting mock function call"));
 
-  GMOCK_FLAG(verbose) = saved_flag;
+  GMOCK_FLAG_SET(verbose, saved_flag);
 }
 
 TEST(NaggyMockTest, IsNaggy_IsNice_IsStrict) {
@@ -491,8 +493,8 @@ TEST(StrictMockTest, NonDefaultConstructor) {
 // Tests that StrictMock works with a mock class that has a 10-ary
 // non-default constructor.
 TEST(StrictMockTest, NonDefaultConstructor10) {
-  StrictMock<MockBar> strict_bar('a', 'b', "c", "d", 'e', 'f',
-                                 "g", "h", true, false);
+  StrictMock<MockBar> strict_bar('a', 'b', "c", "d", 'e', 'f', "g", "h", true,
+                                 false);
   EXPECT_EQ("abcdefghTF", strict_bar.str());
 
   EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true),
index a2c2be248864b2bc23711a0ef34666c9fa7a4649..c31af821559b53d54f297a31adea91af409f63df 100644 (file)
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file tests the internal cross-platform support utilities.
 
 #include "gmock/internal/gmock-port.h"
+
 #include "gtest/gtest.h"
 
 // NOTE: if this file is left without tests for some reason, put a dummy
index 6f66cf156a90f9ec413010ac0c8581776dbd362d..53c80f4e3d2f7606d1997cb6613e3ec5dc1cc285 100644 (file)
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file tests the internal preprocessor macro library.
-#include "gmock/internal/gmock-pp.h"
-
 #include <string>
 
 #include "gmock/gmock.h"
+#include "gmock/internal/gmock-pp.h"
 
 namespace testing {
 namespace {
index fa97411332c67af530547321fd9c7409231c0f79..122d5b94e485b081eb177b6cf3320df2a2fed70b 100644 (file)
@@ -27,7 +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.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file tests the spec builder syntax.
 #include <ostream>  // NOLINT
 #include <sstream>
 #include <string>
+#include <type_traits>
 
 #include "gmock/gmock.h"
 #include "gmock/internal/gmock-port.h"
-#include "gtest/gtest.h"
 #include "gtest/gtest-spi.h"
+#include "gtest/gtest.h"
 #include "gtest/internal/gtest-port.h"
 
 namespace testing {
-namespace internal {
-
-// Helper class for testing the Expectation class template.
-class ExpectationTester {
- public:
-  // Sets the call count of the given expectation to the given number.
-  void SetCallCount(int n, ExpectationBase* exp) {
-    exp->call_count_ = n;
-  }
-};
-
-}  // namespace internal
-}  // namespace testing
-
 namespace {
 
-using testing::_;
-using testing::AnyNumber;
-using testing::AtLeast;
-using testing::AtMost;
-using testing::Between;
-using testing::Cardinality;
-using testing::CardinalityInterface;
-using testing::Const;
-using testing::ContainsRegex;
-using testing::DoAll;
-using testing::DoDefault;
-using testing::Eq;
-using testing::Expectation;
-using testing::ExpectationSet;
-using testing::GMOCK_FLAG(verbose);
-using testing::Gt;
-using testing::IgnoreResult;
-using testing::InSequence;
-using testing::Invoke;
-using testing::InvokeWithoutArgs;
-using testing::IsNotSubstring;
-using testing::IsSubstring;
-using testing::Lt;
-using testing::Message;
-using testing::Mock;
-using testing::NaggyMock;
-using testing::Ne;
-using testing::Return;
-using testing::SaveArg;
-using testing::Sequence;
-using testing::SetArgPointee;
-using testing::internal::ExpectationTester;
-using testing::internal::FormatFileLocation;
-using testing::internal::kAllow;
-using testing::internal::kErrorVerbosity;
-using testing::internal::kFail;
-using testing::internal::kInfoVerbosity;
-using testing::internal::kWarn;
-using testing::internal::kWarningVerbosity;
+using ::testing::internal::FormatFileLocation;
+using ::testing::internal::kAllow;
+using ::testing::internal::kErrorVerbosity;
+using ::testing::internal::kFail;
+using ::testing::internal::kInfoVerbosity;
+using ::testing::internal::kWarn;
+using ::testing::internal::kWarningVerbosity;
 
 #if GTEST_HAS_STREAM_REDIRECTION
-using testing::HasSubstr;
-using testing::internal::CaptureStdout;
-using testing::internal::GetCapturedStdout;
+using ::testing::internal::CaptureStdout;
+using ::testing::internal::GetCapturedStdout;
 #endif
 
 class Incomplete;
@@ -126,8 +79,7 @@ TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {
   // use the mock, as long as Google Mock knows how to print the
   // argument.
   MockIncomplete incomplete;
-  EXPECT_CALL(incomplete, ByRefFunc(_))
-      .Times(AnyNumber());
+  EXPECT_CALL(incomplete, ByRefFunc(_)).Times(AnyNumber());
 }
 
 // The definition of the printer for the argument type doesn't have to
@@ -155,7 +107,8 @@ class MockA {
   MOCK_METHOD2(ReturnInt, int(int x, int y));
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA);
+  MockA(const MockA&) = delete;
+  MockA& operator=(const MockA&) = delete;
 };
 
 class MockB {
@@ -163,10 +116,11 @@ class MockB {
   MockB() {}
 
   MOCK_CONST_METHOD0(DoB, int());  // NOLINT
-  MOCK_METHOD1(DoB, int(int n));  // NOLINT
+  MOCK_METHOD1(DoB, int(int n));   // NOLINT
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
+  MockB(const MockB&) = delete;
+  MockB& operator=(const MockB&) = delete;
 };
 
 class ReferenceHoldingMock {
@@ -176,7 +130,8 @@ class ReferenceHoldingMock {
   MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*));
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock);
+  ReferenceHoldingMock(const ReferenceHoldingMock&) = delete;
+  ReferenceHoldingMock& operator=(const ReferenceHoldingMock&) = delete;
 };
 
 // Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
@@ -198,7 +153,8 @@ class MockCC : public CC {
   MOCK_METHOD0(Method, int());
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC);
+  MockCC(const MockCC&) = delete;
+  MockCC& operator=(const MockCC&) = delete;
 };
 
 // Tests that a method with expanded name compiles.
@@ -254,41 +210,42 @@ TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
 TEST(OnCallSyntaxTest, WithIsOptional) {
   MockA a;
 
-  ON_CALL(a, DoA(5))
-      .WillByDefault(Return());
-  ON_CALL(a, DoA(_))
-      .With(_)
-      .WillByDefault(Return());
+  ON_CALL(a, DoA(5)).WillByDefault(Return());
+  ON_CALL(a, DoA(_)).With(_).WillByDefault(Return());
 }
 
 TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
   MockA a;
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    ON_CALL(a, ReturnResult(_))
-        .With(_)
-        .With(_)
-        .WillByDefault(Return(Result()));
-  }, ".With() cannot appear more than once in an ON_CALL()");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        ON_CALL(a, ReturnResult(_))
+            .With(_)
+            .With(_)
+            .WillByDefault(Return(Result()));
+      },
+      ".With() cannot appear more than once in an ON_CALL()");
 }
 
 TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
   MockA a;
 
-  EXPECT_DEATH_IF_SUPPORTED({
-    ON_CALL(a, DoA(5));
-    a.DoA(5);
-  }, "");
+  EXPECT_DEATH_IF_SUPPORTED(
+      {
+        ON_CALL(a, DoA(5));
+        a.DoA(5);
+      },
+      "");
 }
 
 TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
   MockA a;
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    ON_CALL(a, DoA(5))
-        .WillByDefault(Return())
-        .WillByDefault(Return());
-  }, ".WillByDefault() must appear exactly once in an ON_CALL()");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        ON_CALL(a, DoA(5)).WillByDefault(Return()).WillByDefault(Return());
+      },
+      ".WillByDefault() must appear exactly once in an ON_CALL()");
 }
 
 // Tests that EXPECT_CALL evaluates its arguments exactly once as
@@ -316,21 +273,18 @@ TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
 TEST(ExpectCallSyntaxTest, WithIsOptional) {
   MockA a;
 
-  EXPECT_CALL(a, DoA(5))
-      .Times(0);
-  EXPECT_CALL(a, DoA(6))
-      .With(_)
-      .Times(0);
+  EXPECT_CALL(a, DoA(5)).Times(0);
+  EXPECT_CALL(a, DoA(6)).With(_).Times(0);
 }
 
 TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
   MockA a;
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_CALL(a, DoA(6))
-        .With(_)
-        .With(_);
-  }, ".With() cannot appear more than once in an EXPECT_CALL()");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_CALL(a, DoA(6)).With(_).With(_);
+      },
+      ".With() cannot appear more than once in an EXPECT_CALL()");
 
   a.DoA(6);
 }
@@ -338,19 +292,19 @@ TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
 TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
   MockA a;
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_CALL(a, DoA(1))
-        .Times(1)
-        .With(_);
-  }, ".With() must be the first clause in an EXPECT_CALL()");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_CALL(a, DoA(1)).Times(1).With(_);
+      },
+      ".With() must be the first clause in an EXPECT_CALL()");
 
   a.DoA(1);
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_CALL(a, DoA(2))
-        .WillOnce(Return())
-        .With(_);
-  }, ".With() must be the first clause in an EXPECT_CALL()");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_CALL(a, DoA(2)).WillOnce(Return()).With(_);
+      },
+      ".With() must be the first clause in an EXPECT_CALL()");
 
   a.DoA(2);
 }
@@ -358,12 +312,9 @@ TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
 TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
   MockA a;
 
-  EXPECT_CALL(a, DoA(1))
-      .WillOnce(Return());
+  EXPECT_CALL(a, DoA(1)).WillOnce(Return());
 
-  EXPECT_CALL(a, DoA(2))
-      .WillOnce(Return())
-      .WillRepeatedly(Return());
+  EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return());
 
   a.DoA(1);
   a.DoA(2);
@@ -373,11 +324,11 @@ TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
 TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
   MockA a;
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_CALL(a, DoA(1))
-        .Times(1)
-        .Times(2);
-  }, ".Times() cannot appear more than once in an EXPECT_CALL()");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_CALL(a, DoA(1)).Times(1).Times(2);
+      },
+      ".Times() cannot appear more than once in an EXPECT_CALL()");
 
   a.DoA(1);
   a.DoA(1);
@@ -387,11 +338,11 @@ TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
   MockA a;
   Sequence s;
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_CALL(a, DoA(1))
-        .InSequence(s)
-        .Times(1);
-  }, ".Times() cannot appear after ");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_CALL(a, DoA(1)).InSequence(s).Times(1);
+      },
+      ".Times() may only appear *before* ");
 
   a.DoA(1);
 }
@@ -401,8 +352,7 @@ TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
   Sequence s;
 
   EXPECT_CALL(a, DoA(1));
-  EXPECT_CALL(a, DoA(2))
-      .InSequence(s);
+  EXPECT_CALL(a, DoA(2)).InSequence(s);
 
   a.DoA(1);
   a.DoA(2);
@@ -412,9 +362,7 @@ TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
   MockA a;
   Sequence s1, s2;
 
-  EXPECT_CALL(a, DoA(1))
-      .InSequence(s1, s2)
-      .InSequence(s1);
+  EXPECT_CALL(a, DoA(1)).InSequence(s1, s2).InSequence(s1);
 
   a.DoA(1);
 }
@@ -423,13 +371,12 @@ TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
   MockA a;
   Sequence s;
 
-  Expectation e = EXPECT_CALL(a, DoA(1))
-      .Times(AnyNumber());
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_CALL(a, DoA(2))
-        .After(e)
-        .InSequence(s);
-  }, ".InSequence() cannot appear after ");
+  Expectation e = EXPECT_CALL(a, DoA(1)).Times(AnyNumber());
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_CALL(a, DoA(2)).After(e).InSequence(s);
+      },
+      ".InSequence() cannot appear after ");
 
   a.DoA(2);
 }
@@ -438,11 +385,11 @@ TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
   MockA a;
   Sequence s;
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_CALL(a, DoA(1))
-        .WillOnce(Return())
-        .InSequence(s);
-  }, ".InSequence() cannot appear after ");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_CALL(a, DoA(1)).WillOnce(Return()).InSequence(s);
+      },
+      ".InSequence() cannot appear after ");
 
   a.DoA(1);
 }
@@ -451,11 +398,9 @@ TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
   MockA a;
 
   Expectation e = EXPECT_CALL(a, DoA(1));
-  EXPECT_NONFATAL_FAILURE({
-    EXPECT_CALL(a, DoA(2))
-        .WillOnce(Return())
-        .After(e);
-  }, ".After() cannot appear after ");
+  EXPECT_NONFATAL_FAILURE(
+      { EXPECT_CALL(a, DoA(2)).WillOnce(Return()).After(e); },
+      ".After() cannot appear after ");
 
   a.DoA(1);
   a.DoA(2);
@@ -465,8 +410,7 @@ TEST(ExpectCallSyntaxTest, WillIsOptional) {
   MockA a;
 
   EXPECT_CALL(a, DoA(1));
-  EXPECT_CALL(a, DoA(2))
-      .WillOnce(Return());
+  EXPECT_CALL(a, DoA(2)).WillOnce(Return());
 
   a.DoA(1);
   a.DoA(2);
@@ -485,11 +429,11 @@ TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
 TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
   MockA a;
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_CALL(a, DoA(1))
-        .WillRepeatedly(Return())
-        .WillOnce(Return());
-  }, ".WillOnce() cannot appear after ");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillOnce(Return());
+      },
+      ".WillOnce() cannot appear after ");
 
   a.DoA(1);
 }
@@ -497,11 +441,8 @@ TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
 TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
   MockA a;
 
-  EXPECT_CALL(a, DoA(1))
-      .WillOnce(Return());
-  EXPECT_CALL(a, DoA(2))
-      .WillOnce(Return())
-      .WillRepeatedly(Return());
+  EXPECT_CALL(a, DoA(1)).WillOnce(Return());
+  EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return());
 
   a.DoA(1);
   a.DoA(2);
@@ -511,30 +452,30 @@ TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
 TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
   MockA a;
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_CALL(a, DoA(1))
-        .WillRepeatedly(Return())
-        .WillRepeatedly(Return());
-  }, ".WillRepeatedly() cannot appear more than once in an "
-     "EXPECT_CALL()");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillRepeatedly(
+            Return());
+      },
+      ".WillRepeatedly() cannot appear more than once in an "
+      "EXPECT_CALL()");
 }
 
 TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
   MockA a;
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_CALL(a, DoA(1))
-        .RetiresOnSaturation()
-        .WillRepeatedly(Return());
-  }, ".WillRepeatedly() cannot appear after ");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().WillRepeatedly(Return());
+      },
+      ".WillRepeatedly() cannot appear after ");
 }
 
 TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
   MockA a;
 
   EXPECT_CALL(a, DoA(1));
-  EXPECT_CALL(a, DoA(1))
-      .RetiresOnSaturation();
+  EXPECT_CALL(a, DoA(1)).RetiresOnSaturation();
 
   a.DoA(1);
   a.DoA(1);
@@ -543,11 +484,11 @@ TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
 TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
   MockA a;
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_CALL(a, DoA(1))
-        .RetiresOnSaturation()
-        .RetiresOnSaturation();
-  }, ".RetiresOnSaturation() cannot appear more than once");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().RetiresOnSaturation();
+      },
+      ".RetiresOnSaturation() cannot appear more than once");
 
   a.DoA(1);
 }
@@ -558,16 +499,20 @@ TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
     EXPECT_CALL(a, DoA(1));
     a.DoA(1);
   }
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    MockA a;
-    EXPECT_CALL(a, DoA(1));
-  }, "to be called once");
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    MockA a;
-    EXPECT_CALL(a, DoA(1));
-    a.DoA(1);
-    a.DoA(1);
-  }, "to be called once");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        MockA a;
+        EXPECT_CALL(a, DoA(1));
+      },
+      "to be called once");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        MockA a;
+        EXPECT_CALL(a, DoA(1));
+        a.DoA(1);
+        a.DoA(1);
+      },
+      "to be called once");
 }
 
 #if GTEST_HAS_STREAM_REDIRECTION
@@ -580,13 +525,9 @@ TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
     MockB b;
 
     // It's always fine to omit WillOnce() entirely.
-    EXPECT_CALL(b, DoB())
-        .Times(0);
-    EXPECT_CALL(b, DoB(1))
-        .Times(AtMost(1));
-    EXPECT_CALL(b, DoB(2))
-        .Times(1)
-        .WillRepeatedly(Return(1));
+    EXPECT_CALL(b, DoB()).Times(0);
+    EXPECT_CALL(b, DoB(1)).Times(AtMost(1));
+    EXPECT_CALL(b, DoB(2)).Times(1).WillRepeatedly(Return(1));
 
     // It's fine for the number of WillOnce()s to equal the upper bound.
     EXPECT_CALL(b, DoB(3))
@@ -596,10 +537,8 @@ TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
 
     // It's fine for the number of WillOnce()s to be smaller than the
     // upper bound when there is a WillRepeatedly().
-    EXPECT_CALL(b, DoB(4))
-        .Times(AtMost(3))
-        .WillOnce(Return(1))
-        .WillRepeatedly(Return(2));
+    EXPECT_CALL(b, DoB(4)).Times(AtMost(3)).WillOnce(Return(1)).WillRepeatedly(
+        Return(2));
 
     // Satisfies the above expectations.
     b.DoB(2);
@@ -616,13 +555,9 @@ TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
     MockB b;
 
     // Warns when the number of WillOnce()s is larger than the upper bound.
-    EXPECT_CALL(b, DoB())
-        .Times(0)
-        .WillOnce(Return(1));  // #1
-    EXPECT_CALL(b, DoB())
-        .Times(AtMost(1))
-        .WillOnce(Return(1))
-        .WillOnce(Return(2));  // #2
+    EXPECT_CALL(b, DoB()).Times(0).WillOnce(Return(1));  // #1
+    EXPECT_CALL(b, DoB()).Times(AtMost(1)).WillOnce(Return(1)).WillOnce(
+        Return(2));  // #2
     EXPECT_CALL(b, DoB(1))
         .Times(1)
         .WillOnce(Return(1))
@@ -631,41 +566,34 @@ TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
 
     // Warns when the number of WillOnce()s equals the upper bound and
     // there is a WillRepeatedly().
-    EXPECT_CALL(b, DoB())
-        .Times(0)
-        .WillRepeatedly(Return(1));  // #4
-    EXPECT_CALL(b, DoB(2))
-        .Times(1)
-        .WillOnce(Return(1))
-        .WillRepeatedly(Return(2));  // #5
+    EXPECT_CALL(b, DoB()).Times(0).WillRepeatedly(Return(1));  // #4
+    EXPECT_CALL(b, DoB(2)).Times(1).WillOnce(Return(1)).WillRepeatedly(
+        Return(2));  // #5
 
     // Satisfies the above expectations.
     b.DoB(1);
     b.DoB(2);
   }
   const std::string output = GetCapturedStdout();
-  EXPECT_PRED_FORMAT2(
-      IsSubstring,
-      "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
-      "Expected to be never called, but has 1 WillOnce().",
-      output);  // #1
-  EXPECT_PRED_FORMAT2(
-      IsSubstring,
-      "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
-      "Expected to be called at most once, "
-      "but has 2 WillOnce()s.",
-      output);  // #2
+  EXPECT_PRED_FORMAT2(IsSubstring,
+                      "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
+                      "Expected to be never called, but has 1 WillOnce().",
+                      output);  // #1
+  EXPECT_PRED_FORMAT2(IsSubstring,
+                      "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
+                      "Expected to be called at most once, "
+                      "but has 2 WillOnce()s.",
+                      output);  // #2
   EXPECT_PRED_FORMAT2(
       IsSubstring,
       "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
       "Expected to be called once, but has 2 WillOnce()s.",
       output);  // #3
-  EXPECT_PRED_FORMAT2(
-      IsSubstring,
-      "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
-      "Expected to be never called, but has 0 WillOnce()s "
-      "and a WillRepeatedly().",
-      output);  // #4
+  EXPECT_PRED_FORMAT2(IsSubstring,
+                      "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
+                      "Expected to be never called, but has 0 WillOnce()s "
+                      "and a WillRepeatedly().",
+                      output);  // #4
   EXPECT_PRED_FORMAT2(
       IsSubstring,
       "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n"
@@ -679,26 +607,23 @@ TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
 TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
   MockB b;
 
-  EXPECT_CALL(b, DoB())
-      .Times(Between(2, 3))
-      .WillOnce(Return(1));
+  EXPECT_CALL(b, DoB()).Times(Between(2, 3)).WillOnce(Return(1));
 
   CaptureStdout();
   b.DoB();
   const std::string output = GetCapturedStdout();
-  EXPECT_PRED_FORMAT2(
-      IsSubstring,
-      "Too few actions specified in EXPECT_CALL(b, DoB())...\n"
-      "Expected to be called between 2 and 3 times, "
-      "but has only 1 WillOnce().",
-      output);
+  EXPECT_PRED_FORMAT2(IsSubstring,
+                      "Too few actions specified in EXPECT_CALL(b, DoB())...\n"
+                      "Expected to be called between 2 and 3 times, "
+                      "but has only 1 WillOnce().",
+                      output);
   b.DoB();
 }
 
 TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {
-  int original_behavior = testing::GMOCK_FLAG(default_mock_behavior);
+  int original_behavior = GMOCK_FLAG_GET(default_mock_behavior);
 
-  testing::GMOCK_FLAG(default_mock_behavior) = kAllow;
+  GMOCK_FLAG_SET(default_mock_behavior, kAllow);
   CaptureStdout();
   {
     MockA a;
@@ -707,7 +632,7 @@ TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {
   std::string output = GetCapturedStdout();
   EXPECT_TRUE(output.empty()) << output;
 
-  testing::GMOCK_FLAG(default_mock_behavior) = kWarn;
+  GMOCK_FLAG_SET(default_mock_behavior, kWarn);
   CaptureStdout();
   {
     MockA a;
@@ -718,14 +643,16 @@ TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {
   EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
                       warning_output);
 
-  testing::GMOCK_FLAG(default_mock_behavior) = kFail;
-  EXPECT_NONFATAL_FAILURE({
-    MockA a;
-    a.DoA(0);
-  }, "Uninteresting mock function call");
+  GMOCK_FLAG_SET(default_mock_behavior, kFail);
+  EXPECT_NONFATAL_FAILURE(
+      {
+        MockA a;
+        a.DoA(0);
+      },
+      "Uninteresting mock function call");
 
   // Out of bounds values are converted to kWarn
-  testing::GMOCK_FLAG(default_mock_behavior) = -1;
+  GMOCK_FLAG_SET(default_mock_behavior, -1);
   CaptureStdout();
   {
     MockA a;
@@ -735,7 +662,7 @@ TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {
   EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
   EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
                       warning_output);
-  testing::GMOCK_FLAG(default_mock_behavior) = 3;
+  GMOCK_FLAG_SET(default_mock_behavior, 3);
   CaptureStdout();
   {
     MockA a;
@@ -746,7 +673,7 @@ TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {
   EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
                       warning_output);
 
-  testing::GMOCK_FLAG(default_mock_behavior) = original_behavior;
+  GMOCK_FLAG_SET(default_mock_behavior, original_behavior);
 }
 
 #endif  // GTEST_HAS_STREAM_REDIRECTION
@@ -766,8 +693,7 @@ TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
 // matches the invocation.
 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
   MockB b;
-  ON_CALL(b, DoB(1))
-      .WillByDefault(Return(1));
+  ON_CALL(b, DoB(1)).WillByDefault(Return(1));
   EXPECT_CALL(b, DoB(_));
 
   EXPECT_EQ(0, b.DoB(2));
@@ -776,12 +702,9 @@ TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
 // Tests that the last matching ON_CALL() action is taken.
 TEST(OnCallTest, PicksLastMatchingOnCall) {
   MockB b;
-  ON_CALL(b, DoB(_))
-      .WillByDefault(Return(3));
-  ON_CALL(b, DoB(2))
-      .WillByDefault(Return(2));
-  ON_CALL(b, DoB(1))
-      .WillByDefault(Return(1));
+  ON_CALL(b, DoB(_)).WillByDefault(Return(3));
+  ON_CALL(b, DoB(2)).WillByDefault(Return(2));
+  ON_CALL(b, DoB(1)).WillByDefault(Return(1));
   EXPECT_CALL(b, DoB(_));
 
   EXPECT_EQ(2, b.DoB(2));
@@ -805,25 +728,24 @@ TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
 // Tests that the last matching EXPECT_CALL() fires.
 TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
   MockB b;
-  EXPECT_CALL(b, DoB(_))
-      .WillRepeatedly(Return(2));
-  EXPECT_CALL(b, DoB(1))
-      .WillRepeatedly(Return(1));
+  EXPECT_CALL(b, DoB(_)).WillRepeatedly(Return(2));
+  EXPECT_CALL(b, DoB(1)).WillRepeatedly(Return(1));
 
   EXPECT_EQ(1, b.DoB(1));
 }
 
 // Tests lower-bound violation.
 TEST(ExpectCallTest, CatchesTooFewCalls) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    MockB b;
-    EXPECT_CALL(b, DoB(5))
-        .Times(AtLeast(2));
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        MockB b;
+        EXPECT_CALL(b, DoB(5)).Times(AtLeast(2));
 
-    b.DoB(5);
-  }, "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
-     "         Expected: to be called at least twice\n"
-     "           Actual: called once - unsatisfied and active");
+        b.DoB(5);
+      },
+      "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
+      "         Expected: to be called at least twice\n"
+      "           Actual: called once - unsatisfied and active");
 }
 
 // Tests that the cardinality can be inferred when no Times(...) is
@@ -831,28 +753,24 @@ TEST(ExpectCallTest, CatchesTooFewCalls) {
 TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
   {
     MockB b;
-    EXPECT_CALL(b, DoB())
-        .WillOnce(Return(1))
-        .WillOnce(Return(2));
+    EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));
 
     EXPECT_EQ(1, b.DoB());
     EXPECT_EQ(2, b.DoB());
   }
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    MockB b;
-    EXPECT_CALL(b, DoB())
-        .WillOnce(Return(1))
-        .WillOnce(Return(2));
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        MockB b;
+        EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));
 
-    EXPECT_EQ(1, b.DoB());
-  }, "to be called twice");
+        EXPECT_EQ(1, b.DoB());
+      },
+      "to be called twice");
 
   {  // NOLINT
     MockB b;
-    EXPECT_CALL(b, DoB())
-        .WillOnce(Return(1))
-        .WillOnce(Return(2));
+    EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));
 
     EXPECT_EQ(1, b.DoB());
     EXPECT_EQ(2, b.DoB());
@@ -863,40 +781,78 @@ TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
 TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
   {
     MockB b;
-    EXPECT_CALL(b, DoB())
-        .WillOnce(Return(1))
-        .WillRepeatedly(Return(2));
+    EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
 
     EXPECT_EQ(1, b.DoB());
   }
 
   {  // NOLINT
     MockB b;
-    EXPECT_CALL(b, DoB())
-        .WillOnce(Return(1))
-        .WillRepeatedly(Return(2));
+    EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
 
     EXPECT_EQ(1, b.DoB());
     EXPECT_EQ(2, b.DoB());
     EXPECT_EQ(2, b.DoB());
   }
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    MockB b;
-    EXPECT_CALL(b, DoB())
-        .WillOnce(Return(1))
-        .WillRepeatedly(Return(2));
-  }, "to be called at least once");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        MockB b;
+        EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
+      },
+      "to be called at least once");
+}
+
+#if defined(__cplusplus) && __cplusplus >= 201703L
+
+// It should be possible to return a non-moveable type from a mock action in
+// C++17 and above, where it's guaranteed that such a type can be initialized
+// from a prvalue returned from a function.
+TEST(ExpectCallTest, NonMoveableType) {
+  // Define a non-moveable result type.
+  struct Result {
+    explicit Result(int x_in) : x(x_in) {}
+    Result(Result&&) = delete;
+
+    int x;
+  };
+
+  static_assert(!std::is_move_constructible_v<Result>);
+  static_assert(!std::is_copy_constructible_v<Result>);
+
+  static_assert(!std::is_move_assignable_v<Result>);
+  static_assert(!std::is_copy_assignable_v<Result>);
+
+  // We should be able to use a callable that returns that result as both a
+  // OnceAction and an Action, whether the callable ignores arguments or not.
+  const auto return_17 = [] { return Result(17); };
+
+  static_cast<void>(OnceAction<Result()>{return_17});
+  static_cast<void>(Action<Result()>{return_17});
+
+  static_cast<void>(OnceAction<Result(int)>{return_17});
+  static_cast<void>(Action<Result(int)>{return_17});
+
+  // It should be possible to return the result end to end through an
+  // EXPECT_CALL statement, with both WillOnce and WillRepeatedly.
+  MockFunction<Result()> mock;
+  EXPECT_CALL(mock, Call)   //
+      .WillOnce(return_17)  //
+      .WillRepeatedly(return_17);
+
+  EXPECT_EQ(17, mock.AsStdFunction()().x);
+  EXPECT_EQ(17, mock.AsStdFunction()().x);
+  EXPECT_EQ(17, mock.AsStdFunction()().x);
 }
 
+#endif  // C++17 and above
+
 // Tests that the n-th action is taken for the n-th matching
 // invocation.
 TEST(ExpectCallTest, NthMatchTakesNthAction) {
   MockB b;
-  EXPECT_CALL(b, DoB())
-      .WillOnce(Return(1))
-      .WillOnce(Return(2))
-      .WillOnce(Return(3));
+  EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)).WillOnce(
+      Return(3));
 
   EXPECT_EQ(1, b.DoB());
   EXPECT_EQ(2, b.DoB());
@@ -907,9 +863,7 @@ TEST(ExpectCallTest, NthMatchTakesNthAction) {
 // list is exhausted.
 TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
   MockB b;
-  EXPECT_CALL(b, DoB())
-      .WillOnce(Return(1))
-      .WillRepeatedly(Return(2));
+  EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
 
   EXPECT_EQ(1, b.DoB());
   EXPECT_EQ(2, b.DoB());
@@ -922,8 +876,7 @@ TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
 // exhausted and there is no WillRepeatedly().
 TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
   MockB b;
-  EXPECT_CALL(b, DoB(_))
-      .Times(1);
+  EXPECT_CALL(b, DoB(_)).Times(1);
   EXPECT_CALL(b, DoB())
       .Times(AnyNumber())
       .WillOnce(Return(1))
@@ -985,8 +938,7 @@ TEST(UninterestingCallTest, DoesDefaultAction) {
   // When there is an ON_CALL() statement, the action specified by it
   // should be taken.
   MockA a;
-  ON_CALL(a, Binary(_, _))
-      .WillByDefault(Return(true));
+  ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
   EXPECT_TRUE(a.Binary(1, 2));
 
   // When there is no ON_CALL(), the default value for the return type
@@ -1000,8 +952,7 @@ TEST(UnexpectedCallTest, DoesDefaultAction) {
   // When there is an ON_CALL() statement, the action specified by it
   // should be taken.
   MockA a;
-  ON_CALL(a, Binary(_, _))
-      .WillByDefault(Return(true));
+  ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
   EXPECT_CALL(a, Binary(0, 0));
   a.Binary(0, 0);
   bool result = false;
@@ -1012,11 +963,9 @@ TEST(UnexpectedCallTest, DoesDefaultAction) {
   // When there is no ON_CALL(), the default value for the return type
   // should be returned.
   MockB b;
-  EXPECT_CALL(b, DoB(0))
-      .Times(0);
+  EXPECT_CALL(b, DoB(0)).Times(0);
   int n = -1;
-  EXPECT_NONFATAL_FAILURE(n = b.DoB(1),
-                          "Unexpected mock function call");
+  EXPECT_NONFATAL_FAILURE(n = b.DoB(1), "Unexpected mock function call");
   EXPECT_EQ(0, n);
 }
 
@@ -1093,14 +1042,12 @@ TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
 // match the call.
 TEST(UnexpectedCallTest, RetiredExpectation) {
   MockB b;
-  EXPECT_CALL(b, DoB(1))
-      .RetiresOnSaturation();
+  EXPECT_CALL(b, DoB(1)).RetiresOnSaturation();
 
   b.DoB(1);
-  EXPECT_NONFATAL_FAILURE(
-      b.DoB(1),
-      "         Expected: the expectation is active\n"
-      "           Actual: it is retired");
+  EXPECT_NONFATAL_FAILURE(b.DoB(1),
+                          "         Expected: the expectation is active\n"
+                          "           Actual: it is retired");
 }
 
 // Tests that Google Mock explains that an expectation that doesn't
@@ -1109,10 +1056,9 @@ TEST(UnexpectedCallTest, UnmatchedArguments) {
   MockB b;
   EXPECT_CALL(b, DoB(1));
 
-  EXPECT_NONFATAL_FAILURE(
-      b.DoB(2),
-      "  Expected arg #0: is equal to 1\n"
-      "           Actual: 2\n");
+  EXPECT_NONFATAL_FAILURE(b.DoB(2),
+                          "  Expected arg #0: is equal to 1\n"
+                          "           Actual: 2\n");
   b.DoB(1);
 }
 
@@ -1121,15 +1067,10 @@ TEST(UnexpectedCallTest, UnmatchedArguments) {
 TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
   Sequence s1, s2;
   MockB b;
-  EXPECT_CALL(b, DoB(1))
-      .InSequence(s1);
-  EXPECT_CALL(b, DoB(2))
-      .Times(AnyNumber())
-      .InSequence(s1);
-  EXPECT_CALL(b, DoB(3))
-      .InSequence(s2);
-  EXPECT_CALL(b, DoB(4))
-      .InSequence(s1, s2);
+  EXPECT_CALL(b, DoB(1)).InSequence(s1);
+  EXPECT_CALL(b, DoB(2)).Times(AnyNumber()).InSequence(s1);
+  EXPECT_CALL(b, DoB(3)).InSequence(s2);
+  EXPECT_CALL(b, DoB(4)).InSequence(s1, s2);
 
   ::testing::TestPartResultArray failures;
   {
@@ -1147,23 +1088,27 @@ TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
   // Verifies that the failure message contains the two unsatisfied
   // pre-requisites but not the satisfied one.
 #if GTEST_USES_PCRE
-  EXPECT_THAT(r.message(), ContainsRegex(
-      // PCRE has trouble using (.|\n) to match any character, but
-      // supports the (?s) prefix for using . to match any character.
-      "(?s)the following immediate pre-requisites are not satisfied:\n"
-      ".*: pre-requisite #0\n"
-      ".*: pre-requisite #1"));
+  EXPECT_THAT(
+      r.message(),
+      ContainsRegex(
+          // PCRE has trouble using (.|\n) to match any character, but
+          // supports the (?s) prefix for using . to match any character.
+          "(?s)the following immediate pre-requisites are not satisfied:\n"
+          ".*: pre-requisite #0\n"
+          ".*: pre-requisite #1"));
 #elif GTEST_USES_POSIX_RE
-  EXPECT_THAT(r.message(), ContainsRegex(
-      // POSIX RE doesn't understand the (?s) prefix, but has no trouble
-      // with (.|\n).
-      "the following immediate pre-requisites are not satisfied:\n"
-      "(.|\n)*: pre-requisite #0\n"
-      "(.|\n)*: pre-requisite #1"));
+  EXPECT_THAT(r.message(),
+              ContainsRegex(
+                  // POSIX RE doesn't understand the (?s) prefix, but has no
+                  // trouble with (.|\n).
+                  "the following immediate pre-requisites are not satisfied:\n"
+                  "(.|\n)*: pre-requisite #0\n"
+                  "(.|\n)*: pre-requisite #1"));
 #else
   // We can only use Google Test's own simple regex.
-  EXPECT_THAT(r.message(), ContainsRegex(
-      "the following immediate pre-requisites are not satisfied:"));
+  EXPECT_THAT(r.message(),
+              ContainsRegex(
+                  "the following immediate pre-requisites are not satisfied:"));
   EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
   EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
 #endif  // GTEST_USES_PCRE
@@ -1192,8 +1137,7 @@ TEST(ExcessiveCallTest, DoesDefaultAction) {
   // When there is an ON_CALL() statement, the action specified by it
   // should be taken.
   MockA a;
-  ON_CALL(a, Binary(_, _))
-      .WillByDefault(Return(true));
+  ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
   EXPECT_CALL(a, Binary(0, 0));
   a.Binary(0, 0);
   bool result = false;
@@ -1204,8 +1148,7 @@ TEST(ExcessiveCallTest, DoesDefaultAction) {
   // When there is no ON_CALL(), the default value for the return type
   // should be returned.
   MockB b;
-  EXPECT_CALL(b, DoB(0))
-      .Times(0);
+  EXPECT_CALL(b, DoB(0)).Times(0);
   int n = -1;
   EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
                           "Mock function called more times than expected");
@@ -1216,8 +1159,7 @@ TEST(ExcessiveCallTest, DoesDefaultAction) {
 // the failure message contains the argument values.
 TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
   MockA a;
-  EXPECT_CALL(a, DoA(_))
-      .Times(0);
+  EXPECT_CALL(a, DoA(_)).Times(0);
   EXPECT_NONFATAL_FAILURE(
       a.DoA(9),
       "Mock function called more times than expected - returning directly.\n"
@@ -1253,9 +1195,11 @@ TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
     EXPECT_CALL(a, DoA(2));
   }
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    a.DoA(2);
-  }, "Unexpected mock function call");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        a.DoA(2);
+      },
+      "Unexpected mock function call");
 
   a.DoA(1);
   a.DoA(2);
@@ -1275,10 +1219,12 @@ TEST(InSequenceTest, NestedInSequence) {
     }
   }
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    a.DoA(1);
-    a.DoA(3);
-  }, "Unexpected mock function call");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        a.DoA(1);
+        a.DoA(3);
+      },
+      "Unexpected mock function call");
 
   a.DoA(2);
   a.DoA(3);
@@ -1294,9 +1240,11 @@ TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
   }
   EXPECT_CALL(a, DoA(3));
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    a.DoA(2);
-  }, "Unexpected mock function call");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        a.DoA(2);
+      },
+      "Unexpected mock function call");
 
   a.DoA(3);
   a.DoA(1);
@@ -1310,8 +1258,7 @@ TEST(SequenceTest, AnyOrderIsOkByDefault) {
     MockB b;
 
     EXPECT_CALL(a, DoA(1));
-    EXPECT_CALL(b, DoB())
-        .Times(AnyNumber());
+    EXPECT_CALL(b, DoB()).Times(AnyNumber());
 
     a.DoA(1);
     b.DoB();
@@ -1322,8 +1269,7 @@ TEST(SequenceTest, AnyOrderIsOkByDefault) {
     MockB b;
 
     EXPECT_CALL(a, DoA(1));
-    EXPECT_CALL(b, DoB())
-        .Times(AnyNumber());
+    EXPECT_CALL(b, DoB()).Times(AnyNumber());
 
     b.DoB();
     a.DoA(1);
@@ -1334,16 +1280,12 @@ TEST(SequenceTest, AnyOrderIsOkByDefault) {
 // is specified.
 TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
   MockA a;
-  ON_CALL(a, ReturnResult(_))
-      .WillByDefault(Return(Result()));
+  ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
 
   Sequence s;
-  EXPECT_CALL(a, ReturnResult(1))
-      .InSequence(s);
-  EXPECT_CALL(a, ReturnResult(2))
-      .InSequence(s);
-  EXPECT_CALL(a, ReturnResult(3))
-      .InSequence(s);
+  EXPECT_CALL(a, ReturnResult(1)).InSequence(s);
+  EXPECT_CALL(a, ReturnResult(2)).InSequence(s);
+  EXPECT_CALL(a, ReturnResult(3)).InSequence(s);
 
   a.ReturnResult(1);
 
@@ -1358,14 +1300,11 @@ TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
 // is specified.
 TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
   MockA a;
-  ON_CALL(a, ReturnResult(_))
-      .WillByDefault(Return(Result()));
+  ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
 
   Sequence s;
-  EXPECT_CALL(a, ReturnResult(1))
-      .InSequence(s);
-  EXPECT_CALL(a, ReturnResult(2))
-      .InSequence(s);
+  EXPECT_CALL(a, ReturnResult(1)).InSequence(s);
+  EXPECT_CALL(a, ReturnResult(2)).InSequence(s);
 
   // May only be called after a.ReturnResult(1).
   EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");
@@ -1378,8 +1317,7 @@ TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
 class PartialOrderTest : public testing::Test {
  protected:
   PartialOrderTest() {
-    ON_CALL(a_, ReturnResult(_))
-        .WillByDefault(Return(Result()));
+    ON_CALL(a_, ReturnResult(_)).WillByDefault(Return(Result()));
 
     // Specifies this partial ordering:
     //
@@ -1387,16 +1325,10 @@ class PartialOrderTest : public testing::Test {
     //                       a.ReturnResult(2) * n  ==>  a.ReturnResult(3)
     // b.DoB() * 2       ==>
     Sequence x, y;
-    EXPECT_CALL(a_, ReturnResult(1))
-        .InSequence(x);
-    EXPECT_CALL(b_, DoB())
-        .Times(2)
-        .InSequence(y);
-    EXPECT_CALL(a_, ReturnResult(2))
-        .Times(AnyNumber())
-        .InSequence(x, y);
-    EXPECT_CALL(a_, ReturnResult(3))
-        .InSequence(x);
+    EXPECT_CALL(a_, ReturnResult(1)).InSequence(x);
+    EXPECT_CALL(b_, DoB()).Times(2).InSequence(y);
+    EXPECT_CALL(a_, ReturnResult(2)).Times(AnyNumber()).InSequence(x, y);
+    EXPECT_CALL(a_, ReturnResult(3)).InSequence(x);
   }
 
   MockA a_;
@@ -1448,13 +1380,9 @@ TEST(SequenceTest, Retirement) {
   MockA a;
   Sequence s;
 
-  EXPECT_CALL(a, DoA(1))
-      .InSequence(s);
-  EXPECT_CALL(a, DoA(_))
-      .InSequence(s)
-      .RetiresOnSaturation();
-  EXPECT_CALL(a, DoA(1))
-      .InSequence(s);
+  EXPECT_CALL(a, DoA(1)).InSequence(s);
+  EXPECT_CALL(a, DoA(_)).InSequence(s).RetiresOnSaturation();
+  EXPECT_CALL(a, DoA(1)).InSequence(s);
 
   a.DoA(1);
   a.DoA(2);
@@ -1519,12 +1447,12 @@ TEST(ExpectationSetTest, ConstructorsWork) {
 
   Expectation e1;
   const Expectation e2;
-  ExpectationSet es1;  // Default ctor.
+  ExpectationSet es1;                           // Default ctor.
   ExpectationSet es2 = EXPECT_CALL(a, DoA(1));  // Ctor from EXPECT_CALL.
-  ExpectationSet es3 = e1;  // Ctor from Expectation.
-  ExpectationSet es4(e1);   // Ctor from Expectation; alternative syntax.
-  ExpectationSet es5 = e2;  // Ctor from const Expectation.
-  ExpectationSet es6(e2);   // Ctor from const Expectation; alternative syntax.
+  ExpectationSet es3 = e1;                      // Ctor from Expectation.
+  ExpectationSet es4(e1);    // Ctor from Expectation; alternative syntax.
+  ExpectationSet es5 = e2;   // Ctor from const Expectation.
+  ExpectationSet es6(e2);    // Ctor from const Expectation; alternative syntax.
   ExpectationSet es7 = es2;  // Copy ctor.
 
   EXPECT_EQ(0, es1.size());
@@ -1596,7 +1524,7 @@ TEST(ExpectationSetTest, IsEnumerable) {
   EXPECT_TRUE(it != es.end());
   EXPECT_THAT(*it, Eq(Expectation()));
   ++it;
-  EXPECT_TRUE(it== es.end());
+  EXPECT_TRUE(it == es.end());
 }
 
 // Tests the .After() clause.
@@ -1606,8 +1534,7 @@ TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
   ExpectationSet es;
   es += EXPECT_CALL(a, DoA(1));
   es += EXPECT_CALL(a, DoA(2));
-  EXPECT_CALL(a, DoA(3))
-      .After(es);
+  EXPECT_CALL(a, DoA(3)).After(es);
 
   a.DoA(1);
   a.DoA(2);
@@ -1620,9 +1547,7 @@ TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
   // The following also verifies that const Expectation objects work
   // too.  Do not remove the const modifiers.
   const Expectation e1 = EXPECT_CALL(a, DoA(1));
-  const Expectation e2 = EXPECT_CALL(b, DoB())
-      .Times(2)
-      .After(e1);
+  const Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1);
   EXPECT_CALL(a, DoA(2)).After(e2);
 
   a.DoA(1);
@@ -1639,10 +1564,8 @@ TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {
   // Define ordering:
   //   a.DoA(1) ==> b.DoB() ==> a.DoA(2)
   Expectation e1 = EXPECT_CALL(a, DoA(1));
-  Expectation e2 = EXPECT_CALL(b, DoB())
-      .After(e1);
-  EXPECT_CALL(a, DoA(2))
-      .After(e2);
+  Expectation e2 = EXPECT_CALL(b, DoB()).After(e1);
+  EXPECT_CALL(a, DoA(2)).After(e2);
 
   a.DoA(1);
 
@@ -1661,11 +1584,8 @@ TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
   // Define ordering:
   //   a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)
   Expectation e1 = EXPECT_CALL(a, DoA(1));
-  Expectation e2 = EXPECT_CALL(b, DoB())
-      .Times(2)
-      .After(e1);
-  EXPECT_CALL(a, DoA(2))
-      .After(e2);
+  Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1);
+  EXPECT_CALL(a, DoA(2)).After(e2);
 
   a.DoA(1);
   b.DoB();
@@ -1680,16 +1600,14 @@ TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
 // Calls must satisfy the partial order when specified so.
 TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
   MockA a;
-  ON_CALL(a, ReturnResult(_))
-      .WillByDefault(Return(Result()));
+  ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
 
   // Define ordering:
   //   a.DoA(1) ==>
   //   a.DoA(2) ==> a.ReturnResult(3)
   Expectation e = EXPECT_CALL(a, DoA(1));
   const ExpectationSet es = EXPECT_CALL(a, DoA(2));
-  EXPECT_CALL(a, ReturnResult(3))
-      .After(e, es);
+  EXPECT_CALL(a, ReturnResult(3)).After(e, es);
 
   // May only be called last.
   EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
@@ -1708,8 +1626,7 @@ TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {
   //   a.DoA(2) ==> a.DoA(3)
   Expectation e = EXPECT_CALL(a, DoA(1));
   const ExpectationSet es = EXPECT_CALL(a, DoA(2));
-  EXPECT_CALL(a, DoA(3))
-      .After(e, es);
+  EXPECT_CALL(a, DoA(3)).After(e, es);
 
   a.DoA(2);
 
@@ -1726,9 +1643,7 @@ TEST(AfterTest, CanBeUsedWithInSequence) {
   Sequence s;
   Expectation e = EXPECT_CALL(a, DoA(1));
   EXPECT_CALL(a, DoA(2)).InSequence(s);
-  EXPECT_CALL(a, DoA(3))
-      .InSequence(s)
-      .After(e);
+  EXPECT_CALL(a, DoA(3)).InSequence(s).After(e);
 
   a.DoA(1);
 
@@ -1745,10 +1660,7 @@ TEST(AfterTest, CanBeCalledManyTimes) {
   Expectation e1 = EXPECT_CALL(a, DoA(1));
   Expectation e2 = EXPECT_CALL(a, DoA(2));
   Expectation e3 = EXPECT_CALL(a, DoA(3));
-  EXPECT_CALL(a, DoA(4))
-      .After(e1)
-      .After(e2)
-      .After(e3);
+  EXPECT_CALL(a, DoA(4)).After(e1).After(e2).After(e3);
 
   a.DoA(3);
   a.DoA(1);
@@ -1764,8 +1676,7 @@ TEST(AfterTest, AcceptsUpToFiveArguments) {
   Expectation e3 = EXPECT_CALL(a, DoA(3));
   ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
   ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
-  EXPECT_CALL(a, DoA(6))
-      .After(e1, e2, e3, es1, es2);
+  EXPECT_CALL(a, DoA(6)).After(e1, e2, e3, es1, es2);
 
   a.DoA(5);
   a.DoA(2);
@@ -1778,8 +1689,7 @@ TEST(AfterTest, AcceptsUpToFiveArguments) {
 // .After() allows input to contain duplicated Expectations.
 TEST(AfterTest, AcceptsDuplicatedInput) {
   MockA a;
-  ON_CALL(a, ReturnResult(_))
-      .WillByDefault(Return(Result()));
+  ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
 
   // Define ordering:
   //   DoA(1) ==>
@@ -1789,8 +1699,7 @@ TEST(AfterTest, AcceptsDuplicatedInput) {
   ExpectationSet es;
   es += e1;
   es += e2;
-  EXPECT_CALL(a, ReturnResult(3))
-      .After(e1, e2, es, e1);
+  EXPECT_CALL(a, ReturnResult(3)).After(e1, e2, es, e1);
 
   a.DoA(1);
 
@@ -1807,8 +1716,7 @@ TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
   MockA a;
   ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
   Expectation e2 = EXPECT_CALL(a, DoA(2));
-  EXPECT_CALL(a, DoA(3))
-      .After(es1);
+  EXPECT_CALL(a, DoA(3)).After(es1);
   es1 += e2;
 
   a.DoA(1);
@@ -1827,14 +1735,11 @@ TEST(DeletingMockEarlyTest, Success1) {
 
   {
     InSequence dummy;
-    EXPECT_CALL(*b1, DoB(_))
-        .WillOnce(Return(1));
+    EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));
     EXPECT_CALL(*a, Binary(_, _))
         .Times(AnyNumber())
         .WillRepeatedly(Return(true));
-    EXPECT_CALL(*b2, DoB(_))
-        .Times(AnyNumber())
-        .WillRepeatedly(Return(2));
+    EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));
   }
 
   EXPECT_EQ(1, b1->DoB(1));
@@ -1855,13 +1760,9 @@ TEST(DeletingMockEarlyTest, Success2) {
 
   {
     InSequence dummy;
-    EXPECT_CALL(*b1, DoB(_))
-        .WillOnce(Return(1));
-    EXPECT_CALL(*a, Binary(_, _))
-        .Times(AnyNumber());
-    EXPECT_CALL(*b2, DoB(_))
-        .Times(AnyNumber())
-        .WillRepeatedly(Return(2));
+    EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));
+    EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
+    EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));
   }
 
   delete a;  // a is trivially satisfied.
@@ -1876,14 +1777,14 @@ TEST(DeletingMockEarlyTest, Success2) {
 // Suppresses warning on unreferenced formal parameter in MSVC with
 // -W4.
 #ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
+#pragma warning(push)
+#pragma warning(disable : 4100)
 #endif
 
 ACTION_P(Delete, ptr) { delete ptr; }
 
 #ifdef _MSC_VER
-# pragma warning(pop)
+#pragma warning(pop)
 #endif
 
 TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
@@ -1894,8 +1795,7 @@ TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
 
 TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
   MockA* const a = new MockA;
-  EXPECT_CALL(*a, ReturnResult(_))
-      .WillOnce(DoAll(Delete(a), Return(Result())));
+  EXPECT_CALL(*a, ReturnResult(_)).WillOnce(DoAll(Delete(a), Return(Result())));
   a->ReturnResult(42);  // This will cause a to be deleted.
 }
 
@@ -1907,19 +1807,13 @@ TEST(DeletingMockEarlyTest, Failure1) {
 
   {
     InSequence dummy;
-    EXPECT_CALL(*b1, DoB(_))
-        .WillOnce(Return(1));
-    EXPECT_CALL(*a, Binary(_, _))
-        .Times(AnyNumber());
-    EXPECT_CALL(*b2, DoB(_))
-        .Times(AnyNumber())
-        .WillRepeatedly(Return(2));
+    EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));
+    EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
+    EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));
   }
 
   delete a;  // a is trivially satisfied.
-  EXPECT_NONFATAL_FAILURE({
-    b2->DoB(2);
-  }, "Unexpected mock function call");
+  EXPECT_NONFATAL_FAILURE({ b2->DoB(2); }, "Unexpected mock function call");
   EXPECT_EQ(1, b1->DoB(1));
   delete b1;
   delete b2;
@@ -1934,18 +1828,13 @@ TEST(DeletingMockEarlyTest, Failure2) {
   {
     InSequence dummy;
     EXPECT_CALL(*b1, DoB(_));
-    EXPECT_CALL(*a, Binary(_, _))
-        .Times(AnyNumber());
-    EXPECT_CALL(*b2, DoB(_))
-        .Times(AnyNumber());
+    EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
+    EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber());
   }
 
-  EXPECT_NONFATAL_FAILURE(delete b1,
-                          "Actual: never called");
-  EXPECT_NONFATAL_FAILURE(a->Binary(0, 1),
-                          "Unexpected mock function call");
-  EXPECT_NONFATAL_FAILURE(b2->DoB(1),
-                          "Unexpected mock function call");
+  EXPECT_NONFATAL_FAILURE(delete b1, "Actual: never called");
+  EXPECT_NONFATAL_FAILURE(a->Binary(0, 1), "Unexpected mock function call");
+  EXPECT_NONFATAL_FAILURE(b2->DoB(1), "Unexpected mock function call");
   delete a;
   delete b2;
 }
@@ -1970,23 +1859,16 @@ class EvenNumberCardinality : public CardinalityInterface {
   }
 };
 
-Cardinality EvenNumber() {
-  return Cardinality(new EvenNumberCardinality);
-}
+Cardinality EvenNumber() { return Cardinality(new EvenNumberCardinality); }
 
 TEST(ExpectationBaseTest,
      AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
   MockA* a = new MockA;
   Sequence s;
 
-  EXPECT_CALL(*a, DoA(1))
-      .Times(EvenNumber())
-      .InSequence(s);
-  EXPECT_CALL(*a, DoA(2))
-      .Times(AnyNumber())
-      .InSequence(s);
-  EXPECT_CALL(*a, DoA(3))
-      .Times(AnyNumber());
+  EXPECT_CALL(*a, DoA(1)).Times(EvenNumber()).InSequence(s);
+  EXPECT_CALL(*a, DoA(2)).Times(AnyNumber()).InSequence(s);
+  EXPECT_CALL(*a, DoA(3)).Times(AnyNumber());
 
   a->DoA(3);
   a->DoA(1);
@@ -1997,8 +1879,7 @@ TEST(ExpectationBaseTest,
 // The following tests verify the message generated when a mock
 // function is called.
 
-struct Printable {
-};
+struct Printable {};
 
 inline void operator<<(::std::ostream& os, const Printable&) {
   os << "Printable";
@@ -2018,22 +1899,25 @@ class MockC {
   MOCK_METHOD0(NonVoidMethod, int());  // NOLINT
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC);
+  MockC(const MockC&) = delete;
+  MockC& operator=(const MockC&) = delete;
 };
 
 class VerboseFlagPreservingFixture : public testing::Test {
  protected:
   VerboseFlagPreservingFixture()
-      : saved_verbose_flag_(GMOCK_FLAG(verbose)) {}
+      : saved_verbose_flag_(GMOCK_FLAG_GET(verbose)) {}
 
   ~VerboseFlagPreservingFixture() override {
-    GMOCK_FLAG(verbose) = saved_verbose_flag_;
+    GMOCK_FLAG_SET(verbose, saved_verbose_flag_);
   }
 
  private:
   const std::string saved_verbose_flag_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture);
+  VerboseFlagPreservingFixture(const VerboseFlagPreservingFixture&) = delete;
+  VerboseFlagPreservingFixture& operator=(const VerboseFlagPreservingFixture&) =
+      delete;
 };
 
 #if GTEST_HAS_STREAM_REDIRECTION
@@ -2043,7 +1927,7 @@ class VerboseFlagPreservingFixture : public testing::Test {
 // --gmock_verbose=warning is specified.
 TEST(FunctionCallMessageTest,
      UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {
-  GMOCK_FLAG(verbose) = kWarningVerbosity;
+  GMOCK_FLAG_SET(verbose, kWarningVerbosity);
   NaggyMock<MockC> c;
   CaptureStdout();
   c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
@@ -2057,7 +1941,7 @@ TEST(FunctionCallMessageTest,
 // --gmock_verbose=info is specified.
 TEST(FunctionCallMessageTest,
      UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {
-  GMOCK_FLAG(verbose) = kInfoVerbosity;
+  GMOCK_FLAG_SET(verbose, kInfoVerbosity);
   NaggyMock<MockC> c;
   CaptureStdout();
   c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
@@ -2065,7 +1949,7 @@ TEST(FunctionCallMessageTest,
   EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
   EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
 
-# ifndef NDEBUG
+#ifndef NDEBUG
 
   // We check the stack trace content in dbg-mode only, as opt-mode
   // may inline the call we are interested in seeing.
@@ -2081,7 +1965,7 @@ TEST(FunctionCallMessageTest,
   const std::string output2 = GetCapturedStdout();
   EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
 
-# endif  // NDEBUG
+#endif  // NDEBUG
 }
 
 // Tests that an uninteresting mock function call on a naggy mock
@@ -2097,7 +1981,8 @@ TEST(FunctionCallMessageTest,
       IsSubstring,
       "Uninteresting mock function call - returning default value.\n"
       "    Function call: DoB()\n"
-      "          Returns: 0\n", output1.c_str());
+      "          Returns: 0\n",
+      output1.c_str());
   // Makes sure the return value is printed.
 
   // A void mock function.
@@ -2105,12 +1990,12 @@ TEST(FunctionCallMessageTest,
   CaptureStdout();
   c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
   const std::string output2 = GetCapturedStdout();
-  EXPECT_THAT(output2.c_str(),
-              ContainsRegex(
-                  "Uninteresting mock function call - returning directly\\.\n"
-                  "    Function call: VoidMethod"
-                  "\\(false, 5, \"Hi\", NULL, @.+ "
-                  "Printable, 4-byte object <00-00 00-00>\\)"));
+  EXPECT_THAT(
+      output2.c_str(),
+      ContainsRegex("Uninteresting mock function call - returning directly\\.\n"
+                    "    Function call: VoidMethod"
+                    "\\(false, 5, \"Hi\", NULL, @.+ "
+                    "Printable, 4-byte object <00-00 00-00>\\)"));
   // A void function has no return value to print.
 }
 
@@ -2127,14 +2012,14 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
                     const std::string& function_name) {
     if (should_print) {
       EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
-# ifndef NDEBUG
+#ifndef NDEBUG
       // We check the stack trace content in dbg-mode only, as opt-mode
       // may inline the call we are interested in seeing.
       EXPECT_THAT(output.c_str(), HasSubstr(function_name));
-# else
+#else
       // Suppresses 'unused function parameter' warnings.
       static_cast<void>(function_name);
-# endif  // NDEBUG
+#endif  // NDEBUG
     } else {
       EXPECT_STREQ("", output.c_str());
     }
@@ -2144,31 +2029,26 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
   void TestExpectedCall(bool should_print) {
     MockA a;
     EXPECT_CALL(a, DoA(5));
-    EXPECT_CALL(a, Binary(_, 1))
-        .WillOnce(Return(true));
+    EXPECT_CALL(a, Binary(_, 1)).WillOnce(Return(true));
 
     // A void-returning function.
     CaptureStdout();
     a.DoA(5);
-    VerifyOutput(
-        GetCapturedStdout(),
-        should_print,
-        "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
-        "    Function call: DoA(5)\n"
-        "Stack trace:\n",
-        "DoA");
+    VerifyOutput(GetCapturedStdout(), should_print,
+                 "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
+                 "    Function call: DoA(5)\n"
+                 "Stack trace:\n",
+                 "DoA");
 
     // A non-void-returning function.
     CaptureStdout();
     a.Binary(2, 1);
-    VerifyOutput(
-        GetCapturedStdout(),
-        should_print,
-        "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
-        "    Function call: Binary(2, 1)\n"
-        "          Returns: true\n"
-        "Stack trace:\n",
-        "Binary");
+    VerifyOutput(GetCapturedStdout(), should_print,
+                 "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
+                 "    Function call: Binary(2, 1)\n"
+                 "          Returns: true\n"
+                 "Stack trace:\n",
+                 "Binary");
   }
 
   // Tests how the flag affects uninteresting calls on a naggy mock.
@@ -2186,34 +2066,30 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
     // A void-returning function.
     CaptureStdout();
     a.DoA(5);
-    VerifyOutput(
-        GetCapturedStdout(),
-        should_print,
-        "\nGMOCK WARNING:\n"
-        "Uninteresting mock function call - returning directly.\n"
-        "    Function call: DoA(5)\n" +
-        note,
-        "DoA");
+    VerifyOutput(GetCapturedStdout(), should_print,
+                 "\nGMOCK WARNING:\n"
+                 "Uninteresting mock function call - returning directly.\n"
+                 "    Function call: DoA(5)\n" +
+                     note,
+                 "DoA");
 
     // A non-void-returning function.
     CaptureStdout();
     a.Binary(2, 1);
-    VerifyOutput(
-        GetCapturedStdout(),
-        should_print,
-        "\nGMOCK WARNING:\n"
-        "Uninteresting mock function call - returning default value.\n"
-        "    Function call: Binary(2, 1)\n"
-        "          Returns: false\n" +
-        note,
-        "Binary");
+    VerifyOutput(GetCapturedStdout(), should_print,
+                 "\nGMOCK WARNING:\n"
+                 "Uninteresting mock function call - returning default value.\n"
+                 "    Function call: Binary(2, 1)\n"
+                 "          Returns: false\n" +
+                     note,
+                 "Binary");
   }
 };
 
 // Tests that --gmock_verbose=info causes both expected and
 // uninteresting calls to be reported.
 TEST_F(GMockVerboseFlagTest, Info) {
-  GMOCK_FLAG(verbose) = kInfoVerbosity;
+  GMOCK_FLAG_SET(verbose, kInfoVerbosity);
   TestExpectedCall(true);
   TestUninterestingCallOnNaggyMock(true);
 }
@@ -2221,7 +2097,7 @@ TEST_F(GMockVerboseFlagTest, Info) {
 // Tests that --gmock_verbose=warning causes uninteresting calls to be
 // reported.
 TEST_F(GMockVerboseFlagTest, Warning) {
-  GMOCK_FLAG(verbose) = kWarningVerbosity;
+  GMOCK_FLAG_SET(verbose, kWarningVerbosity);
   TestExpectedCall(false);
   TestUninterestingCallOnNaggyMock(true);
 }
@@ -2229,7 +2105,7 @@ TEST_F(GMockVerboseFlagTest, Warning) {
 // Tests that --gmock_verbose=warning causes neither expected nor
 // uninteresting calls to be reported.
 TEST_F(GMockVerboseFlagTest, Error) {
-  GMOCK_FLAG(verbose) = kErrorVerbosity;
+  GMOCK_FLAG_SET(verbose, kErrorVerbosity);
   TestExpectedCall(false);
   TestUninterestingCallOnNaggyMock(false);
 }
@@ -2237,7 +2113,7 @@ TEST_F(GMockVerboseFlagTest, Error) {
 // Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
 // as --gmock_verbose=warning.
 TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
-  GMOCK_FLAG(verbose) = "invalid";  // Treated as "warning".
+  GMOCK_FLAG_SET(verbose, "invalid");  // Treated as "warning".
   TestExpectedCall(false);
   TestUninterestingCallOnNaggyMock(true);
 }
@@ -2261,7 +2137,8 @@ class LogTestHelper {
   MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper);
+  LogTestHelper(const LogTestHelper&) = delete;
+  LogTestHelper& operator=(const LogTestHelper&) = delete;
 };
 
 class GMockLogTest : public VerboseFlagPreservingFixture {
@@ -2270,23 +2147,20 @@ class GMockLogTest : public VerboseFlagPreservingFixture {
 };
 
 TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
-  GMOCK_FLAG(verbose) = kWarningVerbosity;
-  EXPECT_CALL(helper_, Foo(_))
-      .WillOnce(Return(PrintMeNot()));
+  GMOCK_FLAG_SET(verbose, kWarningVerbosity);
+  EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));
   helper_.Foo(PrintMeNot());  // This is an expected call.
 }
 
 TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
-  GMOCK_FLAG(verbose) = kErrorVerbosity;
-  EXPECT_CALL(helper_, Foo(_))
-      .WillOnce(Return(PrintMeNot()));
+  GMOCK_FLAG_SET(verbose, kErrorVerbosity);
+  EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));
   helper_.Foo(PrintMeNot());  // This is an expected call.
 }
 
 TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
-  GMOCK_FLAG(verbose) = kErrorVerbosity;
-  ON_CALL(helper_, Foo(_))
-      .WillByDefault(Return(PrintMeNot()));
+  GMOCK_FLAG_SET(verbose, kErrorVerbosity);
+  ON_CALL(helper_, Foo(_)).WillByDefault(Return(PrintMeNot()));
   helper_.Foo(PrintMeNot());  // This should generate a warning.
 }
 
@@ -2347,8 +2221,7 @@ TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
 // verification succeeds.
 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
   MockB b;
-  EXPECT_CALL(b, DoB())
-      .WillOnce(Return(1));
+  EXPECT_CALL(b, DoB()).WillOnce(Return(1));
   b.DoB();
   ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
 
@@ -2363,8 +2236,7 @@ TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
 // verification fails.
 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
   MockB b;
-  EXPECT_CALL(b, DoB())
-      .WillOnce(Return(1));
+  EXPECT_CALL(b, DoB()).WillOnce(Return(1));
   bool result = true;
   EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
                           "Actual: never called");
@@ -2380,10 +2252,8 @@ TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
 // when all of its methods have expectations.
 TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
   MockB b;
-  EXPECT_CALL(b, DoB())
-      .WillOnce(Return(1));
-  EXPECT_CALL(b, DoB(_))
-      .WillOnce(Return(2));
+  EXPECT_CALL(b, DoB()).WillOnce(Return(1));
+  EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
   b.DoB();
   b.DoB(1);
   ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
@@ -2398,10 +2268,8 @@ TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
 // when a method has more than one expectation.
 TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
   MockB b;
-  EXPECT_CALL(b, DoB(0))
-      .WillOnce(Return(1));
-  EXPECT_CALL(b, DoB(_))
-      .WillOnce(Return(2));
+  EXPECT_CALL(b, DoB(0)).WillOnce(Return(1));
+  EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
   b.DoB(1);
   bool result = true;
   EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
@@ -2422,8 +2290,7 @@ TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
   b.DoB();
   Mock::VerifyAndClearExpectations(&b);
 
-  EXPECT_CALL(b, DoB(_))
-      .WillOnce(Return(1));
+  EXPECT_CALL(b, DoB(_)).WillOnce(Return(1));
   b.DoB(1);
   Mock::VerifyAndClearExpectations(&b);
   Mock::VerifyAndClearExpectations(&b);
@@ -2447,8 +2314,7 @@ TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
 // but not all of its methods have default actions.
 TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
   MockB b;
-  ON_CALL(b, DoB())
-      .WillByDefault(Return(1));
+  ON_CALL(b, DoB()).WillByDefault(Return(1));
 
   Mock::VerifyAndClear(&b);
 
@@ -2460,10 +2326,8 @@ TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
 // its methods have default actions.
 TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
   MockB b;
-  ON_CALL(b, DoB())
-      .WillByDefault(Return(1));
-  ON_CALL(b, DoB(_))
-      .WillByDefault(Return(2));
+  ON_CALL(b, DoB()).WillByDefault(Return(1));
+  ON_CALL(b, DoB(_)).WillByDefault(Return(2));
 
   Mock::VerifyAndClear(&b);
 
@@ -2478,10 +2342,8 @@ TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
 // method has more than one ON_CALL() set on it.
 TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
   MockB b;
-  ON_CALL(b, DoB(0))
-      .WillByDefault(Return(1));
-  ON_CALL(b, DoB(_))
-      .WillByDefault(Return(2));
+  ON_CALL(b, DoB(0)).WillByDefault(Return(1));
+  ON_CALL(b, DoB(_)).WillByDefault(Return(2));
 
   Mock::VerifyAndClear(&b);
 
@@ -2495,13 +2357,11 @@ TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
 // times.
 TEST(VerifyAndClearTest, CanCallManyTimes) {
   MockB b;
-  ON_CALL(b, DoB())
-      .WillByDefault(Return(1));
+  ON_CALL(b, DoB()).WillByDefault(Return(1));
   Mock::VerifyAndClear(&b);
   Mock::VerifyAndClear(&b);
 
-  ON_CALL(b, DoB(_))
-      .WillByDefault(Return(1));
+  ON_CALL(b, DoB(_)).WillByDefault(Return(1));
   Mock::VerifyAndClear(&b);
 
   EXPECT_EQ(0, b.DoB());
@@ -2511,10 +2371,8 @@ TEST(VerifyAndClearTest, CanCallManyTimes) {
 // Tests that VerifyAndClear() works when the verification succeeds.
 TEST(VerifyAndClearTest, Success) {
   MockB b;
-  ON_CALL(b, DoB())
-      .WillByDefault(Return(1));
-  EXPECT_CALL(b, DoB(1))
-      .WillOnce(Return(2));
+  ON_CALL(b, DoB()).WillByDefault(Return(1));
+  EXPECT_CALL(b, DoB(1)).WillOnce(Return(2));
 
   b.DoB();
   b.DoB(1);
@@ -2529,10 +2387,8 @@ TEST(VerifyAndClearTest, Success) {
 // Tests that VerifyAndClear() works when the verification fails.
 TEST(VerifyAndClearTest, Failure) {
   MockB b;
-  ON_CALL(b, DoB(_))
-      .WillByDefault(Return(1));
-  EXPECT_CALL(b, DoB())
-      .WillOnce(Return(2));
+  ON_CALL(b, DoB(_)).WillByDefault(Return(1));
+  EXPECT_CALL(b, DoB()).WillOnce(Return(2));
 
   b.DoB(1);
   bool result = true;
@@ -2550,12 +2406,9 @@ TEST(VerifyAndClearTest, Failure) {
 // expectations are set on a const mock object.
 TEST(VerifyAndClearTest, Const) {
   MockB b;
-  ON_CALL(Const(b), DoB())
-      .WillByDefault(Return(1));
+  ON_CALL(Const(b), DoB()).WillByDefault(Return(1));
 
-  EXPECT_CALL(Const(b), DoB())
-      .WillOnce(DoDefault())
-      .WillOnce(Return(2));
+  EXPECT_CALL(Const(b), DoB()).WillOnce(DoDefault()).WillOnce(Return(2));
 
   b.DoB();
   b.DoB();
@@ -2571,18 +2424,14 @@ TEST(VerifyAndClearTest, Const) {
 // object after VerifyAndClear() has been called on it.
 TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
   MockB b;
-  ON_CALL(b, DoB())
-      .WillByDefault(Return(1));
-  EXPECT_CALL(b, DoB(_))
-      .WillOnce(Return(2));
+  ON_CALL(b, DoB()).WillByDefault(Return(1));
+  EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
   b.DoB(1);
 
   Mock::VerifyAndClear(&b);
 
-  EXPECT_CALL(b, DoB())
-      .WillOnce(Return(3));
-  ON_CALL(b, DoB(_))
-      .WillByDefault(Return(4));
+  EXPECT_CALL(b, DoB()).WillOnce(Return(3));
+  ON_CALL(b, DoB(_)).WillByDefault(Return(4));
 
   EXPECT_EQ(3, b.DoB());
   EXPECT_EQ(4, b.DoB(1));
@@ -2595,19 +2444,13 @@ TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
   MockB b1;
   MockB b2;
 
-  ON_CALL(a, Binary(_, _))
-      .WillByDefault(Return(true));
-  EXPECT_CALL(a, Binary(_, _))
-      .WillOnce(DoDefault())
-      .WillOnce(Return(false));
+  ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
+  EXPECT_CALL(a, Binary(_, _)).WillOnce(DoDefault()).WillOnce(Return(false));
 
-  ON_CALL(b1, DoB())
-      .WillByDefault(Return(1));
-  EXPECT_CALL(b1, DoB(_))
-      .WillOnce(Return(2));
+  ON_CALL(b1, DoB()).WillByDefault(Return(1));
+  EXPECT_CALL(b1, DoB(_)).WillOnce(Return(2));
 
-  ON_CALL(b2, DoB())
-      .WillByDefault(Return(3));
+  ON_CALL(b2, DoB()).WillByDefault(Return(3));
   EXPECT_CALL(b2, DoB(_));
 
   b2.DoB(0);
@@ -2648,8 +2491,7 @@ TEST(VerifyAndClearTest,
   ReferenceHoldingMock test_mock;
 
   // ON_CALL stores a reference to a inside test_mock.
-  ON_CALL(test_mock, AcceptReference(_))
-      .WillByDefault(SetArgPointee<0>(a));
+  ON_CALL(test_mock, AcceptReference(_)).WillByDefault(SetArgPointee<0>(a));
 
   // Throw away the reference to the mock that we have in a. After this, the
   // only reference to it is stored by test_mock.
@@ -2670,9 +2512,8 @@ TEST(VerifyAndClearTest,
 TEST(SynchronizationTest, CanCallMockMethodInAction) {
   MockA a;
   MockC c;
-  ON_CALL(a, DoA(_))
-      .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c,
-                                                    &MockC::NonVoidMethod)));
+  ON_CALL(a, DoA(_)).WillByDefault(
+      IgnoreResult(InvokeWithoutArgs(&c, &MockC::NonVoidMethod)));
   EXPECT_CALL(a, DoA(1));
   EXPECT_CALL(a, DoA(1))
       .WillOnce(Invoke(&a, &MockA::DoA))
@@ -2756,20 +2597,21 @@ TEST(ParameterlessExpectationsTest,
 }
 
 }  // namespace
+}  // namespace testing
 
 // Allows the user to define their own main and then invoke gmock_main
 // from it. This might be necessary on some platforms which require
 // specific setup and teardown.
 #if GMOCK_RENAME_MAIN
-int gmock_main(int argc, char **argv) {
+int gmock_main(int argc, char** argv) {
 #else
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
 #endif  // GMOCK_RENAME_MAIN
   testing::InitGoogleMock(&argc, argv);
   // Ensures that the tests pass no matter what value of
   // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
-  testing::GMOCK_FLAG(catch_leaked_mocks) = true;
-  testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity;
+  GMOCK_FLAG_SET(catch_leaked_mocks, true);
+  GMOCK_FLAG_SET(verbose, testing::internal::kWarningVerbosity);
 
   return RUN_ALL_TESTS();
 }
index fffbb8b66f09f966425ceac3f3a515672c69d9b6..6db0086bb724406d446e1b09983f477041165d28 100644 (file)
 #include "test/gmock-actions_test.cc"
 #include "test/gmock-cardinalities_test.cc"
 #include "test/gmock-internal-utils_test.cc"
-#include "test/gmock-matchers_test.cc"
+#include "test/gmock-matchers-arithmetic_test.cc"
+#include "test/gmock-matchers-comparisons_test.cc"
+#include "test/gmock-matchers-containers_test.cc"
+#include "test/gmock-matchers-misc_test.cc"
 #include "test/gmock-more-actions_test.cc"
 #include "test/gmock-nice-strict_test.cc"
 #include "test/gmock-port_test.cc"
index 72eb43f74ef4b8f5e9e4e3b199abe4657bec13fd..44e5e35f66a9b3fc165be147cc9e3b55c36f640e 100644 (file)
@@ -27,7 +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.
 
-
 // Tests Google Mock's functionality that depends on exceptions.
 
 #include "gmock/gmock.h"
@@ -75,6 +74,5 @@ TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) {
   }
 }
 
-
 }  // unnamed namespace
 #endif
index 7e4b1eea9ae89107cd861352850e9abad94a14a4..4f41c7bbd0e9ce202840ca6ee39ae5b7ba5821d0 100755 (executable)
@@ -31,7 +31,7 @@
 
 """Tests that leaked mock objects can be caught be Google Mock."""
 
-import gmock_test_utils
+from googlemock.test import gmock_test_utils
 
 PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_leak_test_')
 TEST_WITH_EXPECT_CALL = [PROGRAM_PATH, '--gtest_filter=*ExpectCall*']
index 2e095abcf49689dfd8bbbaa22b42f301471e3b4f..fa645916f89c8276a016d707bb260a6675f98d8b 100644 (file)
@@ -27,7 +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.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This program is for verifying that a leaked mock object can be
@@ -52,7 +51,8 @@ class MockFoo : public FooInterface {
   MOCK_METHOD0(DoThis, void());
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
+  MockFoo(const MockFoo&) = delete;
+  MockFoo& operator=(const MockFoo&) = delete;
 };
 
 TEST(LeakTest, LeakedMockWithExpectCallCausesFailureWhenLeakCheckingIsEnabled) {
index d27ce176887bf8b2879bcbf2ad597c28fca4d1de..cd3d6908876129c79c0bbe795f8f634821198df3 100644 (file)
@@ -27,7 +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.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file is for verifying that various Google Mock constructs do not
index e7c54cc230683de2d5688b00f251cb5c9fda116d..f51e3988df3a3bc54c53609d4ef6717a40a8ed5a 100644 (file)
@@ -27,7 +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.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file is for verifying that various Google Mock constructs do not
index 5734b2e11c853647e0363638b7d550e9bfc8ad06..eaf18e9d8c6355031e062bf9845b7d64cb4de33b 100644 (file)
@@ -27,7 +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.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file tests that:
 #include "gmock/gmock.h"
 
 #if !GTEST_OS_WINDOWS_MOBILE
-# include <errno.h>
+#include <errno.h>
 #endif
 
 #include <iostream>
@@ -200,14 +199,14 @@ class Interface {
   virtual char* StringFromString(char* str) = 0;
   virtual int IntFromString(char* str) = 0;
   virtual int& IntRefFromString(char* str) = 0;
-  virtual void VoidFromFunc(void(*func)(char* str)) = 0;
+  virtual void VoidFromFunc(void (*func)(char* str)) = 0;
   virtual void VoidFromIntRef(int& n) = 0;  // NOLINT
   virtual void VoidFromFloat(float n) = 0;
   virtual void VoidFromDouble(double n) = 0;
   virtual void VoidFromVector(const std::vector<int>& v) = 0;
 };
 
-class Mock: public Interface {
+class Mock : public Interface {
  public:
   Mock() {}
 
@@ -215,14 +214,15 @@ class Mock: public Interface {
   MOCK_METHOD1(StringFromString, char*(char* str));
   MOCK_METHOD1(IntFromString, int(char* str));
   MOCK_METHOD1(IntRefFromString, int&(char* str));
-  MOCK_METHOD1(VoidFromFunc, void(void(*func)(char* str)));
+  MOCK_METHOD1(VoidFromFunc, void(void (*func)(char* str)));
   MOCK_METHOD1(VoidFromIntRef, void(int& n));  // NOLINT
   MOCK_METHOD1(VoidFromFloat, void(float n));
   MOCK_METHOD1(VoidFromDouble, void(double n));
   MOCK_METHOD1(VoidFromVector, void(const std::vector<int>& v));
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(Mock);
+  Mock(const Mock&) = delete;
+  Mock& operator=(const Mock&) = delete;
 };
 
 class InvokeHelper {
@@ -301,8 +301,8 @@ TEST(LinkTest, TestSetArrayArgument) {
   char ch = 'x';
   char ch2 = 'y';
 
-  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(SetArrayArgument<0>(&ch2,
-                                                                    &ch2 + 1));
+  EXPECT_CALL(mock, VoidFromString(_))
+      .WillOnce(SetArrayArgument<0>(&ch2, &ch2 + 1));
   mock.VoidFromString(&ch);
 }
 
@@ -339,8 +339,8 @@ TEST(LinkTest, TestInvokeWithoutArgs) {
 
   EXPECT_CALL(mock, VoidFromString(_))
       .WillOnce(InvokeWithoutArgs(&InvokeHelper::StaticVoidFromVoid))
-      .WillOnce(InvokeWithoutArgs(&test_invoke_helper,
-                                  &InvokeHelper::VoidFromVoid));
+      .WillOnce(
+          InvokeWithoutArgs(&test_invoke_helper, &InvokeHelper::VoidFromVoid));
   mock.VoidFromString(nullptr);
   mock.VoidFromString(nullptr);
 }
@@ -424,14 +424,14 @@ TEST(LinkTest, TestThrow) {
 // is expanded and macro expansion cannot contain #pragma.  Therefore
 // we suppress them here.
 #ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
+#pragma warning(push)
+#pragma warning(disable : 4100)
 #endif
 
 // Tests the linkage of actions created using ACTION macro.
 namespace {
 ACTION(Return1) { return 1; }
-}
+}  // namespace
 
 TEST(LinkTest, TestActionMacro) {
   Mock mock;
@@ -443,7 +443,7 @@ TEST(LinkTest, TestActionMacro) {
 // Tests the linkage of actions created using ACTION_P macro.
 namespace {
 ACTION_P(ReturnArgument, ret_value) { return ret_value; }
-}
+}  // namespace
 
 TEST(LinkTest, TestActionPMacro) {
   Mock mock;
@@ -457,10 +457,10 @@ namespace {
 ACTION_P2(ReturnEqualsEitherOf, first, second) {
   return arg0 == first || arg0 == second;
 }
-}
+}  // namespace
 
 #ifdef _MSC_VER
-# pragma warning(pop)
+#pragma warning(pop)
 #endif
 
 TEST(LinkTest, TestActionP2Macro) {
@@ -492,8 +492,7 @@ TEST(LinkTest, TestMatchersEq) {
   const char* p = "x";
 
   ON_CALL(mock, VoidFromString(Eq(p))).WillByDefault(Return());
-  ON_CALL(mock, VoidFromString(const_cast<char*>("y")))
-      .WillByDefault(Return());
+  ON_CALL(mock, VoidFromString(const_cast<char*>("y"))).WillByDefault(Return());
 }
 
 // Tests the linkage of the Lt, Gt, Le, Ge, and Ne matchers.
@@ -592,7 +591,7 @@ TEST(LinkTest, TestMatcherElementsAre) {
 // Tests the linkage of the ElementsAreArray matcher.
 TEST(LinkTest, TestMatcherElementsAreArray) {
   Mock mock;
-  char arr[] = { 'a', 'b' };
+  char arr[] = {'a', 'b'};
 
   ON_CALL(mock, VoidFromVector(ElementsAreArray(arr))).WillByDefault(Return());
 }
index 25f99f2b7977dfe060c27ea9cf6598e36536915b..6b4ab9015d0d7fc45dfadf9c9793f44d65659519 100755 (executable)
@@ -43,7 +43,7 @@ from io import open    # pylint: disable=redefined-builtin, g-importing-member
 import os
 import re
 import sys
-import gmock_test_utils
+from googlemock.test import gmock_test_utils
 
 
 # The flag for generating the golden file
@@ -161,13 +161,13 @@ class GMockOutputTest(gmock_test_utils.TestCase):
     golden_file.close()
 
     # The normalized output should match the golden file.
-    self.assertEquals(golden, output)
+    self.assertEqual(golden, output)
 
     # The raw output should contain 2 leaked mock object errors for
     # test GMockOutputTest.CatchesLeakedMocks.
-    self.assertEquals(['GMockOutputTest.CatchesLeakedMocks',
-                       'GMockOutputTest.CatchesLeakedMocks'],
-                      leaky_tests)
+    self.assertEqual(['GMockOutputTest.CatchesLeakedMocks',
+                      'GMockOutputTest.CatchesLeakedMocks'],
+                     leaky_tests)
 
 
 if __name__ == '__main__':
index 3955c7331a1233b60cb4f22e6f3a264472684d2f..a178691591bc1ef8117ee81a5d418d539f48df20 100644 (file)
 // (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 Mock's output in various scenarios.  This ensures that
 // Google Mock's messages are readable and useful.
 
-#include "gmock/gmock.h"
-
 #include <stdio.h>
+
 #include <string>
 
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 // Silence C4100 (unreferenced formal parameter)
 #ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
+#pragma warning(push)
+#pragma warning(disable : 4100)
 #endif
 
 using testing::_;
@@ -63,7 +62,8 @@ class MockFoo {
   MOCK_METHOD2(Bar3, void(int x, int y));
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
+  MockFoo(const MockFoo&) = delete;
+  MockFoo& operator=(const MockFoo&) = delete;
 };
 
 class GMockOutputTest : public testing::Test {
@@ -72,27 +72,25 @@ class GMockOutputTest : public testing::Test {
 };
 
 TEST_F(GMockOutputTest, ExpectedCall) {
-  testing::GMOCK_FLAG(verbose) = "info";
+  GMOCK_FLAG_SET(verbose, "info");
 
   EXPECT_CALL(foo_, Bar2(0, _));
   foo_.Bar2(0, 0);  // Expected call
 
-  testing::GMOCK_FLAG(verbose) = "warning";
+  GMOCK_FLAG_SET(verbose, "warning");
 }
 
 TEST_F(GMockOutputTest, ExpectedCallToVoidFunction) {
-  testing::GMOCK_FLAG(verbose) = "info";
+  GMOCK_FLAG_SET(verbose, "info");
 
   EXPECT_CALL(foo_, Bar3(0, _));
   foo_.Bar3(0, 0);  // Expected call
 
-  testing::GMOCK_FLAG(verbose) = "warning";
+  GMOCK_FLAG_SET(verbose, "warning");
 }
 
 TEST_F(GMockOutputTest, ExplicitActionsRunOut) {
-  EXPECT_CALL(foo_, Bar2(_, _))
-      .Times(2)
-      .WillOnce(Return(false));
+  EXPECT_CALL(foo_, Bar2(_, _)).Times(2).WillOnce(Return(false));
   foo_.Bar2(2, 2);
   foo_.Bar2(1, 1);  // Explicit actions in EXPECT_CALL run out.
 }
@@ -134,8 +132,7 @@ TEST_F(GMockOutputTest, UninterestingCallToVoidFunction) {
 }
 
 TEST_F(GMockOutputTest, RetiredExpectation) {
-  EXPECT_CALL(foo_, Bar2(_, _))
-      .RetiresOnSaturation();
+  EXPECT_CALL(foo_, Bar2(_, _)).RetiresOnSaturation();
   EXPECT_CALL(foo_, Bar2(0, 0));
 
   foo_.Bar2(1, 1);
@@ -160,12 +157,9 @@ TEST_F(GMockOutputTest, UnsatisfiedPrerequisite) {
 TEST_F(GMockOutputTest, UnsatisfiedPrerequisites) {
   Sequence s1, s2;
 
-  EXPECT_CALL(foo_, Bar(_, 0, _))
-      .InSequence(s1);
-  EXPECT_CALL(foo_, Bar2(0, 0))
-      .InSequence(s2);
-  EXPECT_CALL(foo_, Bar2(1, _))
-      .InSequence(s1, s2);
+  EXPECT_CALL(foo_, Bar(_, 0, _)).InSequence(s1);
+  EXPECT_CALL(foo_, Bar2(0, 0)).InSequence(s2);
+  EXPECT_CALL(foo_, Bar2(1, _)).InSequence(s1, s2);
 
   foo_.Bar2(1, 0);  // Has two immediate unsatisfied pre-requisites
   foo_.Bar("Hi", 0, 0);
@@ -179,8 +173,7 @@ TEST_F(GMockOutputTest, UnsatisfiedWith) {
 
 TEST_F(GMockOutputTest, UnsatisfiedExpectation) {
   EXPECT_CALL(foo_, Bar(_, _, _));
-  EXPECT_CALL(foo_, Bar2(0, _))
-      .Times(2);
+  EXPECT_CALL(foo_, Bar2(0, _)).Times(2);
 
   foo_.Bar2(0, 1);
 }
@@ -194,26 +187,22 @@ TEST_F(GMockOutputTest, MismatchArguments) {
 }
 
 TEST_F(GMockOutputTest, MismatchWith) {
-  EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))
-      .With(Ge());
+  EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))).With(Ge());
 
   foo_.Bar2(2, 3);  // Mismatch With()
   foo_.Bar2(2, 1);
 }
 
 TEST_F(GMockOutputTest, MismatchArgumentsAndWith) {
-  EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))
-      .With(Ge());
+  EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))).With(Ge());
 
   foo_.Bar2(1, 3);  // Mismatch arguments and mismatch With()
   foo_.Bar2(2, 1);
 }
 
 TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) {
-  ON_CALL(foo_, Bar2(_, _))
-      .WillByDefault(Return(true));   // Default action #1
-  ON_CALL(foo_, Bar2(1, _))
-      .WillByDefault(Return(false));  // Default action #2
+  ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true));   // Default action #1
+  ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false));  // Default action #2
 
   EXPECT_CALL(foo_, Bar2(2, 2));
   foo_.Bar2(1, 0);  // Unexpected call, takes default action #2.
@@ -222,10 +211,8 @@ TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) {
 }
 
 TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) {
-  ON_CALL(foo_, Bar2(_, _))
-      .WillByDefault(Return(true));   // Default action #1
-  ON_CALL(foo_, Bar2(1, _))
-      .WillByDefault(Return(false));  // Default action #2
+  ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true));   // Default action #1
+  ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false));  // Default action #2
 
   EXPECT_CALL(foo_, Bar2(2, 2));
   EXPECT_CALL(foo_, Bar2(1, 1));
@@ -237,22 +224,17 @@ TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) {
 }
 
 TEST_F(GMockOutputTest, UninterestingCallWithDefaultAction) {
-  ON_CALL(foo_, Bar2(_, _))
-      .WillByDefault(Return(true));   // Default action #1
-  ON_CALL(foo_, Bar2(1, _))
-      .WillByDefault(Return(false));  // Default action #2
+  ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true));   // Default action #1
+  ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false));  // Default action #2
 
   foo_.Bar2(2, 2);  // Uninteresting call, takes default action #1.
   foo_.Bar2(1, 1);  // Uninteresting call, takes default action #2.
 }
 
 TEST_F(GMockOutputTest, ExplicitActionsRunOutWithDefaultAction) {
-  ON_CALL(foo_, Bar2(_, _))
-      .WillByDefault(Return(true));   // Default action #1
+  ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true));  // Default action #1
 
-  EXPECT_CALL(foo_, Bar2(_, _))
-      .Times(2)
-      .WillOnce(Return(false));
+  EXPECT_CALL(foo_, Bar2(_, _)).Times(2).WillOnce(Return(false));
   foo_.Bar2(2, 2);
   foo_.Bar2(1, 1);  // Explicit actions in EXPECT_CALL run out.
 }
@@ -293,17 +275,17 @@ void TestCatchesLeakedMocksInAdHocTests() {
   // foo is deliberately leaked.
 }
 
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
   testing::InitGoogleMock(&argc, argv);
   // Ensures that the tests pass no matter what value of
   // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
-  testing::GMOCK_FLAG(catch_leaked_mocks) = true;
-  testing::GMOCK_FLAG(verbose) = "warning";
+  GMOCK_FLAG_SET(catch_leaked_mocks, true);
+  GMOCK_FLAG_SET(verbose, "warning");
 
   TestCatchesLeakedMocksInAdHocTests();
   return RUN_ALL_TESTS();
 }
 
 #ifdef _MSC_VER
-# pragma warning(pop)
+#pragma warning(pop)
 #endif
index 4846c12430771e403030e43577051ca289b265f5..fdf224fd0a704a22575268d940eba657474c20cb 100644 (file)
@@ -291,7 +291,7 @@ Stack trace:
 [ RUN      ] GMockOutputTest.PrintsMatcher
 FILE:#: Failure
 Value of: (std::pair<int, bool>(42, true))
-Expected: is pair (is >= 48, true)
+Expected: is pair (first: is >= 48, second: true)
   Actual: (42, true) (of type std::pair<int, bool>)
 [  FAILED  ] GMockOutputTest.PrintsMatcher
 [  FAILED  ] GMockOutputTest.UnexpectedCall
index 20725d69b7bf76fab1f8d91f59ff8d024588cae3..9e42cd935847c76914abf2ebd36f6e696ffc72b6 100644 (file)
@@ -27,7 +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.
 
-
 // Tests that Google Mock constructs can be used in a large number of
 // threads concurrently.
 
@@ -49,7 +48,7 @@ const int kRepeat = 50;
 
 class MockFoo {
  public:
-  MOCK_METHOD1(Bar, int(int n));  // NOLINT
+  MOCK_METHOD1(Bar, int(int n));                                   // NOLINT
   MOCK_METHOD2(Baz, char(const char* s1, const std::string& s2));  // NOLINT
 };
 
@@ -62,21 +61,16 @@ void JoinAndDelete(ThreadWithParam<T>* t) {
 
 struct Dummy {};
 
-
 // Tests that different mock objects can be used in their respective
 // threads.  This should generate no Google Test failure.
 void TestConcurrentMockObjects(Dummy /* dummy */) {
   // Creates a mock and does some typical operations on it.
   MockFoo foo;
-  ON_CALL(foo, Bar(_))
-      .WillByDefault(Return(1));
-  ON_CALL(foo, Baz(_, _))
-      .WillByDefault(Return('b'));
-  ON_CALL(foo, Baz(_, "you"))
-      .WillByDefault(Return('a'));
-
-  EXPECT_CALL(foo, Bar(0))
-      .Times(AtMost(3));
+  ON_CALL(foo, Bar(_)).WillByDefault(Return(1));
+  ON_CALL(foo, Baz(_, _)).WillByDefault(Return('b'));
+  ON_CALL(foo, Baz(_, "you")).WillByDefault(Return('a'));
+
+  EXPECT_CALL(foo, Bar(0)).Times(AtMost(3));
   EXPECT_CALL(foo, Baz(_, _));
   EXPECT_CALL(foo, Baz("hi", "you"))
       .WillOnce(Return('z'))
@@ -119,22 +113,19 @@ void Helper1(Helper1Param param) {
 void TestConcurrentCallsOnSameObject(Dummy /* dummy */) {
   MockFoo foo;
 
-  ON_CALL(foo, Bar(_))
-      .WillByDefault(Return(1));
-  EXPECT_CALL(foo, Baz(_, "b"))
-      .Times(kRepeat)
-      .WillRepeatedly(Return('a'));
+  ON_CALL(foo, Bar(_)).WillByDefault(Return(1));
+  EXPECT_CALL(foo, Baz(_, "b")).Times(kRepeat).WillRepeatedly(Return('a'));
   EXPECT_CALL(foo, Baz(_, "c"));  // Expected to be unsatisfied.
 
   // This chunk of code should generate kRepeat failures about
   // excessive calls, and 2*kRepeat failures about unexpected calls.
   int count1 = 0;
-  const Helper1Param param = { &foo, &count1 };
+  const Helper1Param param = {&foo, &count1};
   ThreadWithParam<Helper1Param>* const t =
       new ThreadWithParam<Helper1Param>(Helper1, param, nullptr);
 
   int count2 = 0;
-  const Helper1Param param2 = { &foo, &count2 };
+  const Helper1Param param2 = {&foo, &count2};
   Helper1(param2);
   JoinAndDelete(t);
 
@@ -162,22 +153,18 @@ void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) {
   {
     InSequence dummy;
     EXPECT_CALL(foo, Bar(0));
-    EXPECT_CALL(foo, Bar(1))
-        .InSequence(s1, s2);
+    EXPECT_CALL(foo, Bar(1)).InSequence(s1, s2);
   }
 
   EXPECT_CALL(foo, Bar(2))
-      .Times(2*kRepeat)
+      .Times(2 * kRepeat)
       .InSequence(s1)
       .RetiresOnSaturation();
-  EXPECT_CALL(foo, Bar(3))
-      .Times(2*kRepeat)
-      .InSequence(s2);
+  EXPECT_CALL(foo, Bar(3)).Times(2 * kRepeat).InSequence(s2);
 
   {
     InSequence dummy;
-    EXPECT_CALL(foo, Bar(2))
-        .InSequence(s1, s2);
+    EXPECT_CALL(foo, Bar(2)).InSequence(s1, s2);
     EXPECT_CALL(foo, Bar(4));
   }
 
@@ -196,12 +183,12 @@ void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) {
 // Tests using Google Mock constructs in many threads concurrently.
 TEST(StressTest, CanUseGMockWithThreads) {
   void (*test_routines[])(Dummy dummy) = {
-    &TestConcurrentMockObjects,
-    &TestConcurrentCallsOnSameObject,
-    &TestPartiallyOrderedExpectationsWithThreads,
+      &TestConcurrentMockObjects,
+      &TestConcurrentCallsOnSameObject,
+      &TestPartiallyOrderedExpectationsWithThreads,
   };
 
-  const int kRoutines = sizeof(test_routines)/sizeof(test_routines[0]);
+  const int kRoutines = sizeof(test_routines) / sizeof(test_routines[0]);
   const int kCopiesOfEachRoutine = kMaxTestThreads / kRoutines;
   const int kTestThreads = kCopiesOfEachRoutine * kRoutines;
   ThreadWithParam<Dummy>* threads[kTestThreads] = {};
@@ -220,7 +207,7 @@ TEST(StressTest, CanUseGMockWithThreads) {
   // Ensures that the correct number of failures have been reported.
   const TestInfo* const info = UnitTest::GetInstance()->current_test_info();
   const TestResult& result = *info->result();
-  const int kExpectedFailures = (3*kRepeat + 1)*kCopiesOfEachRoutine;
+  const int kExpectedFailures = (3 * kRepeat + 1) * kCopiesOfEachRoutine;
   GTEST_CHECK_(kExpectedFailures == result.total_part_count())
       << "Expected " << kExpectedFailures << " failures, but got "
       << result.total_part_count();
@@ -229,7 +216,7 @@ TEST(StressTest, CanUseGMockWithThreads) {
 }  // namespace
 }  // namespace testing
 
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
   testing::InitGoogleMock(&argc, argv);
 
   const int exit_code = RUN_ALL_TESTS();  // Expected to fail.
index e9840a337db87d13052f5f416bbc48a1845f1aa8..8f1bd5d03eb89b8149cf574a95d52cd0e25bac3d 100644 (file)
@@ -27,7 +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.
 
-
 // Google Mock - a framework for writing C++ mock classes.
 //
 // This file tests code in gmock.cc.
 #include "gmock/gmock.h"
 
 #include <string>
+
 #include "gtest/gtest.h"
 #include "gtest/internal/custom/gtest.h"
 
 #if !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
 
-using testing::GMOCK_FLAG(default_mock_behavior);
-using testing::GMOCK_FLAG(verbose);
 using testing::InitGoogleMock;
 
 // Verifies that calling InitGoogleMock() on argv results in new_argv,
@@ -49,7 +47,7 @@ using testing::InitGoogleMock;
 template <typename Char, int M, int N>
 void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N],
                         const ::std::string& expected_gmock_verbose) {
-  const ::std::string old_verbose = GMOCK_FLAG(verbose);
+  const ::std::string old_verbose = GMOCK_FLAG_GET(verbose);
 
   int argc = M - 1;
   InitGoogleMock(&argc, const_cast<Char**>(argv));
@@ -59,8 +57,8 @@ void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N],
     EXPECT_STREQ(new_argv[i], argv[i]);
   }
 
-  EXPECT_EQ(expected_gmock_verbose, GMOCK_FLAG(verbose).c_str());
-  GMOCK_FLAG(verbose) = old_verbose;  // Restores the gmock_verbose flag.
+  EXPECT_EQ(expected_gmock_verbose, GMOCK_FLAG_GET(verbose));
+  GMOCK_FLAG_SET(verbose, old_verbose);  // Restores the gmock_verbose flag.
 }
 
 TEST(InitGoogleMockTest, ParsesInvalidCommandLine) {
@@ -68,7 +66,7 @@ TEST(InitGoogleMockTest, ParsesInvalidCommandLine) {
 
   const char* new_argv[] = {nullptr};
 
-  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
+  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));
 }
 
 TEST(InitGoogleMockTest, ParsesEmptyCommandLine) {
@@ -76,7 +74,7 @@ TEST(InitGoogleMockTest, ParsesEmptyCommandLine) {
 
   const char* new_argv[] = {"foo.exe", nullptr};
 
-  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
+  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));
 }
 
 TEST(InitGoogleMockTest, ParsesSingleFlag) {
@@ -88,16 +86,16 @@ TEST(InitGoogleMockTest, ParsesSingleFlag) {
 }
 
 TEST(InitGoogleMockTest, ParsesMultipleFlags) {
-  int old_default_behavior = GMOCK_FLAG(default_mock_behavior);
+  int old_default_behavior = GMOCK_FLAG_GET(default_mock_behavior);
   const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info",
                            L"--gmock_default_mock_behavior=2", nullptr};
 
   const wchar_t* new_argv[] = {L"foo.exe", nullptr};
 
   TestInitGoogleMock(argv, new_argv, "info");
-  EXPECT_EQ(2, GMOCK_FLAG(default_mock_behavior));
+  EXPECT_EQ(2, GMOCK_FLAG_GET(default_mock_behavior));
   EXPECT_NE(2, old_default_behavior);
-  GMOCK_FLAG(default_mock_behavior) = old_default_behavior;
+  GMOCK_FLAG_SET(default_mock_behavior, old_default_behavior);
 }
 
 TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) {
@@ -105,7 +103,7 @@ TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) {
 
   const char* new_argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr};
 
-  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
+  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));
 }
 
 TEST(InitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
@@ -122,7 +120,7 @@ TEST(WideInitGoogleMockTest, ParsesInvalidCommandLine) {
 
   const wchar_t* new_argv[] = {nullptr};
 
-  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
+  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));
 }
 
 TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) {
@@ -130,7 +128,7 @@ TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) {
 
   const wchar_t* new_argv[] = {L"foo.exe", nullptr};
 
-  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
+  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));
 }
 
 TEST(WideInitGoogleMockTest, ParsesSingleFlag) {
@@ -142,16 +140,16 @@ TEST(WideInitGoogleMockTest, ParsesSingleFlag) {
 }
 
 TEST(WideInitGoogleMockTest, ParsesMultipleFlags) {
-  int old_default_behavior = GMOCK_FLAG(default_mock_behavior);
+  int old_default_behavior = GMOCK_FLAG_GET(default_mock_behavior);
   const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info",
                            L"--gmock_default_mock_behavior=2", nullptr};
 
   const wchar_t* new_argv[] = {L"foo.exe", nullptr};
 
   TestInitGoogleMock(argv, new_argv, "info");
-  EXPECT_EQ(2, GMOCK_FLAG(default_mock_behavior));
+  EXPECT_EQ(2, GMOCK_FLAG_GET(default_mock_behavior));
   EXPECT_NE(2, old_default_behavior);
-  GMOCK_FLAG(default_mock_behavior) = old_default_behavior;
+  GMOCK_FLAG_SET(default_mock_behavior, old_default_behavior);
 }
 
 TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) {
@@ -159,7 +157,7 @@ TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) {
 
   const wchar_t* new_argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr};
 
-  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose));
+  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));
 }
 
 TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
@@ -175,7 +173,7 @@ TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
 
 // Makes sure Google Mock flags can be accessed in code.
 TEST(FlagTest, IsAccessibleInCode) {
-  bool dummy = testing::GMOCK_FLAG(catch_leaked_mocks) &&
-      testing::GMOCK_FLAG(verbose) == "";
+  bool dummy =
+      GMOCK_FLAG_GET(catch_leaked_mocks) && GMOCK_FLAG_GET(verbose) == "";
   (void)dummy;  // Avoids the "unused local variable" warning.
 }
index 7dc4e119d3c5b97c3815e6b0d2602770240cce1d..d7bc0974a7095b706041ba91f5f7d6e27fe89e62 100755 (executable)
 """Unit test utilities for Google C++ Mocking Framework."""
 
 import os
-import sys
-
-# Determines path to gtest_test_utils and imports it.
-SCRIPT_DIR = os.path.dirname(__file__) or '.'
-
-# isdir resolves symbolic links.
-gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../../googletest/test')
-if os.path.isdir(gtest_tests_util_dir):
-  GTEST_TESTS_UTIL_DIR = gtest_tests_util_dir
-else:
-  GTEST_TESTS_UTIL_DIR = os.path.join(SCRIPT_DIR, '../../googletest/test')
-sys.path.append(GTEST_TESTS_UTIL_DIR)
 
 # pylint: disable=C6204
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 
 def GetSourceDir():
index abdd98b79a40b697c7207b63b304ed17fde7e66a..aa00a5f3d27f1b603ac395169eca96165e6170f1 100644 (file)
@@ -46,14 +46,9 @@ endif()
 
 # Project version:
 
-if (CMAKE_VERSION VERSION_LESS 3.0)
-  project(gtest CXX C)
-  set(PROJECT_VERSION ${GOOGLETEST_VERSION})
-else()
-  cmake_policy(SET CMP0048 NEW)
-  project(gtest VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
-endif()
-cmake_minimum_required(VERSION 2.8.12)
+cmake_minimum_required(VERSION 3.5)
+cmake_policy(SET CMP0048 NEW)
+project(gtest VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
 
 if (POLICY CMP0063) # Visibility
   cmake_policy(SET CMP0063 NEW)
@@ -136,13 +131,17 @@ set_target_properties(gtest_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
 # to the targets for when we are part of a parent build (ie being pulled
 # in via add_subdirectory() rather than being a standalone build).
 if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
+  string(REPLACE ";" "$<SEMICOLON>" dirs "${gtest_build_include_dirs}")
   target_include_directories(gtest SYSTEM INTERFACE
-    "$<BUILD_INTERFACE:${gtest_build_include_dirs}>"
+    "$<BUILD_INTERFACE:${dirs}>"
     "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
   target_include_directories(gtest_main SYSTEM INTERFACE
-    "$<BUILD_INTERFACE:${gtest_build_include_dirs}>"
+    "$<BUILD_INTERFACE:${dirs}>"
     "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
 endif()
+if(CMAKE_SYSTEM_NAME MATCHES "QNX")
+  target_link_libraries(gtest PUBLIC regex)
+endif()
 target_link_libraries(gtest_main PUBLIC gtest)
 
 ########################################################################
index 1f8b349ae70d7235c62e23fcdfa15d7be3451765..d26b309ed0d14c06d96d5cc4efd8bd3bf288cad5 100644 (file)
@@ -25,7 +25,7 @@ When building GoogleTest as a standalone project, the typical workflow starts
 with
 
 ```
-git clone https://github.com/google/googletest.git -b release-1.10.0
+git clone https://github.com/google/googletest.git -b release-1.11.0
 cd googletest        # Main directory of the cloned repository.
 mkdir build          # Create a directory to hold the build output.
 cd build
@@ -94,7 +94,7 @@ include(FetchContent)
 FetchContent_Declare(
   googletest
   # Specify the commit you depend on and update it regularly.
-  URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip
+  URL https://github.com/google/googletest/archive/e2239ee6043f73722e7aa812a459f54a28552929.zip
 )
 # For Windows: Prevent overriding the parent project's compiler/linker settings
 set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
@@ -203,7 +203,9 @@ add
     -DGTEST_DONT_DEFINE_FOO=1
 
 to the compiler flags to tell GoogleTest to change the macro's name from `FOO`
-to `GTEST_FOO`. Currently `FOO` can be `FAIL`, `SUCCEED`, or `TEST`. For
+to `GTEST_FOO`. Currently `FOO` can be `ASSERT_EQ`, `ASSERT_FALSE`, `ASSERT_GE`,
+`ASSERT_GT`, `ASSERT_LE`, `ASSERT_LT`, `ASSERT_NE`, `ASSERT_TRUE`,
+`EXPECT_FALSE`, `EXPECT_TRUE`, `FAIL`, `SUCCEED`, `TEST`, or `TEST_F`. For
 example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write
 
     GTEST_TEST(SomeTest, DoesThis) { ... }
index 8d8d60a86ca6560bb044d313f95b43202b67db08..5a34c07a1b99f8bf9d011e9ada4fabc225f34080 100644 (file)
@@ -84,13 +84,13 @@ macro(config_compiler_and_linker)
     # Ensure MSVC treats source files as UTF-8 encoded.
     set(cxx_base_flags "${cxx_base_flags} -utf-8")
   elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
-    set(cxx_base_flags "-Wall -Wshadow -Werror -Wconversion")
+    set(cxx_base_flags "-Wall -Wshadow -Wconversion")
     set(cxx_exception_flags "-fexceptions")
     set(cxx_no_exception_flags "-fno-exceptions")
     set(cxx_strict_flags "-W -Wpointer-arith -Wreturn-type -Wcast-qual -Wwrite-strings -Wswitch -Wunused-parameter -Wcast-align -Wchar-subscripts -Winline -Wredundant-decls")
     set(cxx_no_rtti_flags "-fno-rtti")
   elseif (CMAKE_COMPILER_IS_GNUCXX)
-    set(cxx_base_flags "-Wall -Wshadow -Werror")
+    set(cxx_base_flags "-Wall -Wshadow")
     if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0.0)
       set(cxx_base_flags "${cxx_base_flags} -Wno-error=dangling-else")
     endif()
@@ -154,10 +154,6 @@ function(cxx_library_with_type name type cxx_flags)
   set_target_properties(${name}
     PROPERTIES
     COMPILE_FLAGS "${cxx_flags}")
-  # Generate debug library name with a postfix.
-  set_target_properties(${name}
-    PROPERTIES
-    DEBUG_POSTFIX "d")
   # Set the output directory for build artifacts
   set_target_properties(${name}
     PROPERTIES
@@ -304,6 +300,8 @@ function(py_test name)
         COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
           --build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN})
     endif()
+    # Make the Python import path consistent between Bazel and CMake.
+    set_tests_properties(${name} PROPERTIES ENVIRONMENT PYTHONPATH=${CMAKE_SOURCE_DIR})
   endif(PYTHONINTERP_FOUND)
 endfunction()
 
diff --git a/googletest/include/gtest/gtest-assertion-result.h b/googletest/include/gtest/gtest-assertion-result.h
new file mode 100644 (file)
index 0000000..addbb59
--- /dev/null
@@ -0,0 +1,237 @@
+// Copyright 2005, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// The Google C++ Testing and Mocking Framework (Google Test)
+//
+// This file implements the AssertionResult type.
+
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
+
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_ASSERTION_RESULT_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_ASSERTION_RESULT_H_
+
+#include <memory>
+#include <ostream>
+#include <string>
+#include <type_traits>
+
+#include "gtest/gtest-message.h"
+#include "gtest/internal/gtest-port.h"
+
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251                                   \
+/* class A needs to have dll-interface to be used by clients of class B */)
+
+namespace testing {
+
+// A class for indicating whether an assertion was successful.  When
+// the assertion wasn't successful, the AssertionResult object
+// remembers a non-empty message that describes how it failed.
+//
+// To create an instance of this class, use one of the factory functions
+// (AssertionSuccess() and AssertionFailure()).
+//
+// This class is useful for two purposes:
+//   1. Defining predicate functions to be used with Boolean test assertions
+//      EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
+//   2. Defining predicate-format functions to be
+//      used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
+//
+// For example, if you define IsEven predicate:
+//
+//   testing::AssertionResult IsEven(int n) {
+//     if ((n % 2) == 0)
+//       return testing::AssertionSuccess();
+//     else
+//       return testing::AssertionFailure() << n << " is odd";
+//   }
+//
+// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
+// will print the message
+//
+//   Value of: IsEven(Fib(5))
+//     Actual: false (5 is odd)
+//   Expected: true
+//
+// instead of a more opaque
+//
+//   Value of: IsEven(Fib(5))
+//     Actual: false
+//   Expected: true
+//
+// in case IsEven is a simple Boolean predicate.
+//
+// If you expect your predicate to be reused and want to support informative
+// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
+// about half as often as positive ones in our tests), supply messages for
+// both success and failure cases:
+//
+//   testing::AssertionResult IsEven(int n) {
+//     if ((n % 2) == 0)
+//       return testing::AssertionSuccess() << n << " is even";
+//     else
+//       return testing::AssertionFailure() << n << " is odd";
+//   }
+//
+// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
+//
+//   Value of: IsEven(Fib(6))
+//     Actual: true (8 is even)
+//   Expected: false
+//
+// NB: Predicates that support negative Boolean assertions have reduced
+// performance in positive ones so be careful not to use them in tests
+// that have lots (tens of thousands) of positive Boolean assertions.
+//
+// To use this class with EXPECT_PRED_FORMAT assertions such as:
+//
+//   // Verifies that Foo() returns an even number.
+//   EXPECT_PRED_FORMAT1(IsEven, Foo());
+//
+// you need to define:
+//
+//   testing::AssertionResult IsEven(const char* expr, int n) {
+//     if ((n % 2) == 0)
+//       return testing::AssertionSuccess();
+//     else
+//       return testing::AssertionFailure()
+//         << "Expected: " << expr << " is even\n  Actual: it's " << n;
+//   }
+//
+// If Foo() returns 5, you will see the following message:
+//
+//   Expected: Foo() is even
+//     Actual: it's 5
+//
+class GTEST_API_ AssertionResult {
+ public:
+  // Copy constructor.
+  // Used in EXPECT_TRUE/FALSE(assertion_result).
+  AssertionResult(const AssertionResult& other);
+
+// C4800 is a level 3 warning in Visual Studio 2015 and earlier.
+// This warning is not emitted in Visual Studio 2017.
+// This warning is off by default starting in Visual Studio 2019 but can be
+// enabled with command-line options.
+#if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
+  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
+#endif
+
+  // Used in the EXPECT_TRUE/FALSE(bool_expression).
+  //
+  // T must be contextually convertible to bool.
+  //
+  // The second parameter prevents this overload from being considered if
+  // the argument is implicitly convertible to AssertionResult. In that case
+  // we want AssertionResult's copy constructor to be used.
+  template <typename T>
+  explicit AssertionResult(
+      const T& success,
+      typename std::enable_if<
+          !std::is_convertible<T, AssertionResult>::value>::type*
+      /*enabler*/
+      = nullptr)
+      : success_(success) {}
+
+#if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
+  GTEST_DISABLE_MSC_WARNINGS_POP_()
+#endif
+
+  // Assignment operator.
+  AssertionResult& operator=(AssertionResult other) {
+    swap(other);
+    return *this;
+  }
+
+  // Returns true if and only if the assertion succeeded.
+  operator bool() const { return success_; }  // NOLINT
+
+  // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
+  AssertionResult operator!() const;
+
+  // Returns the text streamed into this AssertionResult. Test assertions
+  // use it when they fail (i.e., the predicate's outcome doesn't match the
+  // assertion's expectation). When nothing has been streamed into the
+  // object, returns an empty string.
+  const char* message() const {
+    return message_.get() != nullptr ? message_->c_str() : "";
+  }
+  // Deprecated; please use message() instead.
+  const char* failure_message() const { return message(); }
+
+  // Streams a custom failure message into this object.
+  template <typename T>
+  AssertionResult& operator<<(const T& value) {
+    AppendMessage(Message() << value);
+    return *this;
+  }
+
+  // Allows streaming basic output manipulators such as endl or flush into
+  // this object.
+  AssertionResult& operator<<(
+      ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
+    AppendMessage(Message() << basic_manipulator);
+    return *this;
+  }
+
+ private:
+  // Appends the contents of message to message_.
+  void AppendMessage(const Message& a_message) {
+    if (message_.get() == nullptr) message_.reset(new ::std::string);
+    message_->append(a_message.GetString().c_str());
+  }
+
+  // Swap the contents of this AssertionResult with other.
+  void swap(AssertionResult& other);
+
+  // Stores result of the assertion predicate.
+  bool success_;
+  // Stores the message describing the condition in case the expectation
+  // construct is not satisfied with the predicate's outcome.
+  // Referenced via a pointer to avoid taking too much stack frame space
+  // with test assertions.
+  std::unique_ptr< ::std::string> message_;
+};
+
+// Makes a successful assertion result.
+GTEST_API_ AssertionResult AssertionSuccess();
+
+// Makes a failed assertion result.
+GTEST_API_ AssertionResult AssertionFailure();
+
+// Makes a failed assertion result with the given failure message.
+// Deprecated; use AssertionFailure() << msg.
+GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
+
+}  // namespace testing
+
+GTEST_DISABLE_MSC_WARNINGS_POP_()  // 4251
+
+#endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_ASSERTION_RESULT_H_
index 9b4d4d1337481ee11e1c484b8a38ddad9a2259e7..84e5a5bbd372df80f268165a601bc995e907641d 100644 (file)
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-//
 // The Google C++ Testing and Mocking Framework (Google Test)
 //
 // This header file defines the public API for death tests.  It is
 // #included by gtest.h so a user doesn't need to include this
 // directly.
-// GOOGLETEST_CM0001 DO NOT DELETE
+
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
 #define GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
 
 #include "gtest/internal/gtest-death-test-internal.h"
 
-namespace testing {
-
 // This flag controls the style of death tests.  Valid values are "threadsafe",
 // meaning that the death test child process will re-execute the test binary
 // from the start, running only a single death test, or "fast",
@@ -49,6 +49,8 @@ namespace testing {
 // after forking.
 GTEST_DECLARE_string_(death_test_style);
 
+namespace testing {
+
 #if GTEST_HAS_DEATH_TEST
 
 namespace internal {
@@ -103,7 +105,6 @@ GTEST_API_ bool InDeathTestChild();
 //
 // On the regular expressions used in death tests:
 //
-//   GOOGLETEST_CM0005 DO NOT DELETE
 //   On POSIX-compliant systems (*nix), we use the <regex.h> library,
 //   which uses the POSIX extended regex syntax.
 //
@@ -169,24 +170,24 @@ GTEST_API_ bool InDeathTestChild();
 // Asserts that a given `statement` causes the program to exit, with an
 // integer exit status that satisfies `predicate`, and emitting error output
 // that matches `matcher`.
-# define ASSERT_EXIT(statement, predicate, matcher) \
-    GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_)
+#define ASSERT_EXIT(statement, predicate, matcher) \
+  GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_)
 
 // Like `ASSERT_EXIT`, but continues on to successive tests in the
 // test suite, if any:
-# define EXPECT_EXIT(statement, predicate, matcher) \
-    GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_)
+#define EXPECT_EXIT(statement, predicate, matcher) \
+  GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_)
 
 // Asserts that a given `statement` causes the program to exit, either by
 // explicitly exiting with a nonzero exit code or being killed by a
 // signal, and emitting error output that matches `matcher`.
-# define ASSERT_DEATH(statement, matcher) \
-    ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
+#define ASSERT_DEATH(statement, matcher) \
+  ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
 
 // Like `ASSERT_DEATH`, but continues on to successive tests in the
 // test suite, if any:
-# define EXPECT_DEATH(statement, matcher) \
-    EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
+#define EXPECT_DEATH(statement, matcher) \
+  EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
 
 // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
 
@@ -197,22 +198,23 @@ class GTEST_API_ ExitedWithCode {
   ExitedWithCode(const ExitedWithCode&) = default;
   void operator=(const ExitedWithCode& other) = delete;
   bool operator()(int exit_status) const;
+
  private:
   const int exit_code_;
 };
 
-# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
+#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
 // Tests that an exit code describes an exit due to termination by a
 // given signal.
-// GOOGLETEST_CM0006 DO NOT DELETE
 class GTEST_API_ KilledBySignal {
  public:
   explicit KilledBySignal(int signum);
   bool operator()(int exit_status) const;
+
  private:
   const int signum_;
 };
-# endif  // !GTEST_OS_WINDOWS
+#endif  // !GTEST_OS_WINDOWS
 
 // EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.
 // The death testing framework causes this to have interesting semantics,
@@ -257,23 +259,21 @@ class GTEST_API_ KilledBySignal {
 //   EXPECT_EQ(12, DieInDebugOr12(&sideeffect));
 // }, "death");
 //
-# ifdef NDEBUG
+#ifdef NDEBUG
 
-#  define EXPECT_DEBUG_DEATH(statement, regex) \
+#define EXPECT_DEBUG_DEATH(statement, regex) \
   GTEST_EXECUTE_STATEMENT_(statement, regex)
 
-#  define ASSERT_DEBUG_DEATH(statement, regex) \
+#define ASSERT_DEBUG_DEATH(statement, regex) \
   GTEST_EXECUTE_STATEMENT_(statement, regex)
 
-# else
+#else
 
-#  define EXPECT_DEBUG_DEATH(statement, regex) \
-  EXPECT_DEATH(statement, regex)
+#define EXPECT_DEBUG_DEATH(statement, regex) EXPECT_DEATH(statement, regex)
 
-#  define ASSERT_DEBUG_DEATH(statement, regex) \
-  ASSERT_DEATH(statement, regex)
+#define ASSERT_DEBUG_DEATH(statement, regex) ASSERT_DEATH(statement, regex)
 
-# endif  // NDEBUG for EXPECT_DEBUG_DEATH
+#endif  // NDEBUG for EXPECT_DEBUG_DEATH
 #endif  // GTEST_HAS_DEATH_TEST
 
 // This macro is used for implementing macros such as
@@ -311,18 +311,17 @@ class GTEST_API_ KilledBySignal {
 //  statement unconditionally returns or throws. The Message constructor at
 //  the end allows the syntax of streaming additional messages into the
 //  macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
-# define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \
-    GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
-    if (::testing::internal::AlwaysTrue()) { \
-      GTEST_LOG_(WARNING) \
-          << "Death tests are not supported on this platform.\n" \
-          << "Statement '" #statement "' cannot be verified."; \
-    } else if (::testing::internal::AlwaysFalse()) { \
-      ::testing::internal::RE::PartialMatch(".*", (regex)); \
-      GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
-      terminator; \
-    } else \
-      ::testing::Message()
+#define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator)             \
+  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                                \
+  if (::testing::internal::AlwaysTrue()) {                                     \
+    GTEST_LOG_(WARNING) << "Death tests are not supported on this platform.\n" \
+                        << "Statement '" #statement "' cannot be verified.";   \
+  } else if (::testing::internal::AlwaysFalse()) {                             \
+    ::testing::internal::RE::PartialMatch(".*", (regex));                      \
+    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement);                 \
+    terminator;                                                                \
+  } else                                                                       \
+    ::testing::Message()
 
 // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and
 // ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if
@@ -330,15 +329,15 @@ class GTEST_API_ KilledBySignal {
 // useful when you are combining death test assertions with normal test
 // assertions in one test.
 #if GTEST_HAS_DEATH_TEST
-# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
-    EXPECT_DEATH(statement, regex)
-# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
-    ASSERT_DEATH(statement, regex)
+#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
+  EXPECT_DEATH(statement, regex)
+#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
+  ASSERT_DEATH(statement, regex)
 #else
-# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
-    GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, )
-# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
-    GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return)
+#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
+  GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, )
+#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
+  GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return)
 #endif
 
 }  // namespace testing
index 9fa34a05ba418ee8450d7d57b3ca88757e621492..bffa00c5338c2be1fece5754f698b5ea24a3aa4d 100644 (file)
 // This file implements just enough of the matcher interface to allow
 // EXPECT_DEATH and friends to accept a matcher argument.
 
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
+
 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
 #define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
 
@@ -98,11 +102,11 @@ class MatchResultListener {
  private:
   ::std::ostream* const stream_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
+  MatchResultListener(const MatchResultListener&) = delete;
+  MatchResultListener& operator=(const MatchResultListener&) = delete;
 };
 
-inline MatchResultListener::~MatchResultListener() {
-}
+inline MatchResultListener::~MatchResultListener() {}
 
 // An instance of a subclass of this knows how to describe itself as a
 // matcher.
@@ -176,27 +180,39 @@ namespace internal {
 
 struct AnyEq {
   template <typename A, typename B>
-  bool operator()(const A& a, const B& b) const { return a == b; }
+  bool operator()(const A& a, const B& b) const {
+    return a == b;
+  }
 };
 struct AnyNe {
   template <typename A, typename B>
-  bool operator()(const A& a, const B& b) const { return a != b; }
+  bool operator()(const A& a, const B& b) const {
+    return a != b;
+  }
 };
 struct AnyLt {
   template <typename A, typename B>
-  bool operator()(const A& a, const B& b) const { return a < b; }
+  bool operator()(const A& a, const B& b) const {
+    return a < b;
+  }
 };
 struct AnyGt {
   template <typename A, typename B>
-  bool operator()(const A& a, const B& b) const { return a > b; }
+  bool operator()(const A& a, const B& b) const {
+    return a > b;
+  }
 };
 struct AnyLe {
   template <typename A, typename B>
-  bool operator()(const A& a, const B& b) const { return a <= b; }
+  bool operator()(const A& a, const B& b) const {
+    return a <= b;
+  }
 };
 struct AnyGe {
   template <typename A, typename B>
-  bool operator()(const A& a, const B& b) const { return a >= b; }
+  bool operator()(const A& a, const B& b) const {
+    return a >= b;
+  }
 };
 
 // A match result listener that ignores the explanation.
@@ -205,7 +221,8 @@ class DummyMatchResultListener : public MatchResultListener {
   DummyMatchResultListener() : MatchResultListener(nullptr) {}
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
+  DummyMatchResultListener(const DummyMatchResultListener&) = delete;
+  DummyMatchResultListener& operator=(const DummyMatchResultListener&) = delete;
 };
 
 // A match result listener that forwards the explanation to a given
@@ -217,7 +234,9 @@ class StreamMatchResultListener : public MatchResultListener {
       : MatchResultListener(os) {}
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
+  StreamMatchResultListener(const StreamMatchResultListener&) = delete;
+  StreamMatchResultListener& operator=(const StreamMatchResultListener&) =
+      delete;
 };
 
 struct SharedPayloadBase {
@@ -284,17 +303,18 @@ class MatcherBase : private MatcherDescriberInterface {
   }
 
  protected:
-  MatcherBase() : vtable_(nullptr) {}
+  MatcherBase() : vtable_(nullptr), buffer_() {}
 
   // Constructs a matcher from its implementation.
   template <typename U>
-  explicit MatcherBase(const MatcherInterface<U>* impl) {
+  explicit MatcherBase(const MatcherInterface<U>* impl)
+      : vtable_(nullptr), buffer_() {
     Init(impl);
   }
 
   template <typename M, typename = typename std::remove_reference<
                             M>::type::is_gtest_matcher>
-  MatcherBase(M&& m) {  // NOLINT
+  MatcherBase(M&& m) : vtable_(nullptr), buffer_() {  // NOLINT
     Init(std::forward<M>(m));
   }
 
@@ -420,8 +440,8 @@ class MatcherBase : private MatcherDescriberInterface {
     static const M& Get(const MatcherBase& m) {
       // When inlined along with Init, need to be explicit to avoid violating
       // strict aliasing rules.
-      const M *ptr = static_cast<const M*>(
-          static_cast<const void*>(&m.buffer_));
+      const M* ptr =
+          static_cast<const M*>(static_cast<const void*>(&m.buffer_));
       return *ptr;
     }
     static void Init(MatcherBase& m, M impl) {
@@ -741,7 +761,7 @@ template <typename Rhs>
 class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
  public:
   explicit EqMatcher(const Rhs& rhs)
-      : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
+      : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) {}
   static const char* Desc() { return "is equal to"; }
   static const char* NegatedDesc() { return "isn't equal to"; }
 };
@@ -749,7 +769,7 @@ template <typename Rhs>
 class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
  public:
   explicit NeMatcher(const Rhs& rhs)
-      : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
+      : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) {}
   static const char* Desc() { return "isn't equal to"; }
   static const char* NegatedDesc() { return "is equal to"; }
 };
@@ -757,7 +777,7 @@ template <typename Rhs>
 class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
  public:
   explicit LtMatcher(const Rhs& rhs)
-      : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
+      : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) {}
   static const char* Desc() { return "is <"; }
   static const char* NegatedDesc() { return "isn't <"; }
 };
@@ -765,7 +785,7 @@ template <typename Rhs>
 class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
  public:
   explicit GtMatcher(const Rhs& rhs)
-      : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
+      : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) {}
   static const char* Desc() { return "is >"; }
   static const char* NegatedDesc() { return "isn't >"; }
 };
@@ -773,7 +793,7 @@ template <typename Rhs>
 class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
  public:
   explicit LeMatcher(const Rhs& rhs)
-      : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
+      : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) {}
   static const char* Desc() { return "is <="; }
   static const char* NegatedDesc() { return "isn't <="; }
 };
@@ -781,7 +801,7 @@ template <typename Rhs>
 class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
  public:
   explicit GeMatcher(const Rhs& rhs)
-      : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
+      : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) {}
   static const char* Desc() { return "is >="; }
   static const char* NegatedDesc() { return "isn't >="; }
 };
@@ -872,12 +892,16 @@ PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
 // wouldn't compile.
 template <typename T>
-inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
+inline internal::EqMatcher<T> Eq(T x) {
+  return internal::EqMatcher<T>(x);
+}
 
 // Constructs a Matcher<T> from a 'value' of type T.  The constructed
 // matcher matches any value that's equal to 'value'.
 template <typename T>
-Matcher<T>::Matcher(T value) { *this = Eq(value); }
+Matcher<T>::Matcher(T value) {
+  *this = Eq(value);
+}
 
 // Creates a monomorphic matcher that matches anything with type Lhs
 // and equal to rhs.  A user may need to use this instead of Eq(...)
@@ -892,7 +916,9 @@ Matcher<T>::Matcher(T value) { *this = Eq(value); }
 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
 // for example.
 template <typename Lhs, typename Rhs>
-inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
+inline Matcher<Lhs> TypedEq(const Rhs& rhs) {
+  return Eq(rhs);
+}
 
 // Creates a polymorphic matcher that matches anything >= x.
 template <typename Rhs>
index becfd49fcba9c5ab986e4b4396bc8143a3c587a1..6c8bf900094a31ad4280e667ecdec149429ff8ec 100644 (file)
@@ -27,7 +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.
 
-//
 // The Google C++ Testing and Mocking Framework (Google Test)
 //
 // This header file defines the Message class.
@@ -42,7 +41,9 @@
 // to CHANGE WITHOUT NOTICE.  Therefore DO NOT DEPEND ON IT in a user
 // program!
 
-// GOOGLETEST_CM0001 DO NOT DELETE
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
 #define GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
@@ -110,8 +111,8 @@ class GTEST_API_ Message {
 
   // Streams a non-pointer value to this object.
   template <typename T>
-  inline Message& operator <<(const T& val) {
-    // Some libraries overload << for STL containers.  These
+  inline Message& operator<<(const T& val) {
+        // Some libraries overload << for STL containers.  These
     // overloads are defined in the global namespace instead of ::std.
     //
     // C++'s symbol lookup rule (i.e. Koenig lookup) says that these
@@ -125,7 +126,7 @@ class GTEST_API_ Message {
     // from the global namespace.  With this using declaration,
     // overloads of << defined in the global namespace and those
     // visible via Koenig lookup are both exposed in this function.
-    using ::operator <<;
+    using ::operator<<;
     *ss_ << val;
     return *this;
   }
@@ -144,7 +145,7 @@ class GTEST_API_ Message {
   // ensure consistent result across compilers, we always treat NULL
   // as "(null)".
   template <typename T>
-  inline Message& operator <<(T* const& pointer) {  // NOLINT
+  inline Message& operator<<(T* const& pointer) {  // NOLINT
     if (pointer == nullptr) {
       *ss_ << "(null)";
     } else {
@@ -159,25 +160,23 @@ class GTEST_API_ Message {
   // templatized version above.  Without this definition, streaming
   // endl or other basic IO manipulators to Message will confuse the
   // compiler.
-  Message& operator <<(BasicNarrowIoManip val) {
+  Message& operator<<(BasicNarrowIoManip val) {
     *ss_ << val;
     return *this;
   }
 
   // Instead of 1/0, we want to see true/false for bool values.
-  Message& operator <<(bool b) {
-    return *this << (b ? "true" : "false");
-  }
+  Message& operator<<(bool b) { return *this << (b ? "true" : "false"); }
 
   // These two overloads allow streaming a wide C string to a Message
   // using the UTF-8 encoding.
-  Message& operator <<(const wchar_t* wide_c_str);
-  Message& operator <<(wchar_t* wide_c_str);
+  Message& operator<<(const wchar_t* wide_c_str);
+  Message& operator<<(wchar_t* wide_c_str);
 
 #if GTEST_HAS_STD_WSTRING
   // Converts the given wide string to a narrow string using the UTF-8
   // encoding, and streams the result to this Message object.
-  Message& operator <<(const ::std::wstring& wstr);
+  Message& operator<<(const ::std::wstring& wstr);
 #endif  // GTEST_HAS_STD_WSTRING
 
   // Gets the text streamed to this object so far as an std::string.
@@ -196,7 +195,7 @@ class GTEST_API_ Message {
 };
 
 // Streams a Message to an ostream.
-inline std::ostream& operator <<(std::ostream& os, const Message& sb) {
+inline std::ostream& operator<<(std::ostream& os, const Message& sb) {
   return os << sb.GetString();
 }
 
index 804e702817b03b90a3e77fd8bdc8a037e72f5e7d..b55119ac62f73e95562bff7a4ee6d23611cc3513 100644 (file)
 // 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.
-//
+
 // Macros and functions for implementing parameterized tests
 // in Google C++ Testing and Mocking Framework (Google Test)
-//
-// GOOGLETEST_CM0001 DO NOT DELETE
+
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
+
 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
 
@@ -353,9 +356,7 @@ internal::ValueArray<T...> Values(T... v) {
 // }
 // INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool());
 //
-inline internal::ParamGenerator<bool> Bool() {
-  return Values(false, true);
-}
+inline internal::ParamGenerator<bool> Bool() { return Values(false, true); }
 
 // Combine() allows the user to combine two or more sequences to produce
 // values of a Cartesian product of those sequences' elements.
@@ -428,8 +429,11 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
       return 0;                                                                \
     }                                                                          \
     static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_;               \
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name,    \
-                                                           test_name));        \
+    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)                         \
+    (const GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &) = delete;     \
+    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=(            \
+        const GTEST_TEST_CLASS_NAME_(test_suite_name,                          \
+                                     test_name) &) = delete; /* NOLINT */      \
   };                                                                           \
   int GTEST_TEST_CLASS_NAME_(test_suite_name,                                  \
                              test_name)::gtest_registering_dummy_ =            \
@@ -453,43 +457,42 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
 #define GTEST_GET_FIRST_(first, ...) first
 #define GTEST_GET_SECOND_(first, second, ...) second
 
-#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...)                \
-  static ::testing::internal::ParamGenerator<test_suite_name::ParamType>      \
-      gtest_##prefix##test_suite_name##_EvalGenerator_() {                    \
-    return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_));        \
-  }                                                                           \
-  static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_(   \
-      const ::testing::TestParamInfo<test_suite_name::ParamType>& info) {     \
-    if (::testing::internal::AlwaysFalse()) {                                 \
-      ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_(      \
-          __VA_ARGS__,                                                        \
-          ::testing::internal::DefaultParamName<test_suite_name::ParamType>,  \
-          DUMMY_PARAM_)));                                                    \
-      auto t = std::make_tuple(__VA_ARGS__);                                  \
-      static_assert(std::tuple_size<decltype(t)>::value <= 2,                 \
-                    "Too Many Args!");                                        \
-    }                                                                         \
-    return ((GTEST_EXPAND_(GTEST_GET_SECOND_(                                 \
-        __VA_ARGS__,                                                          \
-        ::testing::internal::DefaultParamName<test_suite_name::ParamType>,    \
-        DUMMY_PARAM_))))(info);                                               \
-  }                                                                           \
-  static int gtest_##prefix##test_suite_name##_dummy_                         \
-      GTEST_ATTRIBUTE_UNUSED_ =                                               \
-          ::testing::UnitTest::GetInstance()                                  \
-              ->parameterized_test_registry()                                 \
-              .GetTestSuitePatternHolder<test_suite_name>(                    \
-                  GTEST_STRINGIFY_(test_suite_name),                          \
-                  ::testing::internal::CodeLocation(__FILE__, __LINE__))      \
-              ->AddTestSuiteInstantiation(                                    \
-                  GTEST_STRINGIFY_(prefix),                                   \
-                  &gtest_##prefix##test_suite_name##_EvalGenerator_,          \
-                  &gtest_##prefix##test_suite_name##_EvalGenerateName_,       \
+#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...)               \
+  static ::testing::internal::ParamGenerator<test_suite_name::ParamType>     \
+      gtest_##prefix##test_suite_name##_EvalGenerator_() {                   \
+    return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_));       \
+  }                                                                          \
+  static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_(  \
+      const ::testing::TestParamInfo<test_suite_name::ParamType>& info) {    \
+    if (::testing::internal::AlwaysFalse()) {                                \
+      ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_(     \
+          __VA_ARGS__,                                                       \
+          ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
+          DUMMY_PARAM_)));                                                   \
+      auto t = std::make_tuple(__VA_ARGS__);                                 \
+      static_assert(std::tuple_size<decltype(t)>::value <= 2,                \
+                    "Too Many Args!");                                       \
+    }                                                                        \
+    return ((GTEST_EXPAND_(GTEST_GET_SECOND_(                                \
+        __VA_ARGS__,                                                         \
+        ::testing::internal::DefaultParamName<test_suite_name::ParamType>,   \
+        DUMMY_PARAM_))))(info);                                              \
+  }                                                                          \
+  static int gtest_##prefix##test_suite_name##_dummy_                        \
+      GTEST_ATTRIBUTE_UNUSED_ =                                              \
+          ::testing::UnitTest::GetInstance()                                 \
+              ->parameterized_test_registry()                                \
+              .GetTestSuitePatternHolder<test_suite_name>(                   \
+                  GTEST_STRINGIFY_(test_suite_name),                         \
+                  ::testing::internal::CodeLocation(__FILE__, __LINE__))     \
+              ->AddTestSuiteInstantiation(                                   \
+                  GTEST_STRINGIFY_(prefix),                                  \
+                  &gtest_##prefix##test_suite_name##_EvalGenerator_,         \
+                  &gtest_##prefix##test_suite_name##_EvalGenerateName_,      \
                   __FILE__, __LINE__)
 
-
 // Allow Marking a Parameterized test class as not needing to be instantiated.
-#define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T)                   \
+#define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T)                  \
   namespace gtest_do_not_use_outside_namespace_scope {}                   \
   static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \
       GTEST_STRINGIFY_(T))
index 076c9de1f41ea8e12c3c06846d3b9ae9f9b7e95d..a91e8b8b10ee3620a16ef28434e81c0fc9119c13 100644 (file)
@@ -27,7 +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.
 
-
 // Google Test - The Google C++ Testing and Mocking Framework
 //
 // This file implements a universal value printer that can print a
@@ -95,7 +94,9 @@
 // being defined as many user-defined container types don't have
 // value_type.
 
-// GOOGLETEST_CM0001 DO NOT DELETE
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
@@ -257,12 +258,10 @@ struct ConvertibleToStringViewPrinter {
 #endif
 };
 
-
 // Prints the given number of bytes in the given object to the given
 // ostream.
 GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
-                                     size_t count,
-                                     ::std::ostream* os);
+                                     size_t count, ::std::ostream* os);
 struct RawBytesPrinter {
   // SFINAE on `sizeof` to make sure we have a complete type.
   template <typename T, size_t = sizeof(T)>
@@ -360,7 +359,7 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
-#ifdef __cpp_char8_t
+#ifdef __cpp_lib_char8_t
 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);
 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);
 #endif
@@ -375,12 +374,12 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
 // to point to a NUL-terminated string, and thus can print it as a string.
 
 #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
-  template <>                                                           \
-  class FormatForComparison<CharType*, OtherStringType> {               \
-   public:                                                              \
-    static ::std::string Format(CharType* value) {                      \
-      return ::testing::PrintToString(value);                           \
-    }                                                                   \
+  template <>                                                            \
+  class FormatForComparison<CharType*, OtherStringType> {                \
+   public:                                                               \
+    static ::std::string Format(CharType* value) {                       \
+      return ::testing::PrintToString(value);                            \
+    }                                                                    \
   }
 
 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
@@ -410,8 +409,8 @@ GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
 //
 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
 template <typename T1, typename T2>
-std::string FormatForComparisonFailureMessage(
-    const T1& value, const T2& /* other_operand */) {
+std::string FormatForComparisonFailureMessage(const T1& value,
+                                              const T2& /* other_operand */) {
   return FormatForComparison<T1, T2>::Format(value);
 }
 
@@ -479,6 +478,12 @@ inline void PrintTo(char8_t c, ::std::ostream* os) {
 }
 #endif
 
+// gcc/clang __{u,}int128_t
+#if defined(__SIZEOF_INT128__)
+GTEST_API_ void PrintTo(__uint128_t v, ::std::ostream* os);
+GTEST_API_ void PrintTo(__int128_t v, ::std::ostream* os);
+#endif  // __SIZEOF_INT128__
+
 // Overloads for C strings.
 GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
 inline void PrintTo(char* s, ::std::ostream* os) {
@@ -545,7 +550,7 @@ void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
 }
 
 // Overloads for ::std::string.
-GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
+GTEST_API_ void PrintStringTo(const ::std::string& s, ::std::ostream* os);
 inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
   PrintStringTo(s, os);
 }
@@ -572,7 +577,7 @@ inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
 
 // Overloads for ::std::wstring.
 #if GTEST_HAS_STD_WSTRING
-GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
+GTEST_API_ void PrintWideStringTo(const ::std::wstring& s, ::std::ostream* os);
 inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
   PrintWideStringTo(s, os);
 }
@@ -587,6 +592,12 @@ inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
 
 inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
 
+#if GTEST_HAS_RTTI
+inline void PrintTo(const std::type_info& info, std::ostream* os) {
+  *os << internal::GetTypeName(info);
+}
+#endif  // GTEST_HAS_RTTI
+
 template <typename T>
 void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
   UniversalPrinter<T&>::Print(ref.get(), os);
@@ -744,6 +755,14 @@ class UniversalPrinter<Optional<T>> {
   }
 };
 
+template <>
+class UniversalPrinter<decltype(Nullopt())> {
+ public:
+  static void Print(decltype(Nullopt()), ::std::ostream* os) {
+    *os << "(nullopt)";
+  }
+};
+
 #endif  // GTEST_INTERNAL_HAS_OPTIONAL
 
 #if GTEST_INTERNAL_HAS_VARIANT
@@ -802,8 +821,8 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
   }
 }
 // This overload prints a (const) char array compactly.
-GTEST_API_ void UniversalPrintArray(
-    const char* begin, size_t len, ::std::ostream* os);
+GTEST_API_ void UniversalPrintArray(const char* begin, size_t len,
+                                    ::std::ostream* os);
 
 #ifdef __cpp_char8_t
 // This overload prints a (const) char8_t array compactly.
@@ -820,8 +839,8 @@ GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,
                                     ::std::ostream* os);
 
 // This overload prints a (const) wchar_t array compactly.
-GTEST_API_ void UniversalPrintArray(
-    const wchar_t* begin, size_t len, ::std::ostream* os);
+GTEST_API_ void UniversalPrintArray(const wchar_t* begin, size_t len,
+                                    ::std::ostream* os);
 
 // Implements printing an array type T[N].
 template <typename T, size_t N>
@@ -980,10 +999,10 @@ void UniversalPrint(const T& value, ::std::ostream* os) {
   UniversalPrinter<T1>::Print(value, os);
 }
 
-typedef ::std::vector< ::std::string> Strings;
+typedef ::std::vector<::std::string> Strings;
 
-  // Tersely prints the first N fields of a tuple to a string vector,
-  // one element for each field.
+// Tersely prints the first N fields of a tuple to a string vector,
+// one element for each field.
 template <typename Tuple>
 void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
                                Strings*) {}
index eacef44669e8104a3d28daa054edadcdeb23c548..bec8c4810bb189e2efedf6eb2c21d9c199528afb 100644 (file)
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-//
 // Utilities for testing Google Test itself and code that uses Google Test
 // (e.g. frameworks built on top of Google Test).
 
-// GOOGLETEST_CM0004 DO NOT DELETE
-
 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
 #define GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
 
@@ -88,7 +85,10 @@ class GTEST_API_ ScopedFakeTestPartResultReporter
   TestPartResultReporterInterface* old_reporter_;
   TestPartResultArray* const result_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
+  ScopedFakeTestPartResultReporter(const ScopedFakeTestPartResultReporter&) =
+      delete;
+  ScopedFakeTestPartResultReporter& operator=(
+      const ScopedFakeTestPartResultReporter&) = delete;
 };
 
 namespace internal {
@@ -104,12 +104,14 @@ class GTEST_API_ SingleFailureChecker {
   SingleFailureChecker(const TestPartResultArray* results,
                        TestPartResult::Type type, const std::string& substr);
   ~SingleFailureChecker();
+
  private:
   const TestPartResultArray* const results_;
   const TestPartResult::Type type_;
   const std::string substr_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
+  SingleFailureChecker(const SingleFailureChecker&) = delete;
+  SingleFailureChecker& operator=(const SingleFailureChecker&) = delete;
 };
 
 }  // namespace internal
@@ -119,7 +121,8 @@ class GTEST_API_ SingleFailureChecker {
 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
 
 // A set of macros for testing Google Test assertions or code that's expected
-// to generate Google Test fatal failures.  It verifies that the given
+// to generate Google Test fatal failures (e.g. a failure from an ASSERT_EQ, but
+// not a non-fatal failure, as from EXPECT_EQ).  It verifies that the given
 // statement will cause exactly one fatal Google Test failure with 'substr'
 // being part of the failure message.
 //
@@ -141,44 +144,46 @@ GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
 // helper macro, due to some peculiarity in how the preprocessor
 // works.  The AcceptsMacroThatExpandsToUnprotectedComma test in
 // gtest_unittest.cc will fail to compile if we do that.
-#define EXPECT_FATAL_FAILURE(statement, substr) \
-  do { \
-    class GTestExpectFatalFailureHelper {\
-     public:\
-      static void Execute() { statement; }\
-    };\
-    ::testing::TestPartResultArray gtest_failures;\
-    ::testing::internal::SingleFailureChecker gtest_checker(\
-        &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
-    {\
-      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
-          ::testing::ScopedFakeTestPartResultReporter:: \
-          INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
-      GTestExpectFatalFailureHelper::Execute();\
-    }\
+#define EXPECT_FATAL_FAILURE(statement, substr)                               \
+  do {                                                                        \
+    class GTestExpectFatalFailureHelper {                                     \
+     public:                                                                  \
+      static void Execute() { statement; }                                    \
+    };                                                                        \
+    ::testing::TestPartResultArray gtest_failures;                            \
+    ::testing::internal::SingleFailureChecker gtest_checker(                  \
+        &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr)); \
+    {                                                                         \
+      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(             \
+          ::testing::ScopedFakeTestPartResultReporter::                       \
+              INTERCEPT_ONLY_CURRENT_THREAD,                                  \
+          &gtest_failures);                                                   \
+      GTestExpectFatalFailureHelper::Execute();                               \
+    }                                                                         \
   } while (::testing::internal::AlwaysFalse())
 
-#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
-  do { \
-    class GTestExpectFatalFailureHelper {\
-     public:\
-      static void Execute() { statement; }\
-    };\
-    ::testing::TestPartResultArray gtest_failures;\
-    ::testing::internal::SingleFailureChecker gtest_checker(\
-        &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
-    {\
-      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
-          ::testing::ScopedFakeTestPartResultReporter:: \
-          INTERCEPT_ALL_THREADS, &gtest_failures);\
-      GTestExpectFatalFailureHelper::Execute();\
-    }\
+#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr)                \
+  do {                                                                        \
+    class GTestExpectFatalFailureHelper {                                     \
+     public:                                                                  \
+      static void Execute() { statement; }                                    \
+    };                                                                        \
+    ::testing::TestPartResultArray gtest_failures;                            \
+    ::testing::internal::SingleFailureChecker gtest_checker(                  \
+        &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr)); \
+    {                                                                         \
+      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(             \
+          ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
+          &gtest_failures);                                                   \
+      GTestExpectFatalFailureHelper::Execute();                               \
+    }                                                                         \
   } while (::testing::internal::AlwaysFalse())
 
 // A macro for testing Google Test assertions or code that's expected to
-// generate Google Test non-fatal failures.  It asserts that the given
-// statement will cause exactly one non-fatal Google Test failure with 'substr'
-// being part of the failure message.
+// generate Google Test non-fatal failures (e.g. a failure from an EXPECT_EQ,
+// but not from an ASSERT_EQ). It asserts that the given statement will cause
+// exactly one non-fatal Google Test failure with 'substr' being part of the
+// failure message.
 //
 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
 // affects and considers failures generated in the current thread and
@@ -207,32 +212,37 @@ GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
 // instead of
 //   GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
 // to avoid an MSVC warning on unreachable code.
-#define EXPECT_NONFATAL_FAILURE(statement, substr) \
-  do {\
-    ::testing::TestPartResultArray gtest_failures;\
-    ::testing::internal::SingleFailureChecker gtest_checker(\
+#define EXPECT_NONFATAL_FAILURE(statement, substr)                    \
+  do {                                                                \
+    ::testing::TestPartResultArray gtest_failures;                    \
+    ::testing::internal::SingleFailureChecker gtest_checker(          \
         &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
-        (substr));\
-    {\
-      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
-          ::testing::ScopedFakeTestPartResultReporter:: \
-          INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
-      if (::testing::internal::AlwaysTrue()) { statement; }\
-    }\
+        (substr));                                                    \
+    {                                                                 \
+      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(     \
+          ::testing::ScopedFakeTestPartResultReporter::               \
+              INTERCEPT_ONLY_CURRENT_THREAD,                          \
+          &gtest_failures);                                           \
+      if (::testing::internal::AlwaysTrue()) {                        \
+        statement;                                                    \
+      }                                                               \
+    }                                                                 \
   } while (::testing::internal::AlwaysFalse())
 
-#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
-  do {\
-    ::testing::TestPartResultArray gtest_failures;\
-    ::testing::internal::SingleFailureChecker gtest_checker(\
-        &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
-        (substr));\
-    {\
-      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
+#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr)             \
+  do {                                                                        \
+    ::testing::TestPartResultArray gtest_failures;                            \
+    ::testing::internal::SingleFailureChecker gtest_checker(                  \
+        &gtest_failures, ::testing::TestPartResult::kNonFatalFailure,         \
+        (substr));                                                            \
+    {                                                                         \
+      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(             \
           ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
-          &gtest_failures);\
-      if (::testing::internal::AlwaysTrue()) { statement; }\
-    }\
+          &gtest_failures);                                                   \
+      if (::testing::internal::AlwaysTrue()) {                                \
+        statement;                                                            \
+      }                                                                       \
+    }                                                                         \
   } while (::testing::internal::AlwaysFalse())
 
 #endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
index 203fdf98c69fcdf9647437cdc8e6cc70ae18e609..09cc8c34f0413bd36cda310e6cd893cc3e1c51cf 100644 (file)
 // 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.
-//
-// GOOGLETEST_CM0001 DO NOT DELETE
+
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
 #define GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
 
 #include <iosfwd>
 #include <vector>
+
 #include "gtest/internal/gtest-internal.h"
 #include "gtest/internal/gtest-string.h"
 
@@ -142,7 +145,8 @@ class GTEST_API_ TestPartResultArray {
  private:
   std::vector<TestPartResult> array_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray);
+  TestPartResultArray(const TestPartResultArray&) = delete;
+  TestPartResultArray& operator=(const TestPartResultArray&) = delete;
 };
 
 // This interface knows how to report a test part result.
@@ -168,11 +172,13 @@ class GTEST_API_ HasNewFatalFailureHelper
   ~HasNewFatalFailureHelper() override;
   void ReportTestPartResult(const TestPartResult& result) override;
   bool has_new_fatal_failure() const { return has_new_fatal_failure_; }
+
  private:
   bool has_new_fatal_failure_;
   TestPartResultReporterInterface* original_reporter_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper);
+  HasNewFatalFailureHelper(const HasNewFatalFailureHelper&) = delete;
+  HasNewFatalFailureHelper& operator=(const HasNewFatalFailureHelper&) = delete;
 };
 
 }  // namespace internal
index 9fdc6be10dc26b8033e1aa5a0f5af05f82547915..bd35a32660130403369577f61fb68c85c4f85eb3 100644 (file)
@@ -27,7 +27,9 @@
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-// GOOGLETEST_CM0001 DO NOT DELETE
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
 #define GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
@@ -190,7 +192,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
   typedef ::testing::internal::GenerateTypeList<Types>::type            \
       GTEST_TYPE_PARAMS_(CaseName);                                     \
   typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \
-      GTEST_NAME_GENERATOR_(CaseName)
+  GTEST_NAME_GENERATOR_(CaseName)
 
 #define TYPED_TEST(CaseName, TestName)                                        \
   static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1,                       \
@@ -256,7 +258,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
 // #included in multiple translation units linked together.
 #define TYPED_TEST_SUITE_P(SuiteName)              \
   static ::testing::internal::TypedTestSuitePState \
-      GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName)
+  GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName)
 
 // Legacy API is deprecated but still available
 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
@@ -301,21 +303,21 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
   REGISTER_TYPED_TEST_SUITE_P
 #endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
 
-#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...)       \
-  static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1,                       \
-                "test-suit-prefix must not be empty");                      \
-  static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ =        \
-      ::testing::internal::TypeParameterizedTestSuite<                      \
-          SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_,    \
-          ::testing::internal::GenerateTypeList<Types>::type>::             \
-          Register(GTEST_STRINGIFY_(Prefix),                                \
-                   ::testing::internal::CodeLocation(__FILE__, __LINE__),   \
-                   &GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName),             \
-                   GTEST_STRINGIFY_(SuiteName),                             \
-                   GTEST_REGISTERED_TEST_NAMES_(SuiteName),                 \
-                   ::testing::internal::GenerateNames<                      \
-                       ::testing::internal::NameGeneratorSelector<          \
-                           __VA_ARGS__>::type,                              \
+#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...)     \
+  static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1,                     \
+                "test-suit-prefix must not be empty");                    \
+  static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ =      \
+      ::testing::internal::TypeParameterizedTestSuite<                    \
+          SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_,  \
+          ::testing::internal::GenerateTypeList<Types>::type>::           \
+          Register(GTEST_STRINGIFY_(Prefix),                              \
+                   ::testing::internal::CodeLocation(__FILE__, __LINE__), \
+                   &GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName),           \
+                   GTEST_STRINGIFY_(SuiteName),                           \
+                   GTEST_REGISTERED_TEST_NAMES_(SuiteName),               \
+                   ::testing::internal::GenerateNames<                    \
+                       ::testing::internal::NameGeneratorSelector<        \
+                           __VA_ARGS__>::type,                            \
                        ::testing::internal::GenerateTypeList<Types>::type>())
 
 // Legacy API is deprecated but still available
index 7a5d057c4a7eccd5c05a5d01f00d405a281e8dd5..d19a587a18cf27f6127a9d0f27f6bc59092913e9 100644 (file)
@@ -27,7 +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.
 
-//
 // The Google C++ Testing and Mocking Framework (Google Test)
 //
 // This header file defines the public API for Google Test.  It should be
@@ -47,8 +46,6 @@
 // registration from Barthelemy Dagenais' (barthelemy@prologique.com)
 // easyUnit framework.
 
-// GOOGLETEST_CM0001 DO NOT DELETE
-
 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_H_
 #define GOOGLETEST_INCLUDE_GTEST_GTEST_H_
 
 #include <type_traits>
 #include <vector>
 
-#include "gtest/internal/gtest-internal.h"
-#include "gtest/internal/gtest-string.h"
+#include "gtest/gtest-assertion-result.h"
 #include "gtest/gtest-death-test.h"
 #include "gtest/gtest-matchers.h"
 #include "gtest/gtest-message.h"
 #include "gtest/gtest-param-test.h"
 #include "gtest/gtest-printers.h"
-#include "gtest/gtest_prod.h"
 #include "gtest/gtest-test-part.h"
 #include "gtest/gtest-typed-test.h"
+#include "gtest/gtest_pred_impl.h"
+#include "gtest/gtest_prod.h"
+#include "gtest/internal/gtest-internal.h"
+#include "gtest/internal/gtest-string.h"
 
 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
 /* class A needs to have dll-interface to be used by clients of class B */)
 
-namespace testing {
-
-// Silence C4100 (unreferenced formal parameter) and 4805
-// unsafe mix of type 'const int' and type 'const bool'
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4805)
-# pragma warning(disable:4100)
-#endif
-
-
 // Declares the flags.
 
 // This flag temporary enables the disabled tests.
@@ -138,6 +126,12 @@ GTEST_DECLARE_int32_(random_seed);
 // is 1. If the value is -1 the tests are repeating forever.
 GTEST_DECLARE_int32_(repeat);
 
+// This flag controls whether Google Test Environments are recreated for each
+// repeat of the tests. The default value is true. If set to false the global
+// test Environment objects are only set up once, for the first iteration, and
+// only torn down once, for the last.
+GTEST_DECLARE_bool_(recreate_environments_when_repeating);
+
 // This flag controls whether Google Test includes Google Test internal
 // stack frames in failure stack traces.
 GTEST_DECLARE_bool_(show_internal_stack_frames);
@@ -163,6 +157,16 @@ GTEST_DECLARE_string_(stream_result_to);
 GTEST_DECLARE_string_(flagfile);
 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
 
+namespace testing {
+
+// Silence C4100 (unreferenced formal parameter) and 4805
+// unsafe mix of type 'const int' and type 'const bool'
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4805)
+#pragma warning(disable : 4100)
+#endif
+
 // The upper limit for valid stack trace depths.
 const int kMaxStackTraceDepth = 100;
 
@@ -201,193 +205,6 @@ using TestCase = TestSuite;
 class TestInfo;
 class UnitTest;
 
-// A class for indicating whether an assertion was successful.  When
-// the assertion wasn't successful, the AssertionResult object
-// remembers a non-empty message that describes how it failed.
-//
-// To create an instance of this class, use one of the factory functions
-// (AssertionSuccess() and AssertionFailure()).
-//
-// This class is useful for two purposes:
-//   1. Defining predicate functions to be used with Boolean test assertions
-//      EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
-//   2. Defining predicate-format functions to be
-//      used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
-//
-// For example, if you define IsEven predicate:
-//
-//   testing::AssertionResult IsEven(int n) {
-//     if ((n % 2) == 0)
-//       return testing::AssertionSuccess();
-//     else
-//       return testing::AssertionFailure() << n << " is odd";
-//   }
-//
-// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
-// will print the message
-//
-//   Value of: IsEven(Fib(5))
-//     Actual: false (5 is odd)
-//   Expected: true
-//
-// instead of a more opaque
-//
-//   Value of: IsEven(Fib(5))
-//     Actual: false
-//   Expected: true
-//
-// in case IsEven is a simple Boolean predicate.
-//
-// If you expect your predicate to be reused and want to support informative
-// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
-// about half as often as positive ones in our tests), supply messages for
-// both success and failure cases:
-//
-//   testing::AssertionResult IsEven(int n) {
-//     if ((n % 2) == 0)
-//       return testing::AssertionSuccess() << n << " is even";
-//     else
-//       return testing::AssertionFailure() << n << " is odd";
-//   }
-//
-// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
-//
-//   Value of: IsEven(Fib(6))
-//     Actual: true (8 is even)
-//   Expected: false
-//
-// NB: Predicates that support negative Boolean assertions have reduced
-// performance in positive ones so be careful not to use them in tests
-// that have lots (tens of thousands) of positive Boolean assertions.
-//
-// To use this class with EXPECT_PRED_FORMAT assertions such as:
-//
-//   // Verifies that Foo() returns an even number.
-//   EXPECT_PRED_FORMAT1(IsEven, Foo());
-//
-// you need to define:
-//
-//   testing::AssertionResult IsEven(const char* expr, int n) {
-//     if ((n % 2) == 0)
-//       return testing::AssertionSuccess();
-//     else
-//       return testing::AssertionFailure()
-//         << "Expected: " << expr << " is even\n  Actual: it's " << n;
-//   }
-//
-// If Foo() returns 5, you will see the following message:
-//
-//   Expected: Foo() is even
-//     Actual: it's 5
-//
-class GTEST_API_ AssertionResult {
- public:
-  // Copy constructor.
-  // Used in EXPECT_TRUE/FALSE(assertion_result).
-  AssertionResult(const AssertionResult& other);
-
-// C4800 is a level 3 warning in Visual Studio 2015 and earlier.
-// This warning is not emitted in Visual Studio 2017.
-// This warning is off by default starting in Visual Studio 2019 but can be
-// enabled with command-line options.
-#if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
-  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
-#endif
-
-  // Used in the EXPECT_TRUE/FALSE(bool_expression).
-  //
-  // T must be contextually convertible to bool.
-  //
-  // The second parameter prevents this overload from being considered if
-  // the argument is implicitly convertible to AssertionResult. In that case
-  // we want AssertionResult's copy constructor to be used.
-  template <typename T>
-  explicit AssertionResult(
-      const T& success,
-      typename std::enable_if<
-          !std::is_convertible<T, AssertionResult>::value>::type*
-      /*enabler*/
-      = nullptr)
-      : success_(success) {}
-
-#if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
-  GTEST_DISABLE_MSC_WARNINGS_POP_()
-#endif
-
-  // Assignment operator.
-  AssertionResult& operator=(AssertionResult other) {
-    swap(other);
-    return *this;
-  }
-
-  // Returns true if and only if the assertion succeeded.
-  operator bool() const { return success_; }  // NOLINT
-
-  // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
-  AssertionResult operator!() const;
-
-  // Returns the text streamed into this AssertionResult. Test assertions
-  // use it when they fail (i.e., the predicate's outcome doesn't match the
-  // assertion's expectation). When nothing has been streamed into the
-  // object, returns an empty string.
-  const char* message() const {
-    return message_.get() != nullptr ? message_->c_str() : "";
-  }
-  // Deprecated; please use message() instead.
-  const char* failure_message() const { return message(); }
-
-  // Streams a custom failure message into this object.
-  template <typename T> AssertionResult& operator<<(const T& value) {
-    AppendMessage(Message() << value);
-    return *this;
-  }
-
-  // Allows streaming basic output manipulators such as endl or flush into
-  // this object.
-  AssertionResult& operator<<(
-      ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
-    AppendMessage(Message() << basic_manipulator);
-    return *this;
-  }
-
- private:
-  // Appends the contents of message to message_.
-  void AppendMessage(const Message& a_message) {
-    if (message_.get() == nullptr) message_.reset(new ::std::string);
-    message_->append(a_message.GetString().c_str());
-  }
-
-  // Swap the contents of this AssertionResult with other.
-  void swap(AssertionResult& other);
-
-  // Stores result of the assertion predicate.
-  bool success_;
-  // Stores the message describing the condition in case the expectation
-  // construct is not satisfied with the predicate's outcome.
-  // Referenced via a pointer to avoid taking too much stack frame space
-  // with test assertions.
-  std::unique_ptr< ::std::string> message_;
-};
-
-// Makes a successful assertion result.
-GTEST_API_ AssertionResult AssertionSuccess();
-
-// Makes a failed assertion result.
-GTEST_API_ AssertionResult AssertionFailure();
-
-// Makes a failed assertion result with the given failure message.
-// Deprecated; use AssertionFailure() << msg.
-GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
-
-}  // namespace testing
-
-// Includes the auto-generated header that implements a family of generic
-// predicate assertion macros. This include comes late because it relies on
-// APIs declared above.
-#include "gtest/gtest_pred_impl.h"
-
-namespace testing {
-
 // The abstract class that all tests inherit from.
 //
 // In Google Test, a unit test program contains one or many TestSuites, and
@@ -522,7 +339,8 @@ class GTEST_API_ Test {
   virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
 
   // We disallow copying Tests.
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
+  Test(const Test&) = delete;
+  Test& operator=(const Test&) = delete;
 };
 
 typedef internal::TimeInMillis TimeInMillis;
@@ -536,24 +354,17 @@ class TestProperty {
   // C'tor.  TestProperty does NOT have a default constructor.
   // Always use this constructor (with parameters) to create a
   // TestProperty object.
-  TestProperty(const std::string& a_key, const std::string& a_value) :
-    key_(a_key), value_(a_value) {
-  }
+  TestProperty(const std::string& a_key, const std::string& a_value)
+      : key_(a_key), value_(a_value) {}
 
   // Gets the user supplied key.
-  const char* key() const {
-    return key_.c_str();
-  }
+  const char* key() const { return key_.c_str(); }
 
   // Gets the user supplied value.
-  const char* value() const {
-    return value_.c_str();
-  }
+  const char* value() const { return value_.c_str(); }
 
   // Sets a new value, overriding the one supplied in the constructor.
-  void SetValue(const std::string& new_value) {
-    value_ = new_value;
-  }
+  void SetValue(const std::string& new_value) { value_ = new_value; }
 
  private:
   // The key supplied by the user.
@@ -687,7 +498,8 @@ class GTEST_API_ TestResult {
   TimeInMillis elapsed_time_;
 
   // We disallow copying TestResult.
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
+  TestResult(const TestResult&) = delete;
+  TestResult& operator=(const TestResult&) = delete;
 };  // class TestResult
 
 // A TestInfo object stores the following information about a test:
@@ -811,8 +623,8 @@ class GTEST_API_ TestInfo {
   }
 
   // These fields are immutable properties of the test.
-  const std::string test_suite_name_;    // test suite name
-  const std::string name_;               // Test name
+  const std::string test_suite_name_;  // test suite name
+  const std::string name_;             // Test name
   // Name of the parameter type, or NULL if this is not a typed or a
   // type-parameterized test.
   const std::unique_ptr<const ::std::string> type_param_;
@@ -833,7 +645,8 @@ class GTEST_API_ TestInfo {
   // test for the second time.
   TestResult result_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
+  TestInfo(const TestInfo&) = delete;
+  TestInfo& operator=(const TestInfo&) = delete;
 };
 
 // A test suite, which consists of a vector of TestInfos.
@@ -941,7 +754,7 @@ class GTEST_API_ TestSuite {
 
   // Adds a TestInfo to this test suite.  Will delete the TestInfo upon
   // destruction of the TestSuite object.
-  void AddTestInfo(TestInfo * test_info);
+  void AddTestInfo(TestInfo* test_info);
 
   // Clears the results of all tests in this test suite.
   void ClearResult();
@@ -1042,7 +855,8 @@ class GTEST_API_ TestSuite {
   TestResult ad_hoc_test_result_;
 
   // We disallow copying TestSuites.
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestSuite);
+  TestSuite(const TestSuite&) = delete;
+  TestSuite& operator=(const TestSuite&) = delete;
 };
 
 // An Environment object is capable of setting up and tearing down an
@@ -1069,6 +883,7 @@ class Environment {
 
   // Override this to define how to tear down the environment.
   virtual void TearDown() {}
+
  private:
   // If you see an error about overriding the following function or
   // about it being private, you have mis-spelled SetUp() as Setup().
@@ -1120,6 +935,9 @@ class TestEventListener {
   // Fired before the test starts.
   virtual void OnTestStart(const TestInfo& test_info) = 0;
 
+  // Fired when a test is disabled
+  virtual void OnTestDisabled(const TestInfo& /*test_info*/) {}
+
   // Fired after a failed assertion or a SUCCEED() invocation.
   // If you want to throw an exception from this function to skip to the next
   // TEST, it must be AssertionException defined above, or inherited from it.
@@ -1143,8 +961,7 @@ class TestEventListener {
   virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
 
   // Fired after each iteration of tests finishes.
-  virtual void OnTestIterationEnd(const UnitTest& unit_test,
-                                  int iteration) = 0;
+  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration) = 0;
 
   // Fired after all test activities have ended.
   virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
@@ -1169,6 +986,7 @@ class EmptyTestEventListener : public TestEventListener {
 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
 
   void OnTestStart(const TestInfo& /*test_info*/) override {}
+  void OnTestDisabled(const TestInfo& /*test_info*/) override {}
   void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {}
   void OnTestEnd(const TestInfo& /*test_info*/) override {}
   void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
@@ -1258,7 +1076,8 @@ class GTEST_API_ TestEventListeners {
   TestEventListener* default_xml_generator_;
 
   // We disallow copying TestEventListeners.
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
+  TestEventListeners(const TestEventListeners&) = delete;
+  TestEventListeners& operator=(const TestEventListeners&) = delete;
 };
 
 // A UnitTest consists of a vector of TestSuites.
@@ -1301,8 +1120,7 @@ class GTEST_API_ UnitTest {
 
   // Returns the TestInfo object for the test that's currently running,
   // or NULL if no test is running.
-  const TestInfo* current_test_info() const
-      GTEST_LOCK_EXCLUDED_(mutex_);
+  const TestInfo* current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_);
 
   // Returns the random seed used at the start of the current test run.
   int random_seed() const;
@@ -1408,8 +1226,7 @@ class GTEST_API_ UnitTest {
   // eventually call this to report their results.  The user code
   // should use the assertion macros instead of calling this directly.
   void AddTestPartResult(TestPartResult::Type result_type,
-                         const char* file_name,
-                         int line_number,
+                         const char* file_name, int line_number,
                          const std::string& message,
                          const std::string& os_stack_trace)
       GTEST_LOCK_EXCLUDED_(mutex_);
@@ -1440,8 +1257,7 @@ class GTEST_API_ UnitTest {
   friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites();
   friend internal::UnitTestImpl* internal::GetUnitTestImpl();
   friend void internal::ReportFailureInUnknownLocation(
-      TestPartResult::Type result_type,
-      const std::string& message);
+      TestPartResult::Type result_type, const std::string& message);
 
   // Creates an empty UnitTest.
   UnitTest();
@@ -1455,8 +1271,7 @@ class GTEST_API_ UnitTest {
       GTEST_LOCK_EXCLUDED_(mutex_);
 
   // Pops a trace from the per-thread Google Test trace stack.
-  void PopGTestTrace()
-      GTEST_LOCK_EXCLUDED_(mutex_);
+  void PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_);
 
   // Protects mutable state in *impl_.  This is mutable as some const
   // methods need to lock it too.
@@ -1469,7 +1284,8 @@ class GTEST_API_ UnitTest {
   internal::UnitTestImpl* impl_;
 
   // We disallow copying UnitTest.
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
+  UnitTest(const UnitTest&) = delete;
+  UnitTest& operator=(const UnitTest&) = delete;
 };
 
 // A convenient wrapper for adding an environment for the test
@@ -1520,13 +1336,11 @@ namespace internal {
 // when calling EXPECT_* in a tight loop.
 template <typename T1, typename T2>
 AssertionResult CmpHelperEQFailure(const char* lhs_expression,
-                                   const char* rhs_expression,
-                                   const T1& lhs, const T2& rhs) {
-  return EqFailure(lhs_expression,
-                   rhs_expression,
+                                   const char* rhs_expression, const T1& lhs,
+                                   const T2& rhs) {
+  return EqFailure(lhs_expression, rhs_expression,
                    FormatForComparisonFailureMessage(lhs, rhs),
-                   FormatForComparisonFailureMessage(rhs, lhs),
-                   false);
+                   FormatForComparisonFailureMessage(rhs, lhs), false);
 }
 
 // This block of code defines operator==/!=
@@ -1539,8 +1353,7 @@ inline bool operator!=(faketype, faketype) { return false; }
 // The helper function for {ASSERT|EXPECT}_EQ.
 template <typename T1, typename T2>
 AssertionResult CmpHelperEQ(const char* lhs_expression,
-                            const char* rhs_expression,
-                            const T1& lhs,
+                            const char* rhs_expression, const T1& lhs,
                             const T2& rhs) {
   if (lhs == rhs) {
     return AssertionSuccess();
@@ -1571,8 +1384,7 @@ class EqHelper {
   // Even though its body looks the same as the above version, we
   // cannot merge the two, as it will make anonymous enums unhappy.
   static AssertionResult Compare(const char* lhs_expression,
-                                 const char* rhs_expression,
-                                 BiggestInt lhs,
+                                 const char* rhs_expression, BiggestInt lhs,
                                  BiggestInt rhs) {
     return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
   }
@@ -1607,16 +1419,16 @@ AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
 //
 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
 
-#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
-template <typename T1, typename T2>\
-AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
-                                   const T1& val1, const T2& val2) {\
-  if (val1 op val2) {\
-    return AssertionSuccess();\
-  } else {\
-    return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\
-  }\
-}
+#define GTEST_IMPL_CMP_HELPER_(op_name, op)                                \
+  template <typename T1, typename T2>                                      \
+  AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
+                                     const T1& val1, const T2& val2) {     \
+    if (val1 op val2) {                                                    \
+      return AssertionSuccess();                                           \
+    } else {                                                               \
+      return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);            \
+    }                                                                      \
+  }
 
 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
 
@@ -1638,49 +1450,42 @@ GTEST_IMPL_CMP_HELPER_(GT, >)
 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
                                           const char* s2_expression,
-                                          const char* s1,
-                                          const char* s2);
+                                          const char* s1, const char* s2);
 
 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
 //
 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
 GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,
                                               const char* s2_expression,
-                                              const char* s1,
-                                              const char* s2);
+                                              const char* s1, const char* s2);
 
 // The helper function for {ASSERT|EXPECT}_STRNE.
 //
 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
                                           const char* s2_expression,
-                                          const char* s1,
-                                          const char* s2);
+                                          const char* s1, const char* s2);
 
 // The helper function for {ASSERT|EXPECT}_STRCASENE.
 //
 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
 GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
                                               const char* s2_expression,
-                                              const char* s1,
-                                              const char* s2);
-
+                                              const char* s1, const char* s2);
 
 // Helper function for *_STREQ on wide strings.
 //
 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
                                           const char* s2_expression,
-                                          const wchar_t* s1,
-                                          const wchar_t* s2);
+                                          const wchar_t* s1, const wchar_t* s2);
 
 // Helper function for *_STRNE on wide strings.
 //
 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
                                           const char* s2_expression,
-                                          const wchar_t* s1,
-                                          const wchar_t* s2);
+                                          const wchar_t* s1, const wchar_t* s2);
 
 }  // namespace internal
 
@@ -1692,32 +1497,40 @@ GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
 //
 // The {needle,haystack}_expr arguments are the stringified
 // expressions that generated the two real arguments.
-GTEST_API_ AssertionResult IsSubstring(
-    const char* needle_expr, const char* haystack_expr,
-    const char* needle, const char* haystack);
-GTEST_API_ AssertionResult IsSubstring(
-    const char* needle_expr, const char* haystack_expr,
-    const wchar_t* needle, const wchar_t* haystack);
-GTEST_API_ AssertionResult IsNotSubstring(
-    const char* needle_expr, const char* haystack_expr,
-    const char* needle, const char* haystack);
-GTEST_API_ AssertionResult IsNotSubstring(
-    const char* needle_expr, const char* haystack_expr,
-    const wchar_t* needle, const wchar_t* haystack);
-GTEST_API_ AssertionResult IsSubstring(
-    const char* needle_expr, const char* haystack_expr,
-    const ::std::string& needle, const ::std::string& haystack);
-GTEST_API_ AssertionResult IsNotSubstring(
-    const char* needle_expr, const char* haystack_expr,
-    const ::std::string& needle, const ::std::string& haystack);
+GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,
+                                       const char* haystack_expr,
+                                       const char* needle,
+                                       const char* haystack);
+GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,
+                                       const char* haystack_expr,
+                                       const wchar_t* needle,
+                                       const wchar_t* haystack);
+GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,
+                                          const char* haystack_expr,
+                                          const char* needle,
+                                          const char* haystack);
+GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,
+                                          const char* haystack_expr,
+                                          const wchar_t* needle,
+                                          const wchar_t* haystack);
+GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,
+                                       const char* haystack_expr,
+                                       const ::std::string& needle,
+                                       const ::std::string& haystack);
+GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,
+                                          const char* haystack_expr,
+                                          const ::std::string& needle,
+                                          const ::std::string& haystack);
 
 #if GTEST_HAS_STD_WSTRING
-GTEST_API_ AssertionResult IsSubstring(
-    const char* needle_expr, const char* haystack_expr,
-    const ::std::wstring& needle, const ::std::wstring& haystack);
-GTEST_API_ AssertionResult IsNotSubstring(
-    const char* needle_expr, const char* haystack_expr,
-    const ::std::wstring& needle, const ::std::wstring& haystack);
+GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,
+                                       const char* haystack_expr,
+                                       const ::std::wstring& needle,
+                                       const ::std::wstring& haystack);
+GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,
+                                          const char* haystack_expr,
+                                          const ::std::wstring& needle,
+                                          const ::std::wstring& haystack);
 #endif  // GTEST_HAS_STD_WSTRING
 
 namespace internal {
@@ -1732,8 +1545,7 @@ namespace internal {
 template <typename RawType>
 AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
                                          const char* rhs_expression,
-                                         RawType lhs_value,
-                                         RawType rhs_value) {
+                                         RawType lhs_value, RawType rhs_value) {
   const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);
 
   if (lhs.AlmostEquals(rhs)) {
@@ -1748,10 +1560,8 @@ AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
   rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
          << rhs_value;
 
-  return EqFailure(lhs_expression,
-                   rhs_expression,
-                   StringStreamToString(&lhs_ss),
-                   StringStreamToString(&rhs_ss),
+  return EqFailure(lhs_expression, rhs_expression,
+                   StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss),
                    false);
 }
 
@@ -1761,8 +1571,7 @@ AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
 GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
                                                 const char* expr2,
                                                 const char* abs_error_expr,
-                                                double val1,
-                                                double val2,
+                                                double val1, double val2,
                                                 double abs_error);
 
 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
@@ -1770,9 +1579,7 @@ GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
 class GTEST_API_ AssertHelper {
  public:
   // Constructor.
-  AssertHelper(TestPartResult::Type type,
-               const char* file,
-               int line,
+  AssertHelper(TestPartResult::Type type, const char* file, int line,
                const char* message);
   ~AssertHelper();
 
@@ -1786,11 +1593,9 @@ class GTEST_API_ AssertHelper {
   // re-using stack space even for temporary variables, so every EXPECT_EQ
   // reserves stack space for another AssertHelper.
   struct AssertHelperData {
-    AssertHelperData(TestPartResult::Type t,
-                     const char* srcfile,
-                     int line_num,
+    AssertHelperData(TestPartResult::Type t, const char* srcfile, int line_num,
                      const char* msg)
-        : type(t), file(srcfile), line(line_num), message(msg) { }
+        : type(t), file(srcfile), line(line_num), message(msg) {}
 
     TestPartResult::Type const type;
     const char* const file;
@@ -1798,12 +1603,14 @@ class GTEST_API_ AssertHelper {
     std::string const message;
 
    private:
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
+    AssertHelperData(const AssertHelperData&) = delete;
+    AssertHelperData& operator=(const AssertHelperData&) = delete;
   };
 
   AssertHelperData* const data_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
+  AssertHelper(const AssertHelper&) = delete;
+  AssertHelper& operator=(const AssertHelper&) = delete;
 };
 
 }  // namespace internal
@@ -1860,15 +1667,14 @@ class WithParamInterface {
  private:
   // Sets parameter value. The caller is responsible for making sure the value
   // remains alive and unchanged throughout the current test.
-  static void SetParam(const ParamType* parameter) {
-    parameter_ = parameter;
-  }
+  static void SetParam(const ParamType* parameter) { parameter_ = parameter; }
 
   // Static value used for accessing parameter during a test lifetime.
   static const ParamType* parameter_;
 
   // TestClass must be a subclass of WithParamInterface<T> and Test.
-  template <class TestClass> friend class internal::ParameterizedTestFactory;
+  template <class TestClass>
+  friend class internal::ParameterizedTestFactory;
 };
 
 template <typename T>
@@ -1878,8 +1684,7 @@ const T* WithParamInterface<T>::parameter_ = nullptr;
 // WithParamInterface, and can just inherit from ::testing::TestWithParam.
 
 template <typename T>
-class TestWithParam : public Test, public WithParamInterface<T> {
-};
+class TestWithParam : public Test, public WithParamInterface<T> {};
 
 // Macros for indicating success/failure in test code.
 
@@ -1910,7 +1715,7 @@ class TestWithParam : public Test, public WithParamInterface<T> {
 
 // Generates a nonfatal failure at the given source file location with
 // a generic message.
-#define ADD_FAILURE_AT(file, line) \
+#define ADD_FAILURE_AT(file, line)        \
   GTEST_MESSAGE_AT_(file, line, "Failed", \
                     ::testing::TestPartResult::kNonFatalFailure)
 
@@ -1925,7 +1730,7 @@ class TestWithParam : public Test, public WithParamInterface<T> {
 // Define this macro to 1 to omit the definition of FAIL(), which is a
 // generic name and clashes with some other libraries.
 #if !GTEST_DONT_DEFINE_FAIL
-# define FAIL() GTEST_FAIL()
+#define FAIL() GTEST_FAIL()
 #endif
 
 // Generates a success with a generic message.
@@ -1934,7 +1739,7 @@ class TestWithParam : public Test, public WithParamInterface<T> {
 // Define this macro to 1 to omit the definition of SUCCEED(), which
 // is a generic name and clashes with some other libraries.
 #if !GTEST_DONT_DEFINE_SUCCEED
-# define SUCCEED() GTEST_SUCCEED()
+#define SUCCEED() GTEST_SUCCEED()
 #endif
 
 // Macros for testing exceptions.
@@ -1962,16 +1767,15 @@ class TestWithParam : public Test, public WithParamInterface<T> {
 // Boolean assertions. Condition can be either a Boolean expression or an
 // AssertionResult. For more information on how to use AssertionResult with
 // these macros see comments on that class.
-#define GTEST_EXPECT_TRUE(condition) \
+#define GTEST_EXPECT_TRUE(condition)                      \
   GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
                       GTEST_NONFATAL_FAILURE_)
-#define GTEST_EXPECT_FALSE(condition) \
+#define GTEST_EXPECT_FALSE(condition)                        \
   GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
                       GTEST_NONFATAL_FAILURE_)
 #define GTEST_ASSERT_TRUE(condition) \
-  GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
-                      GTEST_FATAL_FAILURE_)
-#define GTEST_ASSERT_FALSE(condition) \
+  GTEST_TEST_BOOLEAN_(condition, #condition, false, true, GTEST_FATAL_FAILURE_)
+#define GTEST_ASSERT_FALSE(condition)                        \
   GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
                       GTEST_FATAL_FAILURE_)
 
@@ -2070,27 +1874,27 @@ class TestWithParam : public Test, public WithParamInterface<T> {
 // ASSERT_XY(), which clashes with some users' own code.
 
 #if !GTEST_DONT_DEFINE_ASSERT_EQ
-# define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
+#define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
 #endif
 
 #if !GTEST_DONT_DEFINE_ASSERT_NE
-# define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
+#define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
 #endif
 
 #if !GTEST_DONT_DEFINE_ASSERT_LE
-# define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
+#define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
 #endif
 
 #if !GTEST_DONT_DEFINE_ASSERT_LT
-# define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
+#define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
 #endif
 
 #if !GTEST_DONT_DEFINE_ASSERT_GE
-# define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
+#define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
 #endif
 
 #if !GTEST_DONT_DEFINE_ASSERT_GT
-# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
+#define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
 #endif
 
 // C-string Comparisons.  All tests treat NULL and any non-NULL string
@@ -2115,7 +1919,7 @@ class TestWithParam : public Test, public WithParamInterface<T> {
   EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
 #define EXPECT_STRCASEEQ(s1, s2) \
   EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
-#define EXPECT_STRCASENE(s1, s2)\
+#define EXPECT_STRCASENE(s1, s2) \
   EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
 
 #define ASSERT_STREQ(s1, s2) \
@@ -2124,7 +1928,7 @@ class TestWithParam : public Test, public WithParamInterface<T> {
   ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
 #define ASSERT_STRCASEEQ(s1, s2) \
   ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
-#define ASSERT_STRCASENE(s1, s2)\
+#define ASSERT_STRCASENE(s1, s2) \
   ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
 
 // Macros for comparing floating-point numbers.
@@ -2141,29 +1945,29 @@ class TestWithParam : public Test, public WithParamInterface<T> {
 // FloatingPoint template class in gtest-internal.h if you are
 // interested in the implementation details.
 
-#define EXPECT_FLOAT_EQ(val1, val2)\
+#define EXPECT_FLOAT_EQ(val1, val2)                                         \
   EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
                       val1, val2)
 
-#define EXPECT_DOUBLE_EQ(val1, val2)\
+#define EXPECT_DOUBLE_EQ(val1, val2)                                         \
   EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
                       val1, val2)
 
-#define ASSERT_FLOAT_EQ(val1, val2)\
+#define ASSERT_FLOAT_EQ(val1, val2)                                         \
   ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
                       val1, val2)
 
-#define ASSERT_DOUBLE_EQ(val1, val2)\
+#define ASSERT_DOUBLE_EQ(val1, val2)                                         \
   ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
                       val1, val2)
 
-#define EXPECT_NEAR(val1, val2, abs_error)\
-  EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
-                      val1, val2, abs_error)
+#define EXPECT_NEAR(val1, val2, abs_error)                                   \
+  EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, val1, val2, \
+                      abs_error)
 
-#define ASSERT_NEAR(val1, val2, abs_error)\
-  ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
-                      val1, val2, abs_error)
+#define ASSERT_NEAR(val1, val2, abs_error)                                   \
+  ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, val1, val2, \
+                      abs_error)
 
 // These predicate format functions work on floating-point values, and
 // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
@@ -2177,7 +1981,6 @@ GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
 GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
                                     double val1, double val2);
 
-
 #if GTEST_OS_WINDOWS
 
 // Macros that test for HRESULT failure and success, these are only useful
@@ -2189,17 +1992,17 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
 // expected result and the actual result with both a human-readable
 // string representation of the error, if available, as well as the
 // hex result code.
-# define EXPECT_HRESULT_SUCCEEDED(expr) \
-    EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
+#define EXPECT_HRESULT_SUCCEEDED(expr) \
+  EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
 
-# define ASSERT_HRESULT_SUCCEEDED(expr) \
-    ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
+#define ASSERT_HRESULT_SUCCEEDED(expr) \
+  ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
 
-# define EXPECT_HRESULT_FAILED(expr) \
-    EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
+#define EXPECT_HRESULT_FAILED(expr) \
+  EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
 
-# define ASSERT_HRESULT_FAILED(expr) \
-    ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
+#define ASSERT_HRESULT_FAILED(expr) \
+  ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
 
 #endif  // GTEST_OS_WINDOWS
 
@@ -2214,9 +2017,9 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
 //   ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
 //
 #define ASSERT_NO_FATAL_FAILURE(statement) \
-    GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
+  GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
 #define EXPECT_NO_FATAL_FAILURE(statement) \
-    GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
+  GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
 
 // Causes a trace (including the given source file path and line number,
 // and the given message) to be included in every test failure message generated
@@ -2258,7 +2061,8 @@ class GTEST_API_ ScopedTrace {
  private:
   void PushTrace(const char* file, int line, std::string message);
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
+  ScopedTrace(const ScopedTrace&) = delete;
+  ScopedTrace& operator=(const ScopedTrace&) = delete;
 } GTEST_ATTRIBUTE_UNUSED_;  // A ScopedTrace object does its job in its
                             // c'tor and d'tor.  Therefore it doesn't
                             // need to be used otherwise.
@@ -2278,9 +2082,9 @@ class GTEST_API_ ScopedTrace {
 // Assuming that each thread maintains its own stack of traces.
 // Therefore, a SCOPED_TRACE() would (correctly) only affect the
 // assertions in its own thread.
-#define SCOPED_TRACE(message) \
-  ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
-    __FILE__, __LINE__, (message))
+#define SCOPED_TRACE(message)                                         \
+  ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \
+      __FILE__, __LINE__, (message))
 
 // Compile-time assertion for type equality.
 // StaticAssertTypeEq<type1, type2>() compiles if and only if type1 and type2
@@ -2378,20 +2182,19 @@ constexpr bool StaticAssertTypeEq() noexcept {
 //     EXPECT_EQ(a_.size(), 0);
 //     EXPECT_EQ(b_.size(), 1);
 //   }
-//
-// GOOGLETEST_CM0011 DO NOT DELETE
-#if !GTEST_DONT_DEFINE_TEST
-#define TEST_F(test_fixture, test_name)\
+#define GTEST_TEST_F(test_fixture, test_name)        \
   GTEST_TEST_(test_fixture, test_name, test_fixture, \
               ::testing::internal::GetTypeId<test_fixture>())
-#endif  // !GTEST_DONT_DEFINE_TEST
+#if !GTEST_DONT_DEFINE_TEST_F
+#define TEST_F(test_fixture, test_name) GTEST_TEST_F(test_fixture, test_name)
+#endif
 
 // Returns a path to temporary directory.
 // Tries to determine an appropriate directory for the platform.
 GTEST_API_ std::string TempDir();
 
 #ifdef _MSC_VER
-#  pragma warning(pop)
+#pragma warning(pop)
 #endif
 
 // Dynamically registers a test with the framework.
@@ -2445,6 +2248,7 @@ GTEST_API_ std::string TempDir();
 // }
 // ...
 // int main(int argc, char** argv) {
+//   ::testing::InitGoogleTest(&argc, argv);
 //   std::vector<int> values_to_test = LoadValuesFromConfig();
 //   RegisterMyTests(values_to_test);
 //   ...
@@ -2486,9 +2290,7 @@ TestInfo* RegisterTest(const char* test_suite_name, const char* test_name,
 // namespace and has an all-caps name.
 int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
 
-inline int RUN_ALL_TESTS() {
-  return ::testing::UnitTest::GetInstance()->Run();
-}
+inline int RUN_ALL_TESTS() { return ::testing::UnitTest::GetInstance()->Run(); }
 
 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
 
index 5029a9bb02ada740f9ee3eee6a5281d6e9593aed..47a24aa687af6ebfed8423bee7802192e73d97ac 100644 (file)
 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// This file is AUTOMATICALLY GENERATED on 01/02/2019 by command
-// 'gen_gtest_pred_impl.py 5'.  DO NOT EDIT BY HAND!
 //
 // Implements a family of generic predicate assertion macros.
-// GOOGLETEST_CM0001 DO NOT DELETE
+
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
 
-#include "gtest/gtest.h"
+#include "gtest/gtest-assertion-result.h"
+#include "gtest/internal/gtest-internal.h"
+#include "gtest/internal/gtest-port.h"
 
 namespace testing {
 
@@ -72,22 +74,18 @@ namespace testing {
 // GTEST_ASSERT_ is the basic statement to which all of the assertions
 // in this file reduce.  Don't use this in your code.
 
-#define GTEST_ASSERT_(expression, on_failure) \
-  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
+#define GTEST_ASSERT_(expression, on_failure)                   \
+  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                 \
   if (const ::testing::AssertionResult gtest_ar = (expression)) \
-    ; \
-  else \
+    ;                                                           \
+  else                                                          \
     on_failure(gtest_ar.failure_message())
 
-
 // Helper function for implementing {EXPECT|ASSERT}_PRED1.  Don't use
 // this in your code.
-template <typename Pred,
-          typename T1>
-AssertionResult AssertPred1Helper(const char* pred_text,
-                                  const char* e1,
-                                  Pred pred,
-                                  const T1& v1) {
+template <typename Pred, typename T1>
+AssertionResult AssertPred1Helper(const char* pred_text, const char* e1,
+                                  Pred pred, const T1& v1) {
   if (pred(v1)) return AssertionSuccess();
 
   return AssertionFailure()
@@ -98,40 +96,27 @@ AssertionResult AssertPred1Helper(const char* pred_text,
 
 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
 // Don't use this in your code.
-#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\
-  GTEST_ASSERT_(pred_format(#v1, v1), \
-                on_failure)
+#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure) \
+  GTEST_ASSERT_(pred_format(#v1, v1), on_failure)
 
 // Internal macro for implementing {EXPECT|ASSERT}_PRED1.  Don't use
 // this in your code.
-#define GTEST_PRED1_(pred, v1, on_failure)\
-  GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \
-                                             #v1, \
-                                             pred, \
-                                             v1), on_failure)
+#define GTEST_PRED1_(pred, v1, on_failure) \
+  GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, #v1, pred, v1), on_failure)
 
 // Unary predicate assertion macros.
 #define EXPECT_PRED_FORMAT1(pred_format, v1) \
   GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_)
-#define EXPECT_PRED1(pred, v1) \
-  GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
+#define EXPECT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
 #define ASSERT_PRED_FORMAT1(pred_format, v1) \
   GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_)
-#define ASSERT_PRED1(pred, v1) \
-  GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
-
-
+#define ASSERT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
 
 // Helper function for implementing {EXPECT|ASSERT}_PRED2.  Don't use
 // this in your code.
-template <typename Pred,
-          typename T1,
-          typename T2>
-AssertionResult AssertPred2Helper(const char* pred_text,
-                                  const char* e1,
-                                  const char* e2,
-                                  Pred pred,
-                                  const T1& v1,
+template <typename Pred, typename T1, typename T2>
+AssertionResult AssertPred2Helper(const char* pred_text, const char* e1,
+                                  const char* e2, Pred pred, const T1& v1,
                                   const T2& v2) {
   if (pred(v1, v2)) return AssertionSuccess();
 
@@ -145,19 +130,14 @@ AssertionResult AssertPred2Helper(const char* pred_text,
 
 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
 // Don't use this in your code.
-#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\
-  GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \
-                on_failure)
+#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure) \
+  GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), on_failure)
 
 // Internal macro for implementing {EXPECT|ASSERT}_PRED2.  Don't use
 // this in your code.
-#define GTEST_PRED2_(pred, v1, v2, on_failure)\
-  GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \
-                                             #v1, \
-                                             #v2, \
-                                             pred, \
-                                             v1, \
-                                             v2), on_failure)
+#define GTEST_PRED2_(pred, v1, v2, on_failure)                               \
+  GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, #v1, #v2, pred, v1, v2), \
+                on_failure)
 
 // Binary predicate assertion macros.
 #define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \
@@ -169,22 +149,12 @@ AssertionResult AssertPred2Helper(const char* pred_text,
 #define ASSERT_PRED2(pred, v1, v2) \
   GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_)
 
-
-
 // Helper function for implementing {EXPECT|ASSERT}_PRED3.  Don't use
 // this in your code.
-template <typename Pred,
-          typename T1,
-          typename T2,
-          typename T3>
-AssertionResult AssertPred3Helper(const char* pred_text,
-                                  const char* e1,
-                                  const char* e2,
-                                  const char* e3,
-                                  Pred pred,
-                                  const T1& v1,
-                                  const T2& v2,
-                                  const T3& v3) {
+template <typename Pred, typename T1, typename T2, typename T3>
+AssertionResult AssertPred3Helper(const char* pred_text, const char* e1,
+                                  const char* e2, const char* e3, Pred pred,
+                                  const T1& v1, const T2& v2, const T3& v3) {
   if (pred(v1, v2, v3)) return AssertionSuccess();
 
   return AssertionFailure()
@@ -198,21 +168,15 @@ AssertionResult AssertPred3Helper(const char* pred_text,
 
 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
 // Don't use this in your code.
-#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\
-  GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \
-                on_failure)
+#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure) \
+  GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), on_failure)
 
 // Internal macro for implementing {EXPECT|ASSERT}_PRED3.  Don't use
 // this in your code.
-#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\
-  GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \
-                                             #v1, \
-                                             #v2, \
-                                             #v3, \
-                                             pred, \
-                                             v1, \
-                                             v2, \
-                                             v3), on_failure)
+#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)                          \
+  GTEST_ASSERT_(                                                            \
+      ::testing::AssertPred3Helper(#pred, #v1, #v2, #v3, pred, v1, v2, v3), \
+      on_failure)
 
 // Ternary predicate assertion macros.
 #define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \
@@ -224,25 +188,13 @@ AssertionResult AssertPred3Helper(const char* pred_text,
 #define ASSERT_PRED3(pred, v1, v2, v3) \
   GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_)
 
-
-
 // Helper function for implementing {EXPECT|ASSERT}_PRED4.  Don't use
 // this in your code.
-template <typename Pred,
-          typename T1,
-          typename T2,
-          typename T3,
-          typename T4>
-AssertionResult AssertPred4Helper(const char* pred_text,
-                                  const char* e1,
-                                  const char* e2,
-                                  const char* e3,
-                                  const char* e4,
-                                  Pred pred,
-                                  const T1& v1,
-                                  const T2& v2,
-                                  const T3& v3,
-                                  const T4& v4) {
+template <typename Pred, typename T1, typename T2, typename T3, typename T4>
+AssertionResult AssertPred4Helper(const char* pred_text, const char* e1,
+                                  const char* e2, const char* e3,
+                                  const char* e4, Pred pred, const T1& v1,
+                                  const T2& v2, const T3& v3, const T4& v4) {
   if (pred(v1, v2, v3, v4)) return AssertionSuccess();
 
   return AssertionFailure()
@@ -257,23 +209,15 @@ AssertionResult AssertPred4Helper(const char* pred_text,
 
 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
 // Don't use this in your code.
-#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\
-  GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \
-                on_failure)
+#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure) \
+  GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), on_failure)
 
 // Internal macro for implementing {EXPECT|ASSERT}_PRED4.  Don't use
 // this in your code.
-#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\
-  GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \
-                                             #v1, \
-                                             #v2, \
-                                             #v3, \
-                                             #v4, \
-                                             pred, \
-                                             v1, \
-                                             v2, \
-                                             v3, \
-                                             v4), on_failure)
+#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)                        \
+  GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, #v1, #v2, #v3, #v4, pred, \
+                                             v1, v2, v3, v4),                 \
+                on_failure)
 
 // 4-ary predicate assertion macros.
 #define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
@@ -285,28 +229,15 @@ AssertionResult AssertPred4Helper(const char* pred_text,
 #define ASSERT_PRED4(pred, v1, v2, v3, v4) \
   GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
 
-
-
 // Helper function for implementing {EXPECT|ASSERT}_PRED5.  Don't use
 // this in your code.
-template <typename Pred,
-          typename T1,
-          typename T2,
-          typename T3,
-          typename T4,
+template <typename Pred, typename T1, typename T2, typename T3, typename T4,
           typename T5>
-AssertionResult AssertPred5Helper(const char* pred_text,
-                                  const char* e1,
-                                  const char* e2,
-                                  const char* e3,
-                                  const char* e4,
-                                  const char* e5,
-                                  Pred pred,
-                                  const T1& v1,
-                                  const T2& v2,
-                                  const T3& v3,
-                                  const T4& v4,
-                                  const T5& v5) {
+AssertionResult AssertPred5Helper(const char* pred_text, const char* e1,
+                                  const char* e2, const char* e3,
+                                  const char* e4, const char* e5, Pred pred,
+                                  const T1& v1, const T2& v2, const T3& v3,
+                                  const T4& v4, const T5& v5) {
   if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
 
   return AssertionFailure()
@@ -322,25 +253,16 @@ AssertionResult AssertPred5Helper(const char* pred_text,
 
 // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.
 // Don't use this in your code.
-#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\
+#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)  \
   GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \
                 on_failure)
 
 // Internal macro for implementing {EXPECT|ASSERT}_PRED5.  Don't use
 // this in your code.
-#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\
-  GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \
-                                             #v1, \
-                                             #v2, \
-                                             #v3, \
-                                             #v4, \
-                                             #v5, \
-                                             pred, \
-                                             v1, \
-                                             v2, \
-                                             v3, \
-                                             v4, \
-                                             v5), on_failure)
+#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)                   \
+  GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, #v1, #v2, #v3, #v4, #v5, \
+                                             pred, v1, v2, v3, v4, v5),      \
+                on_failure)
 
 // 5-ary predicate assertion macros.
 #define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
@@ -352,8 +274,6 @@ AssertionResult AssertPred5Helper(const char* pred_text,
 #define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \
   GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
 
-
-
 }  // namespace testing
 
 #endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
index 38b9d85a51efb747feb969a5cdcadb1c27b2f87e..1f37dc31c347228e21f2474e1dbf0aed6b988189 100644 (file)
@@ -27,9 +27,8 @@
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-//
-// Google C++ Testing and Mocking Framework definitions useful in production code.
-// GOOGLETEST_CM0003 DO NOT DELETE
+// Google C++ Testing and Mocking Framework definitions useful in production
+// code.
 
 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
@@ -55,7 +54,7 @@
 // Note: The test class must be in the same namespace as the class being tested.
 // For example, putting MyClassTest in an anonymous namespace will not work.
 
-#define FRIEND_TEST(test_case_name, test_name)\
-friend class test_case_name##_##test_name##_Test
+#define FRIEND_TEST(test_case_name, test_name) \
+  friend class test_case_name##_##test_name##_Test
 
 #endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
index ff391fb4e2b5765cac8c6943359b15bbd5f4f149..cb49e2c754c250ed975e371551267b938ebcdfa1 100644 (file)
@@ -15,18 +15,6 @@ The custom directory is an injection point for custom user configurations.
 
 The following macros can be defined:
 
-### Flag related macros:
-
-*   `GTEST_FLAG(flag_name)`
-*   `GTEST_USE_OWN_FLAGFILE_FLAG_` - Define to 0 when the system provides its
-    own flagfile flag parsing.
-*   `GTEST_DECLARE_bool_(name)`
-*   `GTEST_DECLARE_int32_(name)`
-*   `GTEST_DECLARE_string_(name)`
-*   `GTEST_DEFINE_bool_(name, default_val, doc)`
-*   `GTEST_DEFINE_int32_(name, default_val, doc)`
-*   `GTEST_DEFINE_string_(name, default_val, doc)`
-
 ### Logging:
 
 *   `GTEST_LOG_(severity)`
index 490296dfad2d00c4811eb49126ab2656961c778d..45580ae805c268d2fd97dc7995bb4fe2a3e5a43d 100644 (file)
 // 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.
-//
+
 // The Google C++ Testing and Mocking Framework (Google Test)
 //
 // This header file defines internal utilities needed for implementing
 // death tests.  They are subject to change without notice.
-// GOOGLETEST_CM0001 DO NOT DELETE
+
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
 
+#include <stdio.h>
+
+#include <memory>
+
 #include "gtest/gtest-matchers.h"
 #include "gtest/internal/gtest-internal.h"
 
-#include <stdio.h>
-#include <memory>
+GTEST_DECLARE_string_(internal_run_death_test);
 
 namespace testing {
 namespace internal {
 
-GTEST_DECLARE_string_(internal_run_death_test);
-
 // Names of the flags (needed for parsing Google Test flags).
 const char kDeathTestStyleFlag[] = "death_test_style";
 const char kDeathTestUseFork[] = "death_test_use_fork";
@@ -83,16 +87,18 @@ class GTEST_API_ DeathTest {
   static bool Create(const char* statement, Matcher<const std::string&> matcher,
                      const char* file, int line, DeathTest** test);
   DeathTest();
-  virtual ~DeathTest() { }
+  virtual ~DeathTest() {}
 
   // A helper class that aborts a death test when it's deleted.
   class ReturnSentinel {
    public:
-    explicit ReturnSentinel(DeathTest* test) : test_(test) { }
+    explicit ReturnSentinel(DeathTest* test) : test_(test) {}
     ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
+
    private:
     DeathTest* const test_;
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
+    ReturnSentinel(const ReturnSentinel&) = delete;
+    ReturnSentinel& operator=(const ReturnSentinel&) = delete;
   } GTEST_ATTRIBUTE_UNUSED_;
 
   // An enumeration of possible roles that may be taken when a death
@@ -137,7 +143,8 @@ class GTEST_API_ DeathTest {
   // A string containing a description of the outcome of the last death test.
   static std::string last_death_test_message_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
+  DeathTest(const DeathTest&) = delete;
+  DeathTest& operator=(const DeathTest&) = delete;
 };
 
 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
@@ -145,7 +152,7 @@ GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
 // Factory interface for death tests.  May be mocked out for testing.
 class DeathTestFactory {
  public:
-  virtual ~DeathTestFactory() { }
+  virtual ~DeathTestFactory() {}
   virtual bool Create(const char* statement,
                       Matcher<const std::string&> matcher, const char* file,
                       int line, DeathTest** test) = 0;
@@ -186,28 +193,28 @@ inline Matcher<const ::std::string&> MakeDeathTestMatcher(
 
 // Traps C++ exceptions escaping statement and reports them as test
 // failures. Note that trapping SEH exceptions is not implemented here.
-# if GTEST_HAS_EXCEPTIONS
-#  define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
-  try { \
-    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
-  } catch (const ::std::exception& gtest_exception) { \
-    fprintf(\
-        stderr, \
-        "\n%s: Caught std::exception-derived exception escaping the " \
-        "death test statement. Exception message: %s\n", \
+#if GTEST_HAS_EXCEPTIONS
+#define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test)           \
+  try {                                                                      \
+    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement);               \
+  } catch (const ::std::exception& gtest_exception) {                        \
+    fprintf(                                                                 \
+        stderr,                                                              \
+        "\n%s: Caught std::exception-derived exception escaping the "        \
+        "death test statement. Exception message: %s\n",                     \
         ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \
-        gtest_exception.what()); \
-    fflush(stderr); \
+        gtest_exception.what());                                             \
+    fflush(stderr);                                                          \
     death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
-  } catch (...) { \
+  } catch (...) {                                                            \
     death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
   }
 
-# else
-#  define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
+#else
+#define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
   GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
 
-# endif
+#endif
 
 // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
 // ASSERT_EXIT*, and EXPECT_EXIT*.
@@ -236,8 +243,6 @@ inline Matcher<const ::std::string&> MakeDeathTestMatcher(
           gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE);   \
           break;                                                               \
         }                                                                      \
-        default:                                                               \
-          break;                                                               \
       }                                                                        \
     }                                                                          \
   } else                                                                       \
@@ -265,16 +270,12 @@ inline Matcher<const ::std::string&> MakeDeathTestMatcher(
 // RUN_ALL_TESTS was called.
 class InternalRunDeathTestFlag {
  public:
-  InternalRunDeathTestFlag(const std::string& a_file,
-                           int a_line,
-                           int an_index,
+  InternalRunDeathTestFlag(const std::string& a_file, int a_line, int an_index,
                            int a_write_fd)
-      : file_(a_file), line_(a_line), index_(an_index),
-        write_fd_(a_write_fd) {}
+      : file_(a_file), line_(a_line), index_(an_index), write_fd_(a_write_fd) {}
 
   ~InternalRunDeathTestFlag() {
-    if (write_fd_ >= 0)
-      posix::Close(write_fd_);
+    if (write_fd_ >= 0) posix::Close(write_fd_);
   }
 
   const std::string& file() const { return file_; }
@@ -288,7 +289,8 @@ class InternalRunDeathTestFlag {
   int index_;
   int write_fd_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
+  InternalRunDeathTestFlag(const InternalRunDeathTestFlag&) = delete;
+  InternalRunDeathTestFlag& operator=(const InternalRunDeathTestFlag&) = delete;
 };
 
 // Returns a newly created InternalRunDeathTestFlag object with fields
index 0c033abc34e0036f39d582366ebe46cb66f2680c..a2a60a962b83813d19ecef5990375e0f41e4c65e 100644 (file)
@@ -26,7 +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.
-//
+
 // Google Test filepath utilities
 //
 // This header file declares classes and functions used internally by
@@ -35,7 +35,9 @@
 // This file is #included in gtest/internal/gtest-internal.h.
 // Do not include this header file separately!
 
-// GOOGLETEST_CM0001 DO NOT DELETE
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
@@ -61,8 +63,8 @@ namespace internal {
 
 class GTEST_API_ FilePath {
  public:
-  FilePath() : pathname_("") { }
-  FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { }
+  FilePath() : pathname_("") {}
+  FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) {}
 
   explicit FilePath(const std::string& pathname) : pathname_(pathname) {
     Normalize();
@@ -73,9 +75,7 @@ class GTEST_API_ FilePath {
     return *this;
   }
 
-  void Set(const FilePath& rhs) {
-    pathname_ = rhs.pathname_;
-  }
+  void Set(const FilePath& rhs) { pathname_ = rhs.pathname_; }
 
   const std::string& string() const { return pathname_; }
   const char* c_str() const { return pathname_.c_str(); }
@@ -88,8 +88,7 @@ class GTEST_API_ FilePath {
   // than zero (e.g., 12), returns "dir/test_12.xml".
   // On Windows platform, uses \ as the separator rather than /.
   static FilePath MakeFileName(const FilePath& directory,
-                               const FilePath& base_name,
-                               int number,
+                               const FilePath& base_name, int number,
                                const char* extension);
 
   // Given directory = "dir", relative_path = "test.xml",
index f8cbdbd81d9a4c6be040c47fdd8dc8622df061cd..9b04e4c85fabd1e3e3bcfcdc5497fad203e9ec4d 100644 (file)
 // 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.
-//
+
 // The Google C++ Testing and Mocking Framework (Google Test)
 //
 // This header file declares functions and macros used internally by
 // Google Test.  They are subject to change without notice.
 
-// GOOGLETEST_CM0001 DO NOT DELETE
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
 #include "gtest/internal/gtest-port.h"
 
 #if GTEST_OS_LINUX
-# include <stdlib.h>
-# include <sys/types.h>
-# include <sys/wait.h>
-# include <unistd.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
 #endif  // GTEST_OS_LINUX
 
 #if GTEST_HAS_EXCEPTIONS
-# include <stdexcept>
+#include <stdexcept>
 #endif
 
 #include <ctype.h>
 #include <float.h>
 #include <string.h>
+
 #include <cstdint>
 #include <iomanip>
 #include <limits>
@@ -76,7 +79,7 @@
 // the current line number.  For more details, see
 // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
-#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
+#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo##bar
 
 // Stringifies its argument.
 // Work around a bug in visual studio which doesn't accept code like this:
@@ -98,21 +101,21 @@ namespace testing {
 
 // Forward declarations.
 
-class AssertionResult;                 // Result of an assertion.
-class Message;                         // Represents a failure message.
-class Test;                            // Represents a test.
-class TestInfo;                        // Information about a test.
-class TestPartResult;                  // Result of a test part.
-class UnitTest;                        // A collection of test suites.
+class AssertionResult;  // Result of an assertion.
+class Message;          // Represents a failure message.
+class Test;             // Represents a test.
+class TestInfo;         // Information about a test.
+class TestPartResult;   // Result of a test part.
+class UnitTest;         // A collection of test suites.
 
 template <typename T>
 ::std::string PrintToString(const T& value);
 
 namespace internal {
 
-struct TraceInfo;                      // Information about a trace point.
-class TestInfoImpl;                    // Opaque implementation of TestInfo
-class UnitTestImpl;                    // Opaque implementation of UnitTest
+struct TraceInfo;    // Information about a trace point.
+class TestInfoImpl;  // Opaque implementation of TestInfo
+class UnitTestImpl;  // Opaque implementation of UnitTest
 
 // The text used in failure messages to indicate the start of the
 // stack trace.
@@ -121,6 +124,7 @@ GTEST_API_ extern const char kStackTraceMarker[];
 // An IgnoredValue object can be implicitly constructed from ANY value.
 class IgnoredValue {
   struct Sink {};
+
  public:
   // This constructor template allows any value to be implicitly
   // converted to IgnoredValue.  The object has no data member and
@@ -136,13 +140,13 @@ class IgnoredValue {
 };
 
 // Appends the user-supplied message to the Google-Test-generated message.
-GTEST_API_ std::string AppendUserMessage(
-    const std::string& gtest_msg, const Message& user_msg);
+GTEST_API_ std::string AppendUserMessage(const std::string& gtest_msg,
+                                         const Message& user_msg);
 
 #if GTEST_HAS_EXCEPTIONS
 
-GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \
-/* an exported class was derived from a class that was not exported */)
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(
+    4275 /* an exported class was derived from a class that was not exported */)
 
 // This exception is thrown by (and only by) a failed Google Test
 // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
@@ -181,14 +185,6 @@ GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,
 
 }  // namespace edit_distance
 
-// Calculate the diff between 'left' and 'right' and return it in unified diff
-// format.
-// If not null, stores in 'total_line_count' the total number of lines found
-// in left + right.
-GTEST_API_ std::string DiffStrings(const std::string& left,
-                                   const std::string& right,
-                                   size_t* total_line_count);
-
 // Constructs and returns the message for an equality assertion
 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
 //
@@ -212,10 +208,8 @@ GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
 
 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
 GTEST_API_ std::string GetBoolAssertionFailureMessage(
-    const AssertionResult& assertion_result,
-    const char* expression_text,
-    const char* actual_predicate_value,
-    const char* expected_predicate_value);
+    const AssertionResult& assertion_result, const char* expression_text,
+    const char* actual_predicate_value, const char* expected_predicate_value);
 
 // This template class represents an IEEE floating-point number
 // (either single-precision or double-precision, depending on the
@@ -256,11 +250,11 @@ class FloatingPoint {
   // Constants.
 
   // # of bits in a number.
-  static const size_t kBitCount = 8*sizeof(RawType);
+  static const size_t kBitCount = 8 * sizeof(RawType);
 
   // # of fraction bits in a number.
   static const size_t kFractionBitCount =
-    std::numeric_limits<RawType>::digits - 1;
+      std::numeric_limits<RawType>::digits - 1;
 
   // # of exponent bits in a number.
   static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
@@ -269,8 +263,8 @@ class FloatingPoint {
   static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
 
   // The mask for the fraction bits.
-  static const Bits kFractionBitMask =
-    ~static_cast<Bits>(0) >> (kExponentBitCount + 1);
+  static const Bits kFractionBitMask = ~static_cast<Bits>(0) >>
+                                       (kExponentBitCount + 1);
 
   // The mask for the exponent bits.
   static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
@@ -309,9 +303,7 @@ class FloatingPoint {
   }
 
   // Returns the floating-point number that represent positive infinity.
-  static RawType Infinity() {
-    return ReinterpretBits(kExponentBitMask);
-  }
+  static RawType Infinity() { return ReinterpretBits(kExponentBitMask); }
 
   // Returns the maximum representable finite floating-point number.
   static RawType Max();
@@ -319,7 +311,7 @@ class FloatingPoint {
   // Non-static methods
 
   // Returns the bits that represents this number.
-  const Bits &bits() const { return u_.bits_; }
+  const Bitsbits() const { return u_.bits_; }
 
   // Returns the exponent bits of this number.
   Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
@@ -348,8 +340,8 @@ class FloatingPoint {
     // a NAN must return false.
     if (is_nan() || rhs.is_nan()) return false;
 
-    return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)
-        <= kMaxUlps;
+    return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) <=
+           kMaxUlps;
   }
 
  private:
@@ -374,7 +366,7 @@ class FloatingPoint {
   //
   // Read http://en.wikipedia.org/wiki/Signed_number_representations
   // for more details on signed number representations.
-  static Bits SignAndMagnitudeToBiased(const Bits &sam) {
+  static Bits SignAndMagnitudeToBiased(const Bitssam) {
     if (kSignBitMask & sam) {
       // sam represents a negative number.
       return ~sam + 1;
@@ -386,8 +378,8 @@ class FloatingPoint {
 
   // Given two numbers in the sign-and-magnitude representation,
   // returns the distance between them as an unsigned number.
-  static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
-                                                     const Bits &sam2) {
+  static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bitssam1,
+                                                     const Bitssam2) {
     const Bits biased1 = SignAndMagnitudeToBiased(sam1);
     const Bits biased2 = SignAndMagnitudeToBiased(sam2);
     return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
@@ -399,9 +391,13 @@ class FloatingPoint {
 // We cannot use std::numeric_limits<T>::max() as it clashes with the max()
 // macro defined by <windows.h>.
 template <>
-inline float FloatingPoint<float>::Max() { return FLT_MAX; }
+inline float FloatingPoint<float>::Max() {
+  return FLT_MAX;
+}
 template <>
-inline double FloatingPoint<double>::Max() { return DBL_MAX; }
+inline double FloatingPoint<double>::Max() {
+  return DBL_MAX;
+}
 
 // Typedefs the instances of the FloatingPoint template class that we
 // care to use.
@@ -461,7 +457,8 @@ class TestFactoryBase {
   TestFactoryBase() {}
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
+  TestFactoryBase(const TestFactoryBase&) = delete;
+  TestFactoryBase& operator=(const TestFactoryBase&) = delete;
 };
 
 // This class provides implementation of TeastFactoryBase interface.
@@ -510,11 +507,11 @@ inline SetUpTearDownSuiteFuncType GetNotDefaultOrNull(
 
 template <typename T>
 //  Note that SuiteApiResolver inherits from T because
-//  SetUpTestSuite()/TearDownTestSuite() could be protected. Ths way
+//  SetUpTestSuite()/TearDownTestSuite() could be protected. This way
 //  SuiteApiResolver can access them.
 struct SuiteApiResolver : T {
   // testing::Test is only forward declared at this point. So we make it a
-  // dependend class for the compiler to be OK with it.
+  // dependent class for the compiler to be OK with it.
   using Test =
       typename std::conditional<sizeof(T) != 0, ::testing::Test, void>::type;
 
@@ -654,7 +651,8 @@ inline const char* SkipComma(const char* str) {
   if (comma == nullptr) {
     return nullptr;
   }
-  while (IsSpace(*(++comma))) {}
+  while (IsSpace(*(++comma))) {
+  }
   return comma;
 }
 
@@ -668,7 +666,7 @@ inline std::string GetPrefixUntilComma(const char* str) {
 // Splits a given string on a given delimiter, populating a given
 // vector with the fields.
 void SplitString(const ::std::string& str, char delimiter,
-                 ::std::vector< ::std::string>* dest);
+                 ::std::vector<::std::string>* dest);
 
 // The default argument to the template below for the case when the user does
 // not provide a name generator.
@@ -781,13 +779,13 @@ class TypeParameterizedTestSuite {
                        const std::vector<std::string>& type_names =
                            GenerateNames<DefaultNameGenerator, Types>()) {
     RegisterTypeParameterizedTestSuiteInstantiation(case_name);
-    std::string test_name = StripTrailingSpaces(
-        GetPrefixUntilComma(test_names));
+    std::string test_name =
+        StripTrailingSpaces(GetPrefixUntilComma(test_names));
     if (!state->TestExists(test_name)) {
       fprintf(stderr, "Failed to get code location for test %s.%s at %s.",
               case_name, test_name.c_str(),
-              FormatFileLocation(code_location.file.c_str(),
-                                 code_location.line).c_str());
+              FormatFileLocation(code_location.file.c_str(), code_location.line)
+                  .c_str());
       fflush(stderr);
       posix::Abort();
     }
@@ -831,8 +829,8 @@ class TypeParameterizedTestSuite<Fixture, internal::None, Types> {
 // For example, if Foo() calls Bar(), which in turn calls
 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
-GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(
-    UnitTest* unit_test, int skip_count);
+GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(UnitTest* unit_test,
+                                                       int skip_count);
 
 // Helpers for suppressing warnings on unreachable code or constant
 // condition.
@@ -881,7 +879,8 @@ class GTEST_API_ Random {
 
  private:
   uint32_t state_;
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
+  Random(const Random&) = delete;
+  Random& operator=(const Random&) = delete;
 };
 
 // Turns const U&, U&, const U, and U all into U.
@@ -954,7 +953,9 @@ IsContainer IsContainerTest(int /* dummy */) {
 
 typedef char IsNotContainer;
 template <class C>
-IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; }
+IsNotContainer IsContainerTest(long /* dummy */) {
+  return '\0';
+}
 
 // Trait to detect whether a type T is a hash table.
 // The heuristic used is that the type contains an inner type `hasher` and does
@@ -1017,11 +1018,13 @@ bool ArrayEq(const T* lhs, size_t size, const U* rhs);
 
 // This generic version is used when k is 0.
 template <typename T, typename U>
-inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; }
+inline bool ArrayEq(const T& lhs, const U& rhs) {
+  return lhs == rhs;
+}
 
 // This overload is used when k >= 1.
 template <typename T, typename U, size_t N>
-inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) {
+inline bool ArrayEq(const T (&lhs)[N], const U (&rhs)[N]) {
   return internal::ArrayEq(lhs, N, rhs);
 }
 
@@ -1031,8 +1034,7 @@ inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) {
 template <typename T, typename U>
 bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
   for (size_t i = 0; i != size; i++) {
-    if (!internal::ArrayEq(lhs[i], rhs[i]))
-      return false;
+    if (!internal::ArrayEq(lhs[i], rhs[i])) return false;
   }
   return true;
 }
@@ -1042,8 +1044,7 @@ bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
 template <typename Iter, typename Element>
 Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
   for (Iter it = begin; it != end; ++it) {
-    if (internal::ArrayEq(*it, elem))
-      return it;
+    if (internal::ArrayEq(*it, elem)) return it;
   }
   return end;
 }
@@ -1057,11 +1058,13 @@ void CopyArray(const T* from, size_t size, U* to);
 
 // This generic version is used when k is 0.
 template <typename T, typename U>
-inline void CopyArray(const T& from, U* to) { *to = from; }
+inline void CopyArray(const T& from, U* to) {
+  *to = from;
+}
 
 // This overload is used when k >= 1.
 template <typename T, typename U, size_t N>
-inline void CopyArray(const T(&from)[N], U(*to)[N]) {
+inline void CopyArray(const T (&from)[N], U (*to)[N]) {
   internal::CopyArray(from, N, *to);
 }
 
@@ -1114,8 +1117,7 @@ class NativeArray {
   }
 
   ~NativeArray() {
-    if (clone_ != &NativeArray::InitRef)
-      delete[] array_;
+    if (clone_ != &NativeArray::InitRef) delete[] array_;
   }
 
   // STL-style container methods.
@@ -1123,8 +1125,7 @@ class NativeArray {
   const_iterator begin() const { return array_; }
   const_iterator end() const { return array_ + size_; }
   bool operator==(const NativeArray& rhs) const {
-    return size() == rhs.size() &&
-        ArrayEq(begin(), size(), rhs.begin());
+    return size() == rhs.size() && ArrayEq(begin(), size(), rhs.begin());
   }
 
  private:
@@ -1335,9 +1336,9 @@ struct tuple_size<testing::internal::FlatTuple<Ts...>>
 #endif
 }  // namespace std
 
-#define GTEST_MESSAGE_AT_(file, line, message, result_type) \
-  ::testing::internal::AssertHelper(result_type, file, line, message) \
-    = ::testing::Message()
+#define GTEST_MESSAGE_AT_(file, line, message, result_type)             \
+  ::testing::internal::AssertHelper(result_type, file, line, message) \
+      ::testing::Message()
 
 #define GTEST_MESSAGE_(message, result_type) \
   GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
@@ -1458,103 +1459,112 @@ class NeverThrown {
 
 #endif  // GTEST_HAS_EXCEPTIONS
 
-#define GTEST_TEST_NO_THROW_(statement, fail) \
-  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
-  if (::testing::internal::TrueWithString gtest_msg{}) { \
-    try { \
-      GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
-    } \
-    GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
-    catch (...) { \
-      gtest_msg.value = "it throws."; \
-      goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
-    } \
-  } else \
-    GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
-      fail(("Expected: " #statement " doesn't throw an exception.\n" \
-            "  Actual: " + gtest_msg.value).c_str())
-
-#define GTEST_TEST_ANY_THROW_(statement, fail) \
-  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
-  if (::testing::internal::AlwaysTrue()) { \
-    bool gtest_caught_any = false; \
-    try { \
-      GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
-    } \
-    catch (...) { \
-      gtest_caught_any = true; \
-    } \
-    if (!gtest_caught_any) { \
+#define GTEST_TEST_NO_THROW_(statement, fail)                            \
+  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                          \
+  if (::testing::internal::TrueWithString gtest_msg{}) {                 \
+    try {                                                                \
+      GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement);         \
+    }                                                                    \
+    GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_()                           \
+    catch (...) {                                                        \
+      gtest_msg.value = "it throws.";                                    \
+      goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__);      \
+    }                                                                    \
+  } else                                                                 \
+    GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__)              \
+        : fail(("Expected: " #statement " doesn't throw an exception.\n" \
+                "  Actual: " +                                           \
+                gtest_msg.value)                                         \
+                   .c_str())
+
+#define GTEST_TEST_ANY_THROW_(statement, fail)                       \
+  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                      \
+  if (::testing::internal::AlwaysTrue()) {                           \
+    bool gtest_caught_any = false;                                   \
+    try {                                                            \
+      GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement);     \
+    } catch (...) {                                                  \
+      gtest_caught_any = true;                                       \
+    }                                                                \
+    if (!gtest_caught_any) {                                         \
       goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
-    } \
-  } else \
-    GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
-      fail("Expected: " #statement " throws an exception.\n" \
-           "  Actual: it doesn't.")
-
+    }                                                                \
+  } else                                                             \
+    GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__)         \
+        : fail("Expected: " #statement                               \
+               " throws an exception.\n"                             \
+               "  Actual: it doesn't.")
 
 // Implements Boolean test assertions such as EXPECT_TRUE. expression can be
 // either a boolean expression or an AssertionResult. text is a textual
 // representation of expression as it was passed into the EXPECT_TRUE.
 #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
-  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
-  if (const ::testing::AssertionResult gtest_ar_ = \
-      ::testing::AssertionResult(expression)) \
-    ; \
-  else \
-    fail(::testing::internal::GetBoolAssertionFailureMessage(\
-        gtest_ar_, text, #actual, #expected).c_str())
-
-#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
-  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
-  if (::testing::internal::AlwaysTrue()) { \
+  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                       \
+  if (const ::testing::AssertionResult gtest_ar_ =                    \
+          ::testing::AssertionResult(expression))                     \
+    ;                                                                 \
+  else                                                                \
+    fail(::testing::internal::GetBoolAssertionFailureMessage(         \
+             gtest_ar_, text, #actual, #expected)                     \
+             .c_str())
+
+#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail)                          \
+  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                                \
+  if (::testing::internal::AlwaysTrue()) {                                     \
     ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
-    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
-    if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
-      goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
-    } \
-  } else \
-    GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
-      fail("Expected: " #statement " doesn't generate new fatal " \
-           "failures in the current thread.\n" \
-           "  Actual: it does.")
+    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement);                 \
+    if (gtest_fatal_failure_checker.has_new_fatal_failure()) {                 \
+      goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__);            \
+    }                                                                          \
+  } else                                                                       \
+    GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__)                    \
+        : fail("Expected: " #statement                                         \
+               " doesn't generate new fatal "                                  \
+               "failures in the current thread.\n"                             \
+               "  Actual: it does.")
 
 // Expands to the name of the class that implements the given test.
 #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
   test_suite_name##_##test_name##_Test
 
 // Helper macro for defining tests.
-#define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id)      \
-  static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1,                \
-                "test_suite_name must not be empty");                         \
-  static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1,                      \
-                "test_name must not be empty");                               \
-  class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)                    \
-      : public parent_class {                                                 \
-   public:                                                                    \
-    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default;           \
-    ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name,   \
-                                                           test_name));       \
-    GTEST_DISALLOW_MOVE_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name,   \
-                                                           test_name));       \
-                                                                              \
-   private:                                                                   \
-    void TestBody() override;                                                 \
-    static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;     \
-  };                                                                          \
-                                                                              \
-  ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name,          \
-                                                    test_name)::test_info_ =  \
-      ::testing::internal::MakeAndRegisterTestInfo(                           \
-          #test_suite_name, #test_name, nullptr, nullptr,                     \
-          ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \
-          ::testing::internal::SuiteApiResolver<                              \
-              parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__),         \
-          ::testing::internal::SuiteApiResolver<                              \
-              parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__),      \
-          new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_(    \
-              test_suite_name, test_name)>);                                  \
+#define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id)       \
+  static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1,                 \
+                "test_suite_name must not be empty");                          \
+  static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1,                       \
+                "test_name must not be empty");                                \
+  class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)                     \
+      : public parent_class {                                                  \
+   public:                                                                     \
+    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default;            \
+    ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default;  \
+    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)                         \
+    (const GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &) = delete;     \
+    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=(            \
+        const GTEST_TEST_CLASS_NAME_(test_suite_name,                          \
+                                     test_name) &) = delete; /* NOLINT */      \
+    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)                         \
+    (GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &&) noexcept = delete; \
+    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=(            \
+        GTEST_TEST_CLASS_NAME_(test_suite_name,                                \
+                               test_name) &&) noexcept = delete; /* NOLINT */  \
+                                                                               \
+   private:                                                                    \
+    void TestBody() override;                                                  \
+    static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;      \
+  };                                                                           \
+                                                                               \
+  ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name,           \
+                                                    test_name)::test_info_ =   \
+      ::testing::internal::MakeAndRegisterTestInfo(                            \
+          #test_suite_name, #test_name, nullptr, nullptr,                      \
+          ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id),  \
+          ::testing::internal::SuiteApiResolver<                               \
+              parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__),          \
+          ::testing::internal::SuiteApiResolver<                               \
+              parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__),       \
+          new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_(     \
+              test_suite_name, test_name)>);                                   \
   void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
 
 #endif  // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
index c2ef6e3124b05f4be2459b62d463b2b910e5c294..e7af2f904a4c37e5e01768bbc9d12d423096ff8f 100644 (file)
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-
 // Type and function utilities for implementing parameterized tests.
 
-// GOOGLETEST_CM0001 DO NOT DELETE
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
 #include <utility>
 #include <vector>
 
-#include "gtest/internal/gtest-internal.h"
-#include "gtest/internal/gtest-port.h"
 #include "gtest/gtest-printers.h"
 #include "gtest/gtest-test-part.h"
+#include "gtest/internal/gtest-internal.h"
+#include "gtest/internal/gtest-port.h"
 
 namespace testing {
 // Input to a parameterized test name generator, describing a test parameter.
 // Consists of the parameter value and the integer parameter index.
 template <class ParamType>
 struct TestParamInfo {
-  TestParamInfo(const ParamType& a_param, size_t an_index) :
-    param(a_param),
-    index(an_index) {}
+  TestParamInfo(const ParamType& a_param, size_t an_index)
+      : param(a_param), index(an_index) {}
   ParamType param;
   size_t index;
 };
@@ -84,8 +84,10 @@ namespace internal {
 GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,
                                            CodeLocation code_location);
 
-template <typename> class ParamGeneratorInterface;
-template <typename> class ParamGenerator;
+template <typename>
+class ParamGeneratorInterface;
+template <typename>
+class ParamGenerator;
 
 // Interface for iterating over elements provided by an implementation
 // of ParamGeneratorInterface<T>.
@@ -129,8 +131,7 @@ class ParamIterator {
   // ParamIterator assumes ownership of the impl_ pointer.
   ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}
   ParamIterator& operator=(const ParamIterator& other) {
-    if (this != &other)
-      impl_.reset(other.impl_->Clone());
+    if (this != &other) impl_.reset(other.impl_->Clone());
     return *this;
   }
 
@@ -157,7 +158,7 @@ class ParamIterator {
  private:
   friend class ParamGenerator<T>;
   explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}
-  std::unique_ptr<ParamIteratorInterface<T> > impl_;
+  std::unique_ptr<ParamIteratorInterface<T>> impl_;
 };
 
 // ParamGeneratorInterface<T> is the binary interface to access generators
@@ -179,7 +180,7 @@ class ParamGeneratorInterface {
 // This class implements copy initialization semantics and the contained
 // ParamGeneratorInterface<T> instance is shared among all copies
 // of the original object. This is possible because that instance is immutable.
-template<typename T>
+template <typename T>
 class ParamGenerator {
  public:
   typedef ParamIterator<T> iterator;
@@ -196,7 +197,7 @@ class ParamGenerator {
   iterator end() const { return iterator(impl_->End()); }
 
  private:
-  std::shared_ptr<const ParamGeneratorInterface<T> > impl_;
+  std::shared_ptr<const ParamGeneratorInterface<T>> impl_;
 };
 
 // Generates values from a range of two comparable values. Can be used to
@@ -207,8 +208,10 @@ template <typename T, typename IncrementT>
 class RangeGenerator : public ParamGeneratorInterface<T> {
  public:
   RangeGenerator(T begin, T end, IncrementT step)
-      : begin_(begin), end_(end),
-        step_(step), end_index_(CalculateEndIndex(begin, end, step)) {}
+      : begin_(begin),
+        end_(end),
+        step_(step),
+        end_index_(CalculateEndIndex(begin, end, step)) {}
   ~RangeGenerator() override {}
 
   ParamIteratorInterface<T>* Begin() const override {
@@ -251,7 +254,9 @@ class RangeGenerator : public ParamGeneratorInterface<T> {
    private:
     Iterator(const Iterator& other)
         : ParamIteratorInterface<T>(),
-          base_(other.base_), value_(other.value_), index_(other.index_),
+          base_(other.base_),
+          value_(other.value_),
+          index_(other.index_),
           step_(other.step_) {}
 
     // No implementation - assignment is unsupported.
@@ -263,12 +268,10 @@ class RangeGenerator : public ParamGeneratorInterface<T> {
     const IncrementT step_;
   };  // class RangeGenerator::Iterator
 
-  static int CalculateEndIndex(const T& begin,
-                               const T& end,
+  static int CalculateEndIndex(const T& begin, const T& end,
                                const IncrementT& step) {
     int end_index = 0;
-    for (T i = begin; i < end; i = static_cast<T>(i + step))
-      end_index++;
+    for (T i = begin; i < end; i = static_cast<T>(i + step)) end_index++;
     return end_index;
   }
 
@@ -283,7 +286,6 @@ class RangeGenerator : public ParamGeneratorInterface<T> {
   const int end_index_;
 };  // class RangeGenerator
 
-
 // Generates values from a pair of STL-style iterators. Used in the
 // ValuesIn() function. The elements are copied from the source range
 // since the source can be located on the stack, and the generator
@@ -341,13 +343,13 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
           << "The program attempted to compare iterators "
           << "from different generators." << std::endl;
       return iterator_ ==
-          CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
+             CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
     }
 
    private:
     Iterator(const Iterator& other)
-          // The explicit constructor call suppresses a false warning
-          // emitted by gcc when supplied with the -Wextra option.
+        // The explicit constructor call suppresses a false warning
+        // emitted by gcc when supplied with the -Wextra option.
         : ParamIteratorInterface<T>(),
           base_(other.base_),
           iterator_(other.iterator_) {}
@@ -394,8 +396,8 @@ template <class TestClass>
 class ParameterizedTestFactory : public TestFactoryBase {
  public:
   typedef typename TestClass::ParamType ParamType;
-  explicit ParameterizedTestFactory(ParamType parameter) :
-      parameter_(parameter) {}
+  explicit ParameterizedTestFactory(ParamType parameter)
+      parameter_(parameter) {}
   Test* CreateTest() override {
     TestClass::SetParam(&parameter_);
     return new TestClass();
@@ -404,7 +406,8 @@ class ParameterizedTestFactory : public TestFactoryBase {
  private:
   const ParamType parameter_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
+  ParameterizedTestFactory(const ParameterizedTestFactory&) = delete;
+  ParameterizedTestFactory& operator=(const ParameterizedTestFactory&) = delete;
 };
 
 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
@@ -440,7 +443,8 @@ class TestMetaFactory
   }
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory);
+  TestMetaFactory(const TestMetaFactory&) = delete;
+  TestMetaFactory& operator=(const TestMetaFactory&) = delete;
 };
 
 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
@@ -471,7 +475,10 @@ class ParameterizedTestSuiteInfoBase {
   ParameterizedTestSuiteInfoBase() {}
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase);
+  ParameterizedTestSuiteInfoBase(const ParameterizedTestSuiteInfoBase&) =
+      delete;
+  ParameterizedTestSuiteInfoBase& operator=(
+      const ParameterizedTestSuiteInfoBase&) = delete;
 };
 
 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
@@ -547,8 +554,8 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
          test_it != tests_.end(); ++test_it) {
       std::shared_ptr<TestInfo> test_info = *test_it;
       for (typename InstantiationContainer::iterator gen_it =
-               instantiations_.begin(); gen_it != instantiations_.end();
-               ++gen_it) {
+               instantiations_.begin();
+           gen_it != instantiations_.end(); ++gen_it) {
         const std::string& instantiation_name = gen_it->name;
         ParamGenerator<ParamType> generator((*gen_it->generator)());
         ParamNameGeneratorFunc* name_func = gen_it->name_func;
@@ -556,7 +563,7 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
         int line = gen_it->line;
 
         std::string test_suite_name;
-        if ( !instantiation_name.empty() )
+        if (!instantiation_name.empty())
           test_suite_name = instantiation_name + "/";
         test_suite_name += test_info->test_suite_base_name;
 
@@ -569,17 +576,16 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
 
           Message test_name_stream;
 
-          std::string param_name = name_func(
-              TestParamInfo<ParamType>(*param_it, i));
+          std::string param_name =
+              name_func(TestParamInfo<ParamType>(*param_it, i));
 
           GTEST_CHECK_(IsValidParamName(param_name))
               << "Parameterized test name '" << param_name
-              << "' is invalid, in " << file
-              << " line " << line << std::endl;
+              << "' is invalid, in " << file << " line " << line << std::endl;
 
           GTEST_CHECK_(test_param_names.count(param_name) == 0)
-              << "Duplicate parameterized test name '" << param_name
-              << "', in " << file << " line " << line << std::endl;
+              << "Duplicate parameterized test name '" << param_name << "', in "
+              << file << " line " << line << std::endl;
 
           test_param_names.insert(param_name);
 
@@ -596,15 +602,15 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
               SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),
               test_info->test_meta_factory->CreateTestFactory(*param_it));
         }  // for param_it
-      }  // for gen_it
-    }  // for test_it
+      }    // for gen_it
+    }      // for test_it
 
     if (!generated_instantiations) {
       // There are no generaotrs, or they all generate nothing ...
       InsertSyntheticTestCase(GetTestSuiteName(), code_location_,
                               !tests_.empty());
     }
-  }    // RegisterTests
+  }  // RegisterTests
 
  private:
   // LocalTestInfo structure keeps information about a single test registered
@@ -620,42 +626,39 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
 
     const std::string test_suite_base_name;
     const std::string test_base_name;
-    const std::unique_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
+    const std::unique_ptr<TestMetaFactoryBase<ParamType>> test_meta_factory;
     const CodeLocation code_location;
   };
-  using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo> >;
+  using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo>>;
   // Records data received from INSTANTIATE_TEST_SUITE_P macros:
   //  <Instantiation name, Sequence generator creation function,
   //     Name generator function, Source file, Source line>
   struct InstantiationInfo {
-      InstantiationInfo(const std::string &name_in,
-                        GeneratorCreationFunc* generator_in,
-                        ParamNameGeneratorFunc* name_func_in,
-                        const char* file_in,
-                        int line_in)
-          : name(name_in),
-            generator(generator_in),
-            name_func(name_func_in),
-            file(file_in),
-            line(line_in) {}
-
-      std::string name;
-      GeneratorCreationFunc* generator;
-      ParamNameGeneratorFunc* name_func;
-      const char* file;
-      int line;
+    InstantiationInfo(const std::string& name_in,
+                      GeneratorCreationFunc* generator_in,
+                      ParamNameGeneratorFunc* name_func_in, const char* file_in,
+                      int line_in)
+        : name(name_in),
+          generator(generator_in),
+          name_func(name_func_in),
+          file(file_in),
+          line(line_in) {}
+
+    std::string name;
+    GeneratorCreationFunc* generator;
+    ParamNameGeneratorFunc* name_func;
+    const char* file;
+    int line;
   };
   typedef ::std::vector<InstantiationInfo> InstantiationContainer;
 
   static bool IsValidParamName(const std::string& name) {
     // Check for empty string
-    if (name.empty())
-      return false;
+    if (name.empty()) return false;
 
     // Check for invalid characters
     for (std::string::size_type index = 0; index < name.size(); ++index) {
-      if (!IsAlNum(name[index]) && name[index] != '_')
-        return false;
+      if (!IsAlNum(name[index]) && name[index] != '_') return false;
     }
 
     return true;
@@ -666,7 +669,9 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
   TestInfoContainer tests_;
   InstantiationContainer instantiations_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfo);
+  ParameterizedTestSuiteInfo(const ParameterizedTestSuiteInfo&) = delete;
+  ParameterizedTestSuiteInfo& operator=(const ParameterizedTestSuiteInfo&) =
+      delete;
 };  // class ParameterizedTestSuiteInfo
 
 //  Legacy API is deprecated but still available
@@ -709,7 +714,7 @@ class ParameterizedTestSuiteRegistry {
           // type we are looking for, so we downcast it to that type
           // without further checks.
           typed_test_info = CheckedDowncastToActualType<
-              ParameterizedTestSuiteInfo<TestSuite> >(test_suite_info);
+              ParameterizedTestSuiteInfo<TestSuite>>(test_suite_info);
         }
         break;
       }
@@ -741,7 +746,10 @@ class ParameterizedTestSuiteRegistry {
 
   TestSuiteInfoContainer test_suite_infos_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry);
+  ParameterizedTestSuiteRegistry(const ParameterizedTestSuiteRegistry&) =
+      delete;
+  ParameterizedTestSuiteRegistry& operator=(
+      const ParameterizedTestSuiteRegistry&) = delete;
 };
 
 // Keep track of what type-parameterized test suite are defined and
@@ -836,7 +844,8 @@ class CartesianProductGenerator
       : public ParamIteratorInterface<ParamType> {
    public:
     IteratorImpl(const ParamGeneratorInterface<ParamType>* base,
-             const std::tuple<ParamGenerator<T>...>& generators, bool is_end)
+                 const std::tuple<ParamGenerator<T>...>& generators,
+                 bool is_end)
         : base_(base),
           begin_(std::get<I>(generators).begin()...),
           end_(std::get<I>(generators).end()...),
index dd845915e3ca75abe421d828c35271927e1ca810..f025db76ad371713a12ec29145ddb0dc9e655203 100644 (file)
@@ -26,7 +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.
-//
+
 // The Google C++ Testing and Mocking Framework (Google Test)
 //
 // This header file defines the GTEST_OS_* macro.
 
 // Determines the platform on which Google Test is compiled.
 #ifdef __CYGWIN__
-# define GTEST_OS_CYGWIN 1
-# elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__)
-#  define GTEST_OS_WINDOWS_MINGW 1
-#  define GTEST_OS_WINDOWS 1
+#define GTEST_OS_CYGWIN 1
+#elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__)
+#define GTEST_OS_WINDOWS_MINGW 1
+#define GTEST_OS_WINDOWS 1
 #elif defined _WIN32
-# define GTEST_OS_WINDOWS 1
-# ifdef _WIN32_WCE
-#  define GTEST_OS_WINDOWS_MOBILE 1
-# elif defined(WINAPI_FAMILY)
-#  include <winapifamily.h>
-#  if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
-#   define GTEST_OS_WINDOWS_DESKTOP 1
-#  elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
-#   define GTEST_OS_WINDOWS_PHONE 1
-#  elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
-#   define GTEST_OS_WINDOWS_RT 1
-#  elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE)
-#   define GTEST_OS_WINDOWS_PHONE 1
-#   define GTEST_OS_WINDOWS_TV_TITLE 1
-#  else
-    // WINAPI_FAMILY defined but no known partition matched.
-    // Default to desktop.
-#   define GTEST_OS_WINDOWS_DESKTOP 1
-#  endif
-# else
-#  define GTEST_OS_WINDOWS_DESKTOP 1
-# endif  // _WIN32_WCE
+#define GTEST_OS_WINDOWS 1
+#ifdef _WIN32_WCE
+#define GTEST_OS_WINDOWS_MOBILE 1
+#elif defined(WINAPI_FAMILY)
+#include <winapifamily.h>
+#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
+#define GTEST_OS_WINDOWS_DESKTOP 1
+#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
+#define GTEST_OS_WINDOWS_PHONE 1
+#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
+#define GTEST_OS_WINDOWS_RT 1
+#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE)
+#define GTEST_OS_WINDOWS_PHONE 1
+#define GTEST_OS_WINDOWS_TV_TITLE 1
+#else
+// WINAPI_FAMILY defined but no known partition matched.
+// Default to desktop.
+#define GTEST_OS_WINDOWS_DESKTOP 1
+#endif
+#else
+#define GTEST_OS_WINDOWS_DESKTOP 1
+#endif  // _WIN32_WCE
 #elif defined __OS2__
-# define GTEST_OS_OS2 1
+#define GTEST_OS_OS2 1
 #elif defined __APPLE__
-# define GTEST_OS_MAC 1
-# include <TargetConditionals.h>
-# if TARGET_OS_IPHONE
-#  define GTEST_OS_IOS 1
-# endif
+#define GTEST_OS_MAC 1
+#include <TargetConditionals.h>
+#if TARGET_OS_IPHONE
+#define GTEST_OS_IOS 1
+#endif
 #elif defined __DragonFly__
-# define GTEST_OS_DRAGONFLY 1
+#define GTEST_OS_DRAGONFLY 1
 #elif defined __FreeBSD__
-# define GTEST_OS_FREEBSD 1
+#define GTEST_OS_FREEBSD 1
 #elif defined __Fuchsia__
-# define GTEST_OS_FUCHSIA 1
+#define GTEST_OS_FUCHSIA 1
+#elif defined(__GNU__)
+#define GTEST_OS_GNU_HURD 1
 #elif defined(__GLIBC__) && defined(__FreeBSD_kernel__)
-# define GTEST_OS_GNU_KFREEBSD 1
+#define GTEST_OS_GNU_KFREEBSD 1
 #elif defined __linux__
-# define GTEST_OS_LINUX 1
-# if defined __ANDROID__
-#  define GTEST_OS_LINUX_ANDROID 1
-# endif
+#define GTEST_OS_LINUX 1
+#if defined __ANDROID__
+#define GTEST_OS_LINUX_ANDROID 1
+#endif
 #elif defined __MVS__
-# define GTEST_OS_ZOS 1
+#define GTEST_OS_ZOS 1
 #elif defined(__sun) && defined(__SVR4)
-# define GTEST_OS_SOLARIS 1
+#define GTEST_OS_SOLARIS 1
 #elif defined(_AIX)
-# define GTEST_OS_AIX 1
+#define GTEST_OS_AIX 1
 #elif defined(__hpux)
-# define GTEST_OS_HPUX 1
+#define GTEST_OS_HPUX 1
 #elif defined __native_client__
-# define GTEST_OS_NACL 1
+#define GTEST_OS_NACL 1
 #elif defined __NetBSD__
-# define GTEST_OS_NETBSD 1
+#define GTEST_OS_NETBSD 1
 #elif defined __OpenBSD__
-# define GTEST_OS_OPENBSD 1
+#define GTEST_OS_OPENBSD 1
 #elif defined __QNX__
-# define GTEST_OS_QNX 1
+#define GTEST_OS_QNX 1
 #elif defined(__HAIKU__)
 #define GTEST_OS_HAIKU 1
 #elif defined ESP8266
index 0953a781c05514dea7461a49dd6b6d52587e800f..0003d276589db7840a1fa86f2a1ead4985670edf 100644 (file)
@@ -26,7 +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.
-//
+
 // Low-level types and utilities for porting Google Test to various
 // platforms.  All macros ending with _ and symbols defined in an
 // internal namespace are subject to change without notice.  Code
@@ -38,7 +38,9 @@
 // files are expected to #include this.  Therefore, it cannot #include
 // any other Google Test header.
 
-// GOOGLETEST_CM0001 DO NOT DELETE
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
 //   GTEST_OS_DRAGONFLY - DragonFlyBSD
 //   GTEST_OS_FREEBSD  - FreeBSD
 //   GTEST_OS_FUCHSIA  - Fuchsia
+//   GTEST_OS_GNU_HURD - GNU/Hurd
 //   GTEST_OS_GNU_KFREEBSD - GNU/kFreeBSD
 //   GTEST_OS_HAIKU    - Haiku
 //   GTEST_OS_HPUX     - HP-UX
 //   GTEST_HAS_TYPED_TEST   - typed tests
 //   GTEST_HAS_TYPED_TEST_P - type-parameterized tests
 //   GTEST_IS_THREADSAFE    - Google Test is thread-safe.
-//   GOOGLETEST_CM0007 DO NOT DELETE
+//   GTEST_USES_RE2         - the RE2 regular expression library is used
 //   GTEST_USES_POSIX_RE    - enhanced POSIX regex is used. Do not confuse with
 //                            GTEST_HAS_POSIX_RE (see above) which users can
 //                            define themselves.
 //   GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
 //   GTEST_ATTRIBUTE_UNUSED_  - declares that a class' instances or a
 //                              variable don't have to be used.
-//   GTEST_DISALLOW_ASSIGN_   - disables copy operator=.
-//   GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=.
-//   GTEST_DISALLOW_MOVE_ASSIGN_   - disables move operator=.
-//   GTEST_DISALLOW_MOVE_AND_ASSIGN_ - disables move ctor and operator=.
 //   GTEST_MUST_USE_RESULT_   - declares that a function's result must be used.
 //   GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is
 //                                        suppressed (constant conditional).
 //                            - synchronization primitives.
 //
 // Regular expressions:
-//   RE             - a simple regular expression class using the POSIX
-//                    Extended Regular Expression syntax on UNIX-like platforms
-//                    GOOGLETEST_CM0008 DO NOT DELETE
-//                    or a reduced regular exception syntax on other
-//                    platforms, including Windows.
+//   RE             - a simple regular expression class using
+//                     1) the RE2 syntax on all platforms when built with RE2
+//                        and Abseil as dependencies
+//                     2) the POSIX Extended Regular Expression syntax on
+//                        UNIX-like platforms,
+//                     3) A reduced regular exception syntax on other platforms,
+//                        including Windows.
 // Logging:
 //   GTEST_LOG_()   - logs messages at the specified severity level.
 //   LogToStderr()  - directs all log messages to stderr.
 //   BiggestInt     - the biggest signed integer type.
 //
 // Command-line utilities:
-//   GTEST_DECLARE_*()  - declares a flag.
-//   GTEST_DEFINE_*()   - defines a flag.
 //   GetInjectableArgvs() - returns the command line as a vector of strings.
 //
 // Environment variable utilities:
 #include <string.h>
 
 #include <cerrno>
+// #include <condition_variable>  // Guarded by GTEST_IS_THREADSAFE below
 #include <cstdint>
+#include <iostream>
 #include <limits>
+#include <locale>
+#include <memory>
+#include <string>
+// #include <mutex>  // Guarded by GTEST_IS_THREADSAFE below
+#include <tuple>
 #include <type_traits>
+#include <vector>
 
 #ifndef _WIN32_WCE
-# include <sys/types.h>
-# include <sys/stat.h>
+#include <sys/stat.h>
+#include <sys/types.h>
 #endif  // !_WIN32_WCE
 
 #if defined __APPLE__
-# include <AvailabilityMacros.h>
-# include <TargetConditionals.h>
+#include <AvailabilityMacros.h>
+#include <TargetConditionals.h>
 #endif
 
-#include <iostream>  // NOLINT
-#include <locale>
-#include <memory>
-#include <string>  // NOLINT
-#include <tuple>
-#include <vector>  // NOLINT
-
 #include "gtest/internal/custom/gtest-port.h"
 #include "gtest/internal/gtest-port-arch.h"
 
+#if GTEST_HAS_ABSL
+#include "absl/flags/declare.h"
+#include "absl/flags/flag.h"
+#include "absl/flags/reflection.h"
+#endif
+
 #if !defined(GTEST_DEV_EMAIL_)
-# define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com"
-# define GTEST_FLAG_PREFIX_ "gtest_"
-# define GTEST_FLAG_PREFIX_DASH_ "gtest-"
-# define GTEST_FLAG_PREFIX_UPPER_ "GTEST_"
-# define GTEST_NAME_ "Google Test"
-# define GTEST_PROJECT_URL_ "https://github.com/google/googletest/"
+#define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com"
+#define GTEST_FLAG_PREFIX_ "gtest_"
+#define GTEST_FLAG_PREFIX_DASH_ "gtest-"
+#define GTEST_FLAG_PREFIX_UPPER_ "GTEST_"
+#define GTEST_NAME_ "Google Test"
+#define GTEST_PROJECT_URL_ "https://github.com/google/googletest/"
 #endif  // !defined(GTEST_DEV_EMAIL_)
 
 #if !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
-# define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest"
+#define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest"
 #endif  // !defined(GTEST_INIT_GOOGLE_TEST_NAME_)
 
 // Determines the version of gcc that is used to compile this.
 #ifdef __GNUC__
 // 40302 means version 4.3.2.
-# define GTEST_GCC_VER_ \
-    (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__)
+#define GTEST_GCC_VER_ \
+  (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
 #endif  // __GNUC__
 
 // Macros for disabling Microsoft Visual C++ warnings.
 //   /* code that triggers warnings C4800 and C4385 */
 //   GTEST_DISABLE_MSC_WARNINGS_POP_()
 #if defined(_MSC_VER)
-# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \
-    __pragma(warning(push))                        \
-    __pragma(warning(disable: warnings))
-# define GTEST_DISABLE_MSC_WARNINGS_POP_()          \
-    __pragma(warning(pop))
+#define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \
+  __pragma(warning(push)) __pragma(warning(disable : warnings))
+#define GTEST_DISABLE_MSC_WARNINGS_POP_() __pragma(warning(pop))
 #else
 // Not all compilers are MSVC
-# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
-# define GTEST_DISABLE_MSC_WARNINGS_POP_()
+#define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
+#define GTEST_DISABLE_MSC_WARNINGS_POP_()
 #endif
 
 // Clang on Windows does not understand MSVC's pragma warning.
 // We need clang-specific way to disable function deprecation warning.
 #ifdef __clang__
-# define GTEST_DISABLE_MSC_DEPRECATED_PUSH_()                         \
-    _Pragma("clang diagnostic push")                                  \
-    _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \
-    _Pragma("clang diagnostic ignored \"-Wdeprecated-implementations\"")
-#define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
-    _Pragma("clang diagnostic pop")
+#define GTEST_DISABLE_MSC_DEPRECATED_PUSH_()                            \
+  _Pragma("clang diagnostic push")                                      \
+      _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \
+          _Pragma("clang diagnostic ignored \"-Wdeprecated-implementations\"")
+#define GTEST_DISABLE_MSC_DEPRECATED_POP_() _Pragma("clang diagnostic pop")
 #else
-# define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
-    GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
-# define GTEST_DISABLE_MSC_DEPRECATED_POP_() \
-    GTEST_DISABLE_MSC_WARNINGS_POP_()
+#define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \
+  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
+#define GTEST_DISABLE_MSC_DEPRECATED_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()
 #endif
 
 // Brings in definitions for functions used in the testing::internal::posix
 // namespace (read, write, close, chdir, isatty, stat). We do not currently
 // use them on Windows Mobile.
 #if GTEST_OS_WINDOWS
-# if !GTEST_OS_WINDOWS_MOBILE
-#  include <direct.h>
-#  include <io.h>
-# endif
+#if !GTEST_OS_WINDOWS_MOBILE
+#include <direct.h>
+#include <io.h>
+#endif
 // In order to avoid having to include <windows.h>, use forward declaration
 #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)
 // MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two
@@ -367,68 +369,55 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
 // This assumes that non-Windows OSes provide unistd.h. For OSes where this
 // is not the case, we need to include headers that provide the functions
 // mentioned above.
-# include <unistd.h>
-# include <strings.h>
+#include <strings.h>
+#include <unistd.h>
 #endif  // GTEST_OS_WINDOWS
 
 #if GTEST_OS_LINUX_ANDROID
 // Used to define __ANDROID_API__ matching the target NDK API level.
-#  include <android/api-level.h>  // NOLINT
+#include <android/api-level.h>  // NOLINT
 #endif
 
 // Defines this to true if and only if Google Test can use POSIX regular
 // expressions.
 #ifndef GTEST_HAS_POSIX_RE
-# if GTEST_OS_LINUX_ANDROID
+#if GTEST_OS_LINUX_ANDROID
 // On Android, <regex.h> is only available starting with Gingerbread.
-#  define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
-# else
+#define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
+#else
 #define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS && !GTEST_OS_XTENSA)
-# endif
+#endif
 #endif
 
-#if GTEST_USES_PCRE
-// The appropriate headers have already been included.
-
+// Select the regular expression implementation.
+#if GTEST_HAS_ABSL
+// When using Abseil, RE2 is required.
+#include "absl/strings/string_view.h"
+#include "re2/re2.h"
+#define GTEST_USES_RE2 1
 #elif GTEST_HAS_POSIX_RE
-
-// On some platforms, <regex.h> needs someone to define size_t, and
-// won't compile otherwise.  We can #include it here as we already
-// included <stdlib.h>, which is guaranteed to define size_t through
-// <stddef.h>.
-# include <regex.h>  // NOLINT
-
-# define GTEST_USES_POSIX_RE 1
-
-#elif GTEST_OS_WINDOWS
-
-// <regex.h> is not available on Windows.  Use our own simple regex
-// implementation instead.
-# define GTEST_USES_SIMPLE_RE 1
-
+#include <regex.h>  // NOLINT
+#define GTEST_USES_POSIX_RE 1
 #else
-
-// <regex.h> may not be available on this platform.  Use our own
-// simple regex implementation instead.
-# define GTEST_USES_SIMPLE_RE 1
-
-#endif  // GTEST_USES_PCRE
+// Use our own simple regex implementation.
+#define GTEST_USES_SIMPLE_RE 1
+#endif
 
 #ifndef GTEST_HAS_EXCEPTIONS
 // The user didn't tell us whether exceptions are enabled, so we need
 // to figure it out.
-# if defined(_MSC_VER) && defined(_CPPUNWIND)
+#if defined(_MSC_VER) && defined(_CPPUNWIND)
 // MSVC defines _CPPUNWIND to 1 if and only if exceptions are enabled.
-#  define GTEST_HAS_EXCEPTIONS 1
-# elif defined(__BORLANDC__)
+#define GTEST_HAS_EXCEPTIONS 1
+#elif defined(__BORLANDC__)
 // C++Builder's implementation of the STL uses the _HAS_EXCEPTIONS
 // macro to enable exceptions, so we'll do the same.
 // Assumes that exceptions are enabled by default.
-#  ifndef _HAS_EXCEPTIONS
-#   define _HAS_EXCEPTIONS 1
-#  endif  // _HAS_EXCEPTIONS
-#  define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
-# elif defined(__clang__)
+#ifndef _HAS_EXCEPTIONS
+#define _HAS_EXCEPTIONS 1
+#endif  // _HAS_EXCEPTIONS
+#define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS
+#elif defined(__clang__)
 // clang defines __EXCEPTIONS if and only if exceptions are enabled before clang
 // 220714, but if and only if cleanups are enabled after that. In Obj-C++ files,
 // there can be cleanups for ObjC exceptions which also need cleanups, even if
@@ -437,27 +426,27 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
 // cleanups prior to that. To reliably check for C++ exception availability with
 // clang, check for
 // __EXCEPTIONS && __has_feature(cxx_exceptions).
-#  define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions))
-# elif defined(__GNUC__) && __EXCEPTIONS
+#define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions))
+#elif defined(__GNUC__) && __EXCEPTIONS
 // gcc defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
-#  define GTEST_HAS_EXCEPTIONS 1
-# elif defined(__SUNPRO_CC)
+#define GTEST_HAS_EXCEPTIONS 1
+#elif defined(__SUNPRO_CC)
 // Sun Pro CC supports exceptions.  However, there is no compile-time way of
 // detecting whether they are enabled or not.  Therefore, we assume that
 // they are enabled unless the user tells us otherwise.
-#  define GTEST_HAS_EXCEPTIONS 1
-# elif defined(__IBMCPP__) && __EXCEPTIONS
+#define GTEST_HAS_EXCEPTIONS 1
+#elif defined(__IBMCPP__) && __EXCEPTIONS
 // xlC defines __EXCEPTIONS to 1 if and only if exceptions are enabled.
-#  define GTEST_HAS_EXCEPTIONS 1
-# elif defined(__HP_aCC)
+#define GTEST_HAS_EXCEPTIONS 1
+#elif defined(__HP_aCC)
 // Exception handling is in effect by default in HP aCC compiler. It has to
 // be turned of by +noeh compiler option if desired.
-#  define GTEST_HAS_EXCEPTIONS 1
-# else
+#define GTEST_HAS_EXCEPTIONS 1
+#else
 // For other compilers, we assume exceptions are disabled to be
 // conservative.
-#  define GTEST_HAS_EXCEPTIONS 0
-# endif  // defined(_MSC_VER) || defined(__BORLANDC__)
+#define GTEST_HAS_EXCEPTIONS 0
+#endif  // defined(_MSC_VER) || defined(__BORLANDC__)
 #endif  // GTEST_HAS_EXCEPTIONS
 
 #ifndef GTEST_HAS_STD_WSTRING
@@ -477,63 +466,62 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
 // The user didn't tell us whether RTTI is enabled, so we need to
 // figure it out.
 
-# ifdef _MSC_VER
+#ifdef _MSC_VER
 
 #ifdef _CPPRTTI  // MSVC defines this macro if and only if RTTI is enabled.
-#   define GTEST_HAS_RTTI 1
-#  else
-#   define GTEST_HAS_RTTI 0
-#  endif
+#define GTEST_HAS_RTTI 1
+#else
+#define GTEST_HAS_RTTI 0
+#endif
 
 // Starting with version 4.3.2, gcc defines __GXX_RTTI if and only if RTTI is
 // enabled.
-# elif defined(__GNUC__)
+#elif defined(__GNUC__)
 
-#  ifdef __GXX_RTTI
+#ifdef __GXX_RTTI
 // When building against STLport with the Android NDK and with
 // -frtti -fno-exceptions, the build fails at link time with undefined
 // references to __cxa_bad_typeid. Note sure if STL or toolchain bug,
 // so disable RTTI when detected.
-#   if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \
-       !defined(__EXCEPTIONS)
-#    define GTEST_HAS_RTTI 0
-#   else
-#    define GTEST_HAS_RTTI 1
-#   endif  // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS
-#  else
-#   define GTEST_HAS_RTTI 0
-#  endif  // __GXX_RTTI
+#if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && !defined(__EXCEPTIONS)
+#define GTEST_HAS_RTTI 0
+#else
+#define GTEST_HAS_RTTI 1
+#endif  // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS
+#else
+#define GTEST_HAS_RTTI 0
+#endif  // __GXX_RTTI
 
 // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends
 // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the
 // first version with C++ support.
-# elif defined(__clang__)
+#elif defined(__clang__)
 
-#  define GTEST_HAS_RTTI __has_feature(cxx_rtti)
+#define GTEST_HAS_RTTI __has_feature(cxx_rtti)
 
 // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if
 // both the typeid and dynamic_cast features are present.
-# elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)
+#elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)
 
-#  ifdef __RTTI_ALL__
-#   define GTEST_HAS_RTTI 1
-#  else
-#   define GTEST_HAS_RTTI 0
-#  endif
+#ifdef __RTTI_ALL__
+#define GTEST_HAS_RTTI 1
+#else
+#define GTEST_HAS_RTTI 0
+#endif
 
-# else
+#else
 
 // For all other compilers, we assume RTTI is enabled.
-#  define GTEST_HAS_RTTI 1
+#define GTEST_HAS_RTTI 1
 
-# endif  // _MSC_VER
+#endif  // _MSC_VER
 
 #endif  // GTEST_HAS_RTTI
 
 // It's this header's responsibility to #include <typeinfo> when RTTI
 // is enabled.
 #if GTEST_HAS_RTTI
-# include <typeinfo>
+#include <typeinfo>
 #endif
 
 // Determines whether Google Test can use the pthreads library.
@@ -547,16 +535,16 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
   (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX ||          \
    GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \
    GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_OPENBSD ||          \
-   GTEST_OS_HAIKU)
+   GTEST_OS_HAIKU || GTEST_OS_GNU_HURD)
 #endif  // GTEST_HAS_PTHREAD
 
 #if GTEST_HAS_PTHREAD
 // gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is
 // true.
-# include <pthread.h>  // NOLINT
+#include <pthread.h>  // NOLINT
 
 // For timespec and nanosleep, used below.
-# include <time.h>  // NOLINT
+#include <time.h>  // NOLINT
 #endif
 
 // Determines whether clone(2) is supported.
@@ -566,24 +554,23 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
 #ifndef GTEST_HAS_CLONE
 // The user didn't tell us, so we need to figure it out.
 
-# if GTEST_OS_LINUX && !defined(__ia64__)
-#  if GTEST_OS_LINUX_ANDROID
+#if GTEST_OS_LINUX && !defined(__ia64__)
+#if GTEST_OS_LINUX_ANDROID
 // On Android, clone() became available at different API levels for each 32-bit
 // architecture.
-#    if defined(__LP64__) || \
-        (defined(__arm__) && __ANDROID_API__ >= 9) || \
-        (defined(__mips__) && __ANDROID_API__ >= 12) || \
-        (defined(__i386__) && __ANDROID_API__ >= 17)
-#     define GTEST_HAS_CLONE 1
-#    else
-#     define GTEST_HAS_CLONE 0
-#    endif
-#  else
-#   define GTEST_HAS_CLONE 1
-#  endif
-# else
-#  define GTEST_HAS_CLONE 0
-# endif  // GTEST_OS_LINUX && !defined(__ia64__)
+#if defined(__LP64__) || (defined(__arm__) && __ANDROID_API__ >= 9) || \
+    (defined(__mips__) && __ANDROID_API__ >= 12) ||                    \
+    (defined(__i386__) && __ANDROID_API__ >= 17)
+#define GTEST_HAS_CLONE 1
+#else
+#define GTEST_HAS_CLONE 0
+#endif
+#else
+#define GTEST_HAS_CLONE 1
+#endif
+#else
+#define GTEST_HAS_CLONE 0
+#endif  // GTEST_OS_LINUX && !defined(__ia64__)
 
 #endif  // GTEST_HAS_CLONE
 
@@ -594,10 +581,10 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
 // platforms except known mobile ones.
 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
     GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
-#  define GTEST_HAS_STREAM_REDIRECTION 0
-# else
-#  define GTEST_HAS_STREAM_REDIRECTION 1
-# endif  // !GTEST_OS_WINDOWS_MOBILE
+#define GTEST_HAS_STREAM_REDIRECTION 0
+#else
+#define GTEST_HAS_STREAM_REDIRECTION 1
+#endif  // !GTEST_OS_WINDOWS_MOBILE
 #endif  // GTEST_HAS_STREAM_REDIRECTION
 
 // Determines whether to support death tests.
@@ -607,8 +594,9 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
      (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER) || GTEST_OS_WINDOWS_MINGW ||  \
      GTEST_OS_AIX || GTEST_OS_HPUX || GTEST_OS_OPENBSD || GTEST_OS_QNX || \
      GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA ||           \
-     GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU)
-# define GTEST_HAS_DEATH_TEST 1
+     GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU ||     \
+     GTEST_OS_GNU_HURD)
+#define GTEST_HAS_DEATH_TEST 1
 #endif
 
 // Determines whether to support type-driven tests.
@@ -617,8 +605,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
 // Sun Pro CC, IBM Visual Age, and HP aCC support.
 #if defined(__GNUC__) || defined(_MSC_VER) || defined(__SUNPRO_CC) || \
     defined(__IBMCPP__) || defined(__HP_aCC)
-# define GTEST_HAS_TYPED_TEST 1
-# define GTEST_HAS_TYPED_TEST_P 1
+#define GTEST_HAS_TYPED_TEST 1
+#define GTEST_HAS_TYPED_TEST_P 1
 #endif
 
 // Determines whether the system compiler uses UTF-16 for encoding wide strings.
@@ -627,8 +615,9 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
 
 // Determines whether test results can be streamed to a socket.
 #if GTEST_OS_LINUX || GTEST_OS_GNU_KFREEBSD || GTEST_OS_DRAGONFLY || \
-    GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD
-# define GTEST_CAN_STREAM_RESULTS_ 1
+    GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD ||       \
+    GTEST_OS_GNU_HURD
+#define GTEST_CAN_STREAM_RESULTS_ 1
 #endif
 
 // Defines some utility macros.
@@ -642,9 +631,12 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
 //
 // The "switch (0) case 0:" idiom is used to suppress this.
 #ifdef __INTEL_COMPILER
-# define GTEST_AMBIGUOUS_ELSE_BLOCKER_
+#define GTEST_AMBIGUOUS_ELSE_BLOCKER_
 #else
-# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default:  // NOLINT
+#define GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
+  switch (0)                          \
+  case 0:                             \
+  default:  // NOLINT
 #endif
 
 // Use this annotation at the end of a struct/class definition to
@@ -659,55 +651,32 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
 // Also use it after a variable or parameter declaration to tell the
 // compiler the variable/parameter does not have to be used.
 #if defined(__GNUC__) && !defined(COMPILER_ICC)
-# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
+#define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused))
 #elif defined(__clang__)
-# if __has_attribute(unused)
-#  define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused))
-# endif
+#if __has_attribute(unused)
+#define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused))
+#endif
 #endif
 #ifndef GTEST_ATTRIBUTE_UNUSED_
-# define GTEST_ATTRIBUTE_UNUSED_
+#define GTEST_ATTRIBUTE_UNUSED_
 #endif
 
 // Use this annotation before a function that takes a printf format string.
 #if (defined(__GNUC__) || defined(__clang__)) && !defined(COMPILER_ICC)
-# if defined(__MINGW_PRINTF_FORMAT)
+#if defined(__MINGW_PRINTF_FORMAT)
 // MinGW has two different printf implementations. Ensure the format macro
 // matches the selected implementation. See
 // https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/.
-#  define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
-       __attribute__((__format__(__MINGW_PRINTF_FORMAT, string_index, \
-                                 first_to_check)))
-# else
-#  define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
-       __attribute__((__format__(__printf__, string_index, first_to_check)))
-# endif
+#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
+  __attribute__((                                             \
+      __format__(__MINGW_PRINTF_FORMAT, string_index, first_to_check)))
 #else
-# define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check)
+#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \
+  __attribute__((__format__(__printf__, string_index, first_to_check)))
+#endif
+#else
+#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check)
 #endif
-
-
-// A macro to disallow copy operator=
-// This should be used in the private: declarations for a class.
-#define GTEST_DISALLOW_ASSIGN_(type) \
-  type& operator=(type const &) = delete
-
-// A macro to disallow copy constructor and operator=
-// This should be used in the private: declarations for a class.
-#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type) \
-  type(type const&) = delete;                 \
-  type& operator=(type const&) = delete
-
-// A macro to disallow move operator=
-// This should be used in the private: declarations for a class.
-#define GTEST_DISALLOW_MOVE_ASSIGN_(type) \
-  type& operator=(type &&) noexcept = delete
-
-// A macro to disallow move constructor and operator=
-// This should be used in the private: declarations for a class.
-#define GTEST_DISALLOW_MOVE_AND_ASSIGN_(type) \
-  type(type&&) noexcept = delete;             \
-  type& operator=(type&&) noexcept = delete
 
 // Tell the compiler to warn about unused return values for functions declared
 // with this macro.  The macro should be used on function declarations
@@ -715,9 +684,9 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
 //
 //   Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
 #if defined(__GNUC__) && !defined(COMPILER_ICC)
-# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result))
+#define GTEST_MUST_USE_RESULT_ __attribute__((warn_unused_result))
 #else
-# define GTEST_MUST_USE_RESULT_
+#define GTEST_MUST_USE_RESULT_
 #endif  // __GNUC__ && !COMPILER_ICC
 
 // MS C++ compiler emits warning when a conditional expression is compile time
@@ -728,10 +697,9 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
 // while (true) {
 // GTEST_INTENTIONAL_CONST_COND_POP_()
 // }
-# define GTEST_INTENTIONAL_CONST_COND_PUSH_() \
-    GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127)
-# define GTEST_INTENTIONAL_CONST_COND_POP_() \
-    GTEST_DISABLE_MSC_WARNINGS_POP_()
+#define GTEST_INTENTIONAL_CONST_COND_PUSH_() \
+  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127)
+#define GTEST_INTENTIONAL_CONST_COND_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()
 
 // Determine whether the compiler supports Microsoft's Structured Exception
 // Handling.  This is supported by several Windows compilers but generally
@@ -739,13 +707,13 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
 #ifndef GTEST_HAS_SEH
 // The user didn't tell us, so we need to figure it out.
 
-# if defined(_MSC_VER) || defined(__BORLANDC__)
+#if defined(_MSC_VER) || defined(__BORLANDC__)
 // These two compilers are known to support SEH.
-#  define GTEST_HAS_SEH 1
-# else
+#define GTEST_HAS_SEH 1
+#else
 // Assume no SEH.
-#  define GTEST_HAS_SEH 0
-# endif
+#define GTEST_HAS_SEH 0
+#endif
 
 #endif  // GTEST_HAS_SEH
 
@@ -758,94 +726,112 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
 
 #endif  // GTEST_IS_THREADSAFE
 
+#if GTEST_IS_THREADSAFE
+// Some platforms don't support including these threading related headers.
+#include <condition_variable>  // NOLINT
+#include <mutex>               // NOLINT
+#endif                         // GTEST_IS_THREADSAFE
+
 // GTEST_API_ qualifies all symbols that must be exported. The definitions below
 // are guarded by #ifndef to give embedders a chance to define GTEST_API_ in
 // gtest/internal/custom/gtest-port.h
 #ifndef GTEST_API_
 
 #ifdef _MSC_VER
-# if GTEST_LINKED_AS_SHARED_LIBRARY
-#  define GTEST_API_ __declspec(dllimport)
-# elif GTEST_CREATE_SHARED_LIBRARY
-#  define GTEST_API_ __declspec(dllexport)
-# endif
+#if GTEST_LINKED_AS_SHARED_LIBRARY
+#define GTEST_API_ __declspec(dllimport)
+#elif GTEST_CREATE_SHARED_LIBRARY
+#define GTEST_API_ __declspec(dllexport)
+#endif
 #elif __GNUC__ >= 4 || defined(__clang__)
-# define GTEST_API_ __attribute__((visibility ("default")))
+#define GTEST_API_ __attribute__((visibility("default")))
 #endif  // _MSC_VER
 
 #endif  // GTEST_API_
 
 #ifndef GTEST_API_
-# define GTEST_API_
+#define GTEST_API_
 #endif  // GTEST_API_
 
 #ifndef GTEST_DEFAULT_DEATH_TEST_STYLE
-# define GTEST_DEFAULT_DEATH_TEST_STYLE  "fast"
+#define GTEST_DEFAULT_DEATH_TEST_STYLE "fast"
 #endif  // GTEST_DEFAULT_DEATH_TEST_STYLE
 
 #ifdef __GNUC__
 // Ask the compiler to never inline a given function.
-# define GTEST_NO_INLINE_ __attribute__((noinline))
+#define GTEST_NO_INLINE_ __attribute__((noinline))
 #else
-# define GTEST_NO_INLINE_
+#define GTEST_NO_INLINE_
+#endif
+
+#if defined(__clang__)
+// Nested ifs to avoid triggering MSVC warning.
+#if __has_attribute(disable_tail_calls)
+// Ask the compiler not to perform tail call optimization inside
+// the marked function.
+#define GTEST_NO_TAIL_CALL_ __attribute__((disable_tail_calls))
+#endif
+#elif __GNUC__
+#define GTEST_NO_TAIL_CALL_ \
+  __attribute__((optimize("no-optimize-sibling-calls")))
+#else
+#define GTEST_NO_TAIL_CALL_
 #endif
 
 // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.
 #if !defined(GTEST_HAS_CXXABI_H_)
-# if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER))
-#  define GTEST_HAS_CXXABI_H_ 1
-# else
-#  define GTEST_HAS_CXXABI_H_ 0
-# endif
+#if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER))
+#define GTEST_HAS_CXXABI_H_ 1
+#else
+#define GTEST_HAS_CXXABI_H_ 0
+#endif
 #endif
 
 // A function level attribute to disable checking for use of uninitialized
 // memory when built with MemorySanitizer.
 #if defined(__clang__)
-# if __has_feature(memory_sanitizer)
-#  define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \
-       __attribute__((no_sanitize_memory))
-# else
-#  define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
-# endif  // __has_feature(memory_sanitizer)
+#if __has_feature(memory_sanitizer)
+#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ __attribute__((no_sanitize_memory))
+#else
+#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
+#endif  // __has_feature(memory_sanitizer)
 #else
-# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
+#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
 #endif  // __clang__
 
 // A function level attribute to disable AddressSanitizer instrumentation.
 #if defined(__clang__)
-# if __has_feature(address_sanitizer)
-#  define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \
-       __attribute__((no_sanitize_address))
-# else
-#  define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
-# endif  // __has_feature(address_sanitizer)
+#if __has_feature(address_sanitizer)
+#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \
+  __attribute__((no_sanitize_address))
+#else
+#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
+#endif  // __has_feature(address_sanitizer)
 #else
-# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
+#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
 #endif  // __clang__
 
 // A function level attribute to disable HWAddressSanitizer instrumentation.
 #if defined(__clang__)
-# if __has_feature(hwaddress_sanitizer)
-#  define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \
-       __attribute__((no_sanitize("hwaddress")))
-# else
-#  define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
-# endif  // __has_feature(hwaddress_sanitizer)
+#if __has_feature(hwaddress_sanitizer)
+#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \
+  __attribute__((no_sanitize("hwaddress")))
 #else
-# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
+#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
+#endif  // __has_feature(hwaddress_sanitizer)
+#else
+#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
 #endif  // __clang__
 
 // A function level attribute to disable ThreadSanitizer instrumentation.
 #if defined(__clang__)
-# if __has_feature(thread_sanitizer)
-#  define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \
-       __attribute__((no_sanitize_thread))
-# else
-#  define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
-# endif  // __has_feature(thread_sanitizer)
+#if __has_feature(thread_sanitizer)
+#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ __attribute__((no_sanitize_thread))
+#else
+#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
+#endif  // __has_feature(thread_sanitizer)
 #else
-# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
+#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
 #endif  // __clang__
 
 namespace testing {
@@ -867,25 +853,37 @@ namespace internal {
 // Secret object, which is what we want.
 class Secret;
 
-// The GTEST_COMPILE_ASSERT_ is a legacy macro used to verify that a compile
-// time expression is true (in new code, use static_assert instead). For
-// example, you could use it to verify the size of a static array:
-//
-//   GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES,
-//                         names_incorrect_size);
-//
-// The second argument to the macro must be a valid C++ identifier. If the
-// expression is false, compiler will issue an error containing this identifier.
-#define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg)
-
 // A helper for suppressing warnings on constant condition.  It just
 // returns 'condition'.
 GTEST_API_ bool IsTrue(bool condition);
 
 // Defines RE.
 
-#if GTEST_USES_PCRE
-// if used, PCRE is injected by custom/gtest-port.h
+#if GTEST_USES_RE2
+
+// This is almost `using RE = ::RE2`, except it is copy-constructible, and it
+// needs to disambiguate the `std::string`, `absl::string_view`, and `const
+// char*` constructors.
+class GTEST_API_ RE {
+ public:
+  RE(absl::string_view regex) : regex_(regex) {}                  // NOLINT
+  RE(const char* regex) : RE(absl::string_view(regex)) {}         // NOLINT
+  RE(const std::string& regex) : RE(absl::string_view(regex)) {}  // NOLINT
+  RE(const RE& other) : RE(other.pattern()) {}
+
+  const std::string& pattern() const { return regex_.pattern(); }
+
+  static bool FullMatch(absl::string_view str, const RE& re) {
+    return RE2::FullMatch(str, re.regex_);
+  }
+  static bool PartialMatch(absl::string_view str, const RE& re) {
+    return RE2::PartialMatch(str, re.regex_);
+  }
+
+ private:
+  RE2 regex_;
+};
+
 #elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE
 
 // A simple C++ wrapper for <regex.h>.  It uses the POSIX Extended
@@ -924,19 +922,19 @@ class GTEST_API_ RE {
   const char* pattern_;
   bool is_valid_;
 
-# if GTEST_USES_POSIX_RE
+#if GTEST_USES_POSIX_RE
 
   regex_t full_regex_;     // For FullMatch().
   regex_t partial_regex_;  // For PartialMatch().
 
-# else  // GTEST_USES_SIMPLE_RE
+#else  // GTEST_USES_SIMPLE_RE
 
   const char* full_pattern_;  // For FullMatch();
 
-# endif
+#endif
 };
 
-#endif  // GTEST_USES_PCRE
+#endif  // ::testing::internal::RE implementation
 
 // Formats a source file path and a line number as they would appear
 // in an error message from the compiler used to compile this code.
@@ -954,12 +952,7 @@ GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
 //   LogToStderr()  - directs all log messages to stderr.
 //   FlushInfoLog() - flushes informational log messages.
 
-enum GTestLogSeverity {
-  GTEST_INFO,
-  GTEST_WARNING,
-  GTEST_ERROR,
-  GTEST_FATAL
-};
+enum GTestLogSeverity { GTEST_INFO, GTEST_WARNING, GTEST_ERROR, GTEST_FATAL };
 
 // Formats log entry severity, provides a stream object for streaming the
 // log message, and terminates the message with a newline when going out of
@@ -976,14 +969,16 @@ class GTEST_API_ GTestLog {
  private:
   const GTestLogSeverity severity_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog);
+  GTestLog(const GTestLog&) = delete;
+  GTestLog& operator=(const GTestLog&) = delete;
 };
 
 #if !defined(GTEST_LOG_)
 
-# define GTEST_LOG_(severity) \
-    ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
-                                  __FILE__, __LINE__).GetStream()
+#define GTEST_LOG_(severity)                                           \
+  ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \
+                                __FILE__, __LINE__)                    \
+      .GetStream()
 
 inline void LogToStderr() {}
 inline void FlushInfoLog() { fflush(nullptr); }
@@ -995,7 +990,7 @@ inline void FlushInfoLog() { fflush(nullptr); }
 //
 // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition
 // is not satisfied.
-//  Synopsys:
+//  Synopsis:
 //    GTEST_CHECK_(boolean_condition);
 //     or
 //    GTEST_CHECK_(boolean_condition) << "Additional message";
@@ -1005,12 +1000,12 @@ inline void FlushInfoLog() { fflush(nullptr); }
 //    condition itself, plus additional message streamed into it, if any,
 //    and then it aborts the program. It aborts the program irrespective of
 //    whether it is built in the debug mode or not.
-# define GTEST_CHECK_(condition) \
-    GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
-    if (::testing::internal::IsTrue(condition)) \
-      ; \
-    else \
-      GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
+#define GTEST_CHECK_(condition)               \
+  GTEST_AMBIGUOUS_ELSE_BLOCKER_               \
+  if (::testing::internal::IsTrue(condition)) \
+    ;                                         \
+  else                                        \
+    GTEST_LOG_(FATAL) << "Condition " #condition " failed. "
 #endif  // !defined(GTEST_CHECK_)
 
 // An all-mode assert to verify that the given POSIX-style function
@@ -1019,9 +1014,8 @@ inline void FlushInfoLog() { fflush(nullptr); }
 // in {} if you need to use it as the only statement in an 'if'
 // branch.
 #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \
-  if (const int gtest_error = (posix_call)) \
-    GTEST_LOG_(FATAL) << #posix_call << "failed with error " \
-                      << gtest_error
+  if (const int gtest_error = (posix_call))    \
+  GTEST_LOG_(FATAL) << #posix_call << "failed with error " << gtest_error
 
 // Transforms "T" into "const T&" according to standard reference collapsing
 // rules (this is only needed as a backport for C++98 compilers that do not
@@ -1035,9 +1029,13 @@ inline void FlushInfoLog() { fflush(nullptr); }
 // Note that the non-const reference will not have "const" added. This is
 // standard, and necessary so that "T" can always bind to "const T&".
 template <typename T>
-struct ConstRef { typedef const T& type; };
+struct ConstRef {
+  typedef const T& type;
+};
 template <typename T>
-struct ConstRef<T&> { typedef T& type; };
+struct ConstRef<T&> {
+  typedef T& type;
+};
 
 // The argument T must depend on some template parameters.
 #define GTEST_REFERENCE_TO_CONST_(T) \
@@ -1050,7 +1048,7 @@ struct ConstRef<T&> { typedef T& type; };
 // const Foo*).  When you use ImplicitCast_, the compiler checks that
 // the cast is safe.  Such explicit ImplicitCast_s are necessary in
 // surprisingly many situations where C++ demands an exact type match
-// instead of an argument type convertable to a target type.
+// instead of an argument type convertible to a target type.
 //
 // The syntax for using ImplicitCast_ is the same as for static_cast:
 //
@@ -1063,8 +1061,10 @@ struct ConstRef<T&> { typedef T& type; };
 // This relatively ugly name is intentional. It prevents clashes with
 // similar functions users may have (e.g., implicit_cast). The internal
 // namespace alone is not enough because the function can be found by ADL.
-template<typename To>
-inline To ImplicitCast_(To x) { return x; }
+template <typename To>
+inline To ImplicitCast_(To x) {
+  return x;
+}
 
 // When you upcast (that is, cast a pointer from type Foo to type
 // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
@@ -1087,17 +1087,17 @@ inline To ImplicitCast_(To x) { return x; }
 // This relatively ugly name is intentional. It prevents clashes with
 // similar functions users may have (e.g., down_cast). The internal
 // namespace alone is not enough because the function can be found by ADL.
-template<typename To, typename From>  // use like this: DownCast_<T*>(foo);
-inline To DownCast_(From* f) {  // so we only accept pointers
+template <typename To, typename From>  // use like this: DownCast_<T*>(foo);
+inline To DownCast_(From* f) {         // so we only accept pointers
   // Ensures that To is a sub-type of From *.  This test is here only
   // for compile-time type checking, and has no overhead in an
   // optimized build at run-time, as it will be optimized away
   // completely.
   GTEST_INTENTIONAL_CONST_COND_PUSH_()
   if (false) {
-  GTEST_INTENTIONAL_CONST_COND_POP_()
-  const To to = nullptr;
-  ::testing::internal::ImplicitCast_<From*>(to);
+    GTEST_INTENTIONAL_CONST_COND_POP_()
+    const To to = nullptr;
+    ::testing::internal::ImplicitCast_<From*>(to);
   }
 
 #if GTEST_HAS_RTTI
@@ -1162,71 +1162,8 @@ void ClearInjectableArgvs();
 
 // Defines synchronization primitives.
 #if GTEST_IS_THREADSAFE
-# if GTEST_HAS_PTHREAD
-// Sleeps for (roughly) n milliseconds.  This function is only for testing
-// Google Test's own constructs.  Don't use it in user tests, either
-// directly or indirectly.
-inline void SleepMilliseconds(int n) {
-  const timespec time = {
-    0,                  // 0 seconds.
-    n * 1000L * 1000L,  // And n ms.
-  };
-  nanosleep(&time, nullptr);
-}
-# endif  // GTEST_HAS_PTHREAD
-
-# if GTEST_HAS_NOTIFICATION_
-// Notification has already been imported into the namespace.
-// Nothing to do here.
-
-# elif GTEST_HAS_PTHREAD
-// Allows a controller thread to pause execution of newly created
-// threads until notified.  Instances of this class must be created
-// and destroyed in the controller thread.
-//
-// This class is only for testing Google Test's own constructs. Do not
-// use it in user tests, either directly or indirectly.
-class Notification {
- public:
-  Notification() : notified_(false) {
-    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
-  }
-  ~Notification() {
-    pthread_mutex_destroy(&mutex_);
-  }
-
-  // Notifies all threads created with this notification to start. Must
-  // be called from the controller thread.
-  void Notify() {
-    pthread_mutex_lock(&mutex_);
-    notified_ = true;
-    pthread_mutex_unlock(&mutex_);
-  }
-
-  // Blocks until the controller thread notifies. Must be called from a test
-  // thread.
-  void WaitForNotification() {
-    for (;;) {
-      pthread_mutex_lock(&mutex_);
-      const bool notified = notified_;
-      pthread_mutex_unlock(&mutex_);
-      if (notified)
-        break;
-      SleepMilliseconds(10);
-    }
-  }
-
- private:
-  pthread_mutex_t mutex_;
-  bool notified_;
-
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
-};
-
-# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
-
-GTEST_API_ void SleepMilliseconds(int n);
 
+#if GTEST_OS_WINDOWS
 // Provides leak-safe Windows kernel handle ownership.
 // Used in death tests and in threading support.
 class GTEST_API_ AutoHandle {
@@ -1253,8 +1190,18 @@ class GTEST_API_ AutoHandle {
 
   Handle handle_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
+  AutoHandle(const AutoHandle&) = delete;
+  AutoHandle& operator=(const AutoHandle&) = delete;
 };
+#endif
+
+#if GTEST_HAS_NOTIFICATION_
+// Notification has already been imported into the namespace.
+// Nothing to do here.
+
+#else
+GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
+/* class A needs to have dll-interface to be used by clients of class B */)
 
 // Allows a controller thread to pause execution of newly created
 // threads until notified.  Instances of this class must be created
@@ -1262,23 +1209,40 @@ class GTEST_API_ AutoHandle {
 //
 // This class is only for testing Google Test's own constructs. Do not
 // use it in user tests, either directly or indirectly.
+// TODO(b/203539622): Replace unconditionally with absl::Notification.
 class GTEST_API_ Notification {
  public:
-  Notification();
-  void Notify();
-  void WaitForNotification();
+  Notification() : notified_(false) {}
+  Notification(const Notification&) = delete;
+  Notification& operator=(const Notification&) = delete;
 
- private:
-  AutoHandle event_;
+  // Notifies all threads created with this notification to start. Must
+  // be called from the controller thread.
+  void Notify() {
+    std::lock_guard<std::mutex> lock(mu_);
+    notified_ = true;
+    cv_.notify_all();
+  }
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification);
+  // Blocks until the controller thread notifies. Must be called from a test
+  // thread.
+  void WaitForNotification() {
+    std::unique_lock<std::mutex> lock(mu_);
+    cv_.wait(lock, [this]() { return notified_; });
+  }
+
+ private:
+  std::mutex mu_;
+  std::condition_variable cv_;
+  bool notified_;
 };
-# endif  // GTEST_HAS_NOTIFICATION_
+GTEST_DISABLE_MSC_WARNINGS_POP_()  // 4251
+#endif  // GTEST_HAS_NOTIFICATION_
 
 // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD
 // defined, but we don't want to use MinGW's pthreads implementation, which
 // has conformance problems with some versions of the POSIX standard.
-# if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW
+#if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW
 
 // As a C-function, ThreadFuncWithCLinkage cannot be templated itself.
 // Consequently, it cannot select a correct instantiation of ThreadWithParam
@@ -1354,16 +1318,17 @@ class ThreadWithParam : public ThreadWithParamBase {
                    // finished.
   pthread_t thread_;  // The native thread object.
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
+  ThreadWithParam(const ThreadWithParam&) = delete;
+  ThreadWithParam& operator=(const ThreadWithParam&) = delete;
 };
-# endif  // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD ||
-         // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
+#endif  // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD ||
+        // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
 
-# if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
+#if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
 // Mutex and ThreadLocal have already been imported into the namespace.
 // Nothing to do here.
 
-# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
+#elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
 
 // Mutex implements mutex on Windows platforms.  It is used in conjunction
 // with class MutexLock:
@@ -1417,14 +1382,15 @@ class GTEST_API_ Mutex {
   long critical_section_init_phase_;  // NOLINT
   GTEST_CRITICAL_SECTION* critical_section_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
+  Mutex(const Mutex&) = delete;
+  Mutex& operator=(const Mutex&) = delete;
 };
 
-# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
-    extern ::testing::internal::Mutex mutex
+#define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
+  extern ::testing::internal::Mutex mutex
 
-# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
-    ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex)
+#define GTEST_DEFINE_STATIC_MUTEX_(mutex) \
+  ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex)
 
 // We cannot name this class MutexLock because the ctor declaration would
 // conflict with a macro named MutexLock, which is defined on some
@@ -1433,15 +1399,15 @@ class GTEST_API_ Mutex {
 // "MutexLock l(&mu)".  Hence the typedef trick below.
 class GTestMutexLock {
  public:
-  explicit GTestMutexLock(Mutex* mutex)
-      : mutex_(mutex) { mutex_->Lock(); }
+  explicit GTestMutexLock(Mutex* mutex) : mutex_(mutex) { mutex_->Lock(); }
 
   ~GTestMutexLock() { mutex_->Unlock(); }
 
  private:
   Mutex* const mutex_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
+  GTestMutexLock(const GTestMutexLock&) = delete;
+  GTestMutexLock& operator=(const GTestMutexLock&) = delete;
 };
 
 typedef GTestMutexLock MutexLock;
@@ -1468,7 +1434,8 @@ class ThreadLocalBase {
   virtual ~ThreadLocalBase() {}
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase);
+  ThreadLocalBase(const ThreadLocalBase&) = delete;
+  ThreadLocalBase& operator=(const ThreadLocalBase&) = delete;
 };
 
 // Maps a thread to a set of ThreadLocals that have values instantiated on that
@@ -1497,7 +1464,7 @@ class GTEST_API_ ThreadWithParamBase {
     virtual void Run() = 0;
   };
 
-  ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start);
+  ThreadWithParamBase(Runnablerunnable, Notification* thread_can_start);
   virtual ~ThreadWithParamBase();
 
  private:
@@ -1511,30 +1478,26 @@ class ThreadWithParam : public ThreadWithParamBase {
   typedef void UserThreadFunc(T);
 
   ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)
-      : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {
-  }
+      : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {}
   virtual ~ThreadWithParam() {}
 
  private:
   class RunnableImpl : public Runnable {
    public:
-    RunnableImpl(UserThreadFunc* func, T param)
-        : func_(func),
-          param_(param) {
-    }
+    RunnableImpl(UserThreadFunc* func, T param) : func_(func), param_(param) {}
     virtual ~RunnableImpl() {}
-    virtual void Run() {
-      func_(param_);
-    }
+    virtual void Run() { func_(param_); }
 
    private:
     UserThreadFunc* const func_;
     const T param_;
 
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl);
+    RunnableImpl(const RunnableImpl&) = delete;
+    RunnableImpl& operator=(const RunnableImpl&) = delete;
   };
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam);
+  ThreadWithParam(const ThreadWithParam&) = delete;
+  ThreadWithParam& operator=(const ThreadWithParam&) = delete;
 };
 
 // Implements thread-local storage on Windows systems.
@@ -1571,7 +1534,7 @@ class ThreadLocal : public ThreadLocalBase {
   explicit ThreadLocal(const T& value)
       : default_factory_(new InstanceValueHolderFactory(value)) {}
 
-  ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); }
+  ~ThreadLocal() override { ThreadLocalRegistry::OnThreadLocalDestroyed(this); }
 
   T* pointer() { return GetOrCreateValue(); }
   const T* pointer() const { return GetOrCreateValue(); }
@@ -1590,16 +1553,17 @@ class ThreadLocal : public ThreadLocalBase {
 
    private:
     T value_;
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
+    ValueHolder(const ValueHolder&) = delete;
+    ValueHolder& operator=(const ValueHolder&) = delete;
   };
 
-
   T* GetOrCreateValue() const {
     return static_cast<ValueHolder*>(
-        ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer();
+               ThreadLocalRegistry::GetValueOnCurrentThread(this))
+        ->pointer();
   }
 
-  virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const {
+  ThreadLocalValueHolderBase* NewValueForCurrentThread() const override {
     return default_factory_->MakeNewHolder();
   }
 
@@ -1610,7 +1574,8 @@ class ThreadLocal : public ThreadLocalBase {
     virtual ValueHolder* MakeNewHolder() const = 0;
 
    private:
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
+    ValueHolderFactory(const ValueHolderFactory&) = delete;
+    ValueHolderFactory& operator=(const ValueHolderFactory&) = delete;
   };
 
   class DefaultValueHolderFactory : public ValueHolderFactory {
@@ -1619,7 +1584,9 @@ class ThreadLocal : public ThreadLocalBase {
     ValueHolder* MakeNewHolder() const override { return new ValueHolder(); }
 
    private:
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
+    DefaultValueHolderFactory(const DefaultValueHolderFactory&) = delete;
+    DefaultValueHolderFactory& operator=(const DefaultValueHolderFactory&) =
+        delete;
   };
 
   class InstanceValueHolderFactory : public ValueHolderFactory {
@@ -1632,15 +1599,18 @@ class ThreadLocal : public ThreadLocalBase {
    private:
     const T value_;  // The value for each thread.
 
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
+    InstanceValueHolderFactory(const InstanceValueHolderFactory&) = delete;
+    InstanceValueHolderFactory& operator=(const InstanceValueHolderFactory&) =
+        delete;
   };
 
   std::unique_ptr<ValueHolderFactory> default_factory_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
+  ThreadLocal(const ThreadLocal&) = delete;
+  ThreadLocal& operator=(const ThreadLocal&) = delete;
 };
 
-# elif GTEST_HAS_PTHREAD
+#elif GTEST_HAS_PTHREAD
 
 // MutexBase and Mutex implement mutex on pthreads-based platforms.
 class MutexBase {
@@ -1687,8 +1657,8 @@ class MutexBase {
 };
 
 // Forward-declares a static mutex.
-#  define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
-     extern ::testing::internal::MutexBase mutex
+#define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
+  extern ::testing::internal::MutexBase mutex
 
 // Defines and statically (i.e. at link time) initializes a static mutex.
 // The initialization list here does not explicitly initialize each field,
@@ -1707,12 +1677,11 @@ class Mutex : public MutexBase {
     GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
     has_owner_ = false;
   }
-  ~Mutex() {
-    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_));
-  }
+  ~Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); }
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex);
+  Mutex(const Mutex&) = delete;
+  Mutex& operator=(const Mutex&) = delete;
 };
 
 // We cannot name this class MutexLock because the ctor declaration would
@@ -1722,15 +1691,15 @@ class Mutex : public MutexBase {
 // "MutexLock l(&mu)".  Hence the typedef trick below.
 class GTestMutexLock {
  public:
-  explicit GTestMutexLock(MutexBase* mutex)
-      : mutex_(mutex) { mutex_->Lock(); }
+  explicit GTestMutexLock(MutexBase* mutex) : mutex_(mutex) { mutex_->Lock(); }
 
   ~GTestMutexLock() { mutex_->Unlock(); }
 
  private:
   MutexBase* const mutex_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock);
+  GTestMutexLock(const GTestMutexLock&) = delete;
+  GTestMutexLock& operator=(const GTestMutexLock&) = delete;
 };
 
 typedef GTestMutexLock MutexLock;
@@ -1787,7 +1756,8 @@ class GTEST_API_ ThreadLocal {
 
    private:
     T value_;
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder);
+    ValueHolder(const ValueHolder&) = delete;
+    ValueHolder& operator=(const ValueHolder&) = delete;
   };
 
   static pthread_key_t CreateKey() {
@@ -1819,7 +1789,8 @@ class GTEST_API_ ThreadLocal {
     virtual ValueHolder* MakeNewHolder() const = 0;
 
    private:
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory);
+    ValueHolderFactory(const ValueHolderFactory&) = delete;
+    ValueHolderFactory& operator=(const ValueHolderFactory&) = delete;
   };
 
   class DefaultValueHolderFactory : public ValueHolderFactory {
@@ -1828,7 +1799,9 @@ class GTEST_API_ ThreadLocal {
     ValueHolder* MakeNewHolder() const override { return new ValueHolder(); }
 
    private:
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory);
+    DefaultValueHolderFactory(const DefaultValueHolderFactory&) = delete;
+    DefaultValueHolderFactory& operator=(const DefaultValueHolderFactory&) =
+        delete;
   };
 
   class InstanceValueHolderFactory : public ValueHolderFactory {
@@ -1841,17 +1814,20 @@ class GTEST_API_ ThreadLocal {
    private:
     const T value_;  // The value for each thread.
 
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory);
+    InstanceValueHolderFactory(const InstanceValueHolderFactory&) = delete;
+    InstanceValueHolderFactory& operator=(const InstanceValueHolderFactory&) =
+        delete;
   };
 
   // A key pthreads uses for looking up per-thread values.
   const pthread_key_t key_;
   std::unique_ptr<ValueHolderFactory> default_factory_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal);
+  ThreadLocal(const ThreadLocal&) = delete;
+  ThreadLocal& operator=(const ThreadLocal&) = delete;
 };
 
-# endif  // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
+#endif  // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
 
 #else  // GTEST_IS_THREADSAFE
 
@@ -1868,10 +1844,10 @@ class Mutex {
   void AssertHeld() const {}
 };
 
-# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
+#define GTEST_DECLARE_STATIC_MUTEX_(mutex) \
   extern ::testing::internal::Mutex mutex
 
-# define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex
+#define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex
 
 // We cannot name this class MutexLock because the ctor declaration would
 // conflict with a macro named MutexLock, which is defined on some
@@ -1894,6 +1870,7 @@ class GTEST_API_ ThreadLocal {
   const T* pointer() const { return &value_; }
   const T& get() const { return value_; }
   void set(const T& value) { value_ = value; }
+
  private:
   T value_;
 };
@@ -1905,11 +1882,11 @@ class GTEST_API_ ThreadLocal {
 GTEST_API_ size_t GetThreadCount();
 
 #if GTEST_OS_WINDOWS
-# define GTEST_PATH_SEP_ "\\"
-# define GTEST_HAS_ALT_PATH_SEP_ 1
+#define GTEST_PATH_SEP_ "\\"
+#define GTEST_HAS_ALT_PATH_SEP_ 1
 #else
-# define GTEST_PATH_SEP_ "/"
-# define GTEST_HAS_ALT_PATH_SEP_ 0
+#define GTEST_PATH_SEP_ "/"
+#define GTEST_HAS_ALT_PATH_SEP_ 0
 #endif  // GTEST_OS_WINDOWS
 
 // Utilities for char.
@@ -1967,8 +1944,7 @@ inline char ToUpper(char ch) {
 
 inline std::string StripTrailingSpaces(std::string str) {
   std::string::iterator it = str.end();
-  while (it != str.begin() && IsSpace(*--it))
-    it = str.erase(it);
+  while (it != str.begin() && IsSpace(*--it)) it = str.erase(it);
   return str;
 }
 
@@ -1986,36 +1962,35 @@ namespace posix {
 
 typedef struct _stat StatStruct;
 
-# ifdef __BORLANDC__
+#ifdef __BORLANDC__
 inline int DoIsATTY(int fd) { return isatty(fd); }
 inline int StrCaseCmp(const char* s1, const char* s2) {
   return stricmp(s1, s2);
 }
 inline char* StrDup(const char* src) { return strdup(src); }
-# else  // !__BORLANDC__
-#  if GTEST_OS_WINDOWS_MOBILE
+#else  // !__BORLANDC__
+#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
+    GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM)
 inline int DoIsATTY(int /* fd */) { return 0; }
-#  else
+#else
 inline int DoIsATTY(int fd) { return _isatty(fd); }
-#  endif  // GTEST_OS_WINDOWS_MOBILE
+#endif  // GTEST_OS_WINDOWS_MOBILE
 inline int StrCaseCmp(const char* s1, const char* s2) {
   return _stricmp(s1, s2);
 }
 inline char* StrDup(const char* src) { return _strdup(src); }
-# endif  // __BORLANDC__
+#endif  // __BORLANDC__
 
-# if GTEST_OS_WINDOWS_MOBILE
+#if GTEST_OS_WINDOWS_MOBILE
 inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }
 // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this
 // time and thus not defined there.
-# else
+#else
 inline int FileNo(FILE* file) { return _fileno(file); }
 inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }
 inline int RmDir(const char* dir) { return _rmdir(dir); }
-inline bool IsDir(const StatStruct& st) {
-  return (_S_IFDIR & st.st_mode) != 0;
-}
-# endif  // GTEST_OS_WINDOWS_MOBILE
+inline bool IsDir(const StatStruct& st) { return (_S_IFDIR & st.st_mode) != 0; }
+#endif  // GTEST_OS_WINDOWS_MOBILE
 
 #elif GTEST_OS_ESP8266
 typedef struct stat StatStruct;
@@ -2079,12 +2054,12 @@ inline FILE* FOpen(const char* path, const char* mode) {
   std::wstring wide_path = converter.from_bytes(path);
   std::wstring wide_mode = converter.from_bytes(mode);
   return _wfopen(wide_path.c_str(), wide_mode.c_str());
-#else  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
+#else   // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
   return fopen(path, mode);
 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
 }
 #if !GTEST_OS_WINDOWS_MOBILE
-inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
+inline FILEFReopen(const char* path, const char* mode, FILE* stream) {
   return freopen(path, mode, stream);
 }
 inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
@@ -2136,13 +2111,13 @@ GTEST_DISABLE_MSC_DEPRECATED_POP_()
 // snprintf is a variadic function.
 #if _MSC_VER && !GTEST_OS_WINDOWS_MOBILE
 // MSVC 2005 and above support variadic macros.
-# define GTEST_SNPRINTF_(buffer, size, format, ...) \
-     _snprintf_s(buffer, size, size, format, __VA_ARGS__)
+#define GTEST_SNPRINTF_(buffer, size, format, ...) \
+  _snprintf_s(buffer, size, size, format, __VA_ARGS__)
 #elif defined(_MSC_VER)
 // Windows CE does not define _snprintf_s
-# define GTEST_SNPRINTF_ _snprintf
+#define GTEST_SNPRINTF_ _snprintf
 #else
-# define GTEST_SNPRINTF_ snprintf
+#define GTEST_SNPRINTF_ snprintf
 #endif
 
 // The biggest signed integer type the compiler supports.
@@ -2202,37 +2177,84 @@ using TimeInMillis = int64_t;  // Represents time in milliseconds.
 
 // Macro for referencing flags.
 #if !defined(GTEST_FLAG)
-# define GTEST_FLAG(name) FLAGS_gtest_##name
+#define GTEST_FLAG_NAME_(name) gtest_##name
+#define GTEST_FLAG(name) FLAGS_gtest_##name
 #endif  // !defined(GTEST_FLAG)
 
-#if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
-# define GTEST_USE_OWN_FLAGFILE_FLAG_ 1
-#endif  // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_)
+// Pick a command line flags implementation.
+#if GTEST_HAS_ABSL
 
-#if !defined(GTEST_DECLARE_bool_)
-# define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver
+// Macros for defining flags.
+#define GTEST_DEFINE_bool_(name, default_val, doc) \
+  ABSL_FLAG(bool, GTEST_FLAG_NAME_(name), default_val, doc)
+#define GTEST_DEFINE_int32_(name, default_val, doc) \
+  ABSL_FLAG(int32_t, GTEST_FLAG_NAME_(name), default_val, doc)
+#define GTEST_DEFINE_string_(name, default_val, doc) \
+  ABSL_FLAG(std::string, GTEST_FLAG_NAME_(name), default_val, doc)
 
 // Macros for declaring flags.
-# define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name)
-# define GTEST_DECLARE_int32_(name) \
-    GTEST_API_ extern std::int32_t GTEST_FLAG(name)
-# define GTEST_DECLARE_string_(name) \
-    GTEST_API_ extern ::std::string GTEST_FLAG(name)
+#define GTEST_DECLARE_bool_(name) \
+  ABSL_DECLARE_FLAG(bool, GTEST_FLAG_NAME_(name))
+#define GTEST_DECLARE_int32_(name) \
+  ABSL_DECLARE_FLAG(int32_t, GTEST_FLAG_NAME_(name))
+#define GTEST_DECLARE_string_(name) \
+  ABSL_DECLARE_FLAG(std::string, GTEST_FLAG_NAME_(name))
+
+#define GTEST_FLAG_SAVER_ ::absl::FlagSaver
+
+#define GTEST_FLAG_GET(name) ::absl::GetFlag(GTEST_FLAG(name))
+#define GTEST_FLAG_SET(name, value) \
+  (void)(::absl::SetFlag(&GTEST_FLAG(name), value))
+#define GTEST_USE_OWN_FLAGFILE_FLAG_ 0
+
+#else  // GTEST_HAS_ABSL
 
 // Macros for defining flags.
-# define GTEST_DEFINE_bool_(name, default_val, doc) \
-    GTEST_API_ bool GTEST_FLAG(name) = (default_val)
-# define GTEST_DEFINE_int32_(name, default_val, doc) \
-    GTEST_API_ std::int32_t GTEST_FLAG(name) = (default_val)
-# define GTEST_DEFINE_string_(name, default_val, doc) \
-    GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val)
+#define GTEST_DEFINE_bool_(name, default_val, doc)  \
+  namespace testing {                               \
+  GTEST_API_ bool GTEST_FLAG(name) = (default_val); \
+  }                                                 \
+  static_assert(true, "no-op to require trailing semicolon")
+#define GTEST_DEFINE_int32_(name, default_val, doc)         \
+  namespace testing {                                       \
+  GTEST_API_ std::int32_t GTEST_FLAG(name) = (default_val); \
+  }                                                         \
+  static_assert(true, "no-op to require trailing semicolon")
+#define GTEST_DEFINE_string_(name, default_val, doc)         \
+  namespace testing {                                        \
+  GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val); \
+  }                                                          \
+  static_assert(true, "no-op to require trailing semicolon")
 
-#endif  // !defined(GTEST_DECLARE_bool_)
+// Macros for declaring flags.
+#define GTEST_DECLARE_bool_(name)          \
+  namespace testing {                      \
+  GTEST_API_ extern bool GTEST_FLAG(name); \
+  }                                        \
+  static_assert(true, "no-op to require trailing semicolon")
+#define GTEST_DECLARE_int32_(name)                 \
+  namespace testing {                              \
+  GTEST_API_ extern std::int32_t GTEST_FLAG(name); \
+  }                                                \
+  static_assert(true, "no-op to require trailing semicolon")
+#define GTEST_DECLARE_string_(name)                 \
+  namespace testing {                               \
+  GTEST_API_ extern ::std::string GTEST_FLAG(name); \
+  }                                                 \
+  static_assert(true, "no-op to require trailing semicolon")
+
+#define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver
+
+#define GTEST_FLAG_GET(name) ::testing::GTEST_FLAG(name)
+#define GTEST_FLAG_SET(name, value) (void)(::testing::GTEST_FLAG(name) = value)
+#define GTEST_USE_OWN_FLAGFILE_FLAG_ 1
+
+#endif  // GTEST_HAS_ABSL
 
 // Thread annotations
 #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
-# define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
-# define GTEST_LOCK_EXCLUDED_(locks)
+#define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
+#define GTEST_LOCK_EXCLUDED_(locks)
 #endif  // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)
 
 // Parses 'str' for a 32-bit signed integer.  If successful, writes the result
@@ -2308,6 +2330,7 @@ namespace testing {
 namespace internal {
 template <typename T>
 using Optional = ::absl::optional<T>;
+inline ::absl::nullopt_t Nullopt() { return ::absl::nullopt; }
 }  // namespace internal
 }  // namespace testing
 #else
@@ -2321,6 +2344,7 @@ namespace testing {
 namespace internal {
 template <typename T>
 using Optional = ::std::optional<T>;
+inline ::std::nullopt_t Nullopt() { return ::std::nullopt; }
 }  // namespace internal
 }  // namespace testing
 // The case where absl is configured NOT to alias std::optional is not
@@ -2332,7 +2356,7 @@ using Optional = ::std::optional<T>;
 #if GTEST_HAS_ABSL
 // Always use absl::string_view for Matcher<> specializations if googletest
 // is built with absl support.
-# define GTEST_INTERNAL_HAS_STRING_VIEW 1
+#define GTEST_INTERNAL_HAS_STRING_VIEW 1
 #include "absl/strings/string_view.h"
 namespace testing {
 namespace internal {
@@ -2340,11 +2364,11 @@ using StringView = ::absl::string_view;
 }  // namespace internal
 }  // namespace testing
 #else
-# ifdef __has_include
-#   if __has_include(<string_view>) && __cplusplus >= 201703L
+#ifdef __has_include
+#if __has_include(<string_view>) && __cplusplus >= 201703L
 // Otherwise for C++17 and higher use std::string_view for Matcher<>
 // specializations.
-#   define GTEST_INTERNAL_HAS_STRING_VIEW 1
+#define GTEST_INTERNAL_HAS_STRING_VIEW 1
 #include <string_view>
 namespace testing {
 namespace internal {
@@ -2353,8 +2377,8 @@ using StringView = ::std::string_view;
 }  // namespace testing
 // The case where absl is configured NOT to alias std::string_view is not
 // supported.
-#  endif  // __has_include(<string_view>) && __cplusplus >= 201703L
-# endif  // __has_include
+#endif  // __has_include(<string_view>) && __cplusplus >= 201703L
+#endif  // __has_include
 #endif  // GTEST_HAS_ABSL
 
 #if GTEST_HAS_ABSL
index 10f774f96606e5b9b87ba34ec7c52ba475ad85c5..cca2e1f2ad98f9ecffbf090962f032eff54568a8 100644 (file)
@@ -26,7 +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.
-//
+
 // The Google C++ Testing and Mocking Framework (Google Test)
 //
 // This header file declares the String class and functions used internally by
 // This header file is #included by gtest-internal.h.
 // It should not be #included by other files.
 
-// GOOGLETEST_CM0001 DO NOT DELETE
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
 
 #ifdef __BORLANDC__
 // string.h is not guaranteed to provide strcpy on C++ Builder.
-# include <mem.h>
+#include <mem.h>
 #endif
 
 #include <string.h>
+
 #include <cstdint>
 #include <string>
 
@@ -123,8 +126,7 @@ class GTEST_API_ String {
   // Unlike strcasecmp(), this function can handle NULL argument(s).
   // A NULL C string is considered different to any non-NULL C string,
   // including the empty string.
-  static bool CaseInsensitiveCStringEquals(const char* lhs,
-                                           const char* rhs);
+  static bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs);
 
   // Compares two wide C strings, ignoring case.  Returns true if and only if
   // they have the same content.
@@ -143,8 +145,8 @@ class GTEST_API_ String {
 
   // Returns true if and only if the given string ends with the given suffix,
   // ignoring case. Any string is considered to end with an empty suffix.
-  static bool EndsWithCaseInsensitive(
-      const std::string& str, const std::string& suffix);
+  static bool EndsWithCaseInsensitive(const std::string& str,
+                                      const std::string& suffix);
 
   // Formats an int value as "%02d".
   static std::string FormatIntWidth2(int value);  // "%02d" for width == 2
@@ -163,7 +165,7 @@ class GTEST_API_ String {
 
  private:
   String();  // Not meant to be instantiated.
-};  // class String
+};           // class String
 
 // Gets the content of the stringstream's buffer as an std::string.  Each '\0'
 // character in the buffer is replaced with "\\0".
index b87a2e2cace33b8cf1d42a2b3bdb44cbb90dc267..6bc02a7de30afc662599742908a2e451895fdaed 100644 (file)
@@ -30,7 +30,9 @@
 // Type utilities needed for implementing typed and type-parameterized
 // tests.
 
-// GOOGLETEST_CM0001 DO NOT DELETE
+// IWYU pragma: private, include "gtest/gtest.h"
+// IWYU pragma: friend gtest/.*
+// IWYU pragma: friend gmock/.*
 
 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
 
 // #ifdef __GNUC__ is too general here.  It is possible to use gcc without using
 // libstdc++ (which is where cxxabi.h comes from).
-# if GTEST_HAS_CXXABI_H_
-#  include <cxxabi.h>
-# elif defined(__HP_aCC)
-#  include <acxx_demangle.h>
-# endif  // GTEST_HASH_CXXABI_H_
+#if GTEST_HAS_CXXABI_H_
+#include <cxxabi.h>
+#elif defined(__HP_aCC)
+#include <acxx_demangle.h>
+#endif  // GTEST_HASH_CXXABI_H_
 
 namespace testing {
 namespace internal {
@@ -101,7 +103,9 @@ std::string GetTypeName() {
 // A unique type indicating an empty node
 struct None {};
 
-# define GTEST_TEMPLATE_ template <typename T> class
+#define GTEST_TEMPLATE_ \
+  template <typename T> \
+  class
 
 // The template "selector" struct TemplateSel<Tmpl> is used to
 // represent Tmpl, which must be a class template with one type
@@ -119,8 +123,7 @@ struct TemplateSel {
   };
 };
 
-# define GTEST_BIND_(TmplSel, T) \
-  TmplSel::template Bind<T>::type
+#define GTEST_BIND_(TmplSel, T) TmplSel::template Bind<T>::type
 
 template <GTEST_TEMPLATE_ Head_, GTEST_TEMPLATE_... Tail_>
 struct Templates {
index 3a10352baae5ba71acb607e671d9bf15d16e79ad..7c0286e1aee89c85360d5067961e34477a5eca78 100644 (file)
@@ -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.
 
-
-
 // This provides interface PrimeTable that determines whether a number is a
 // prime and determines a next prime number. This interface is used
 // in Google Test samples demonstrating use of parameterized tests.
@@ -57,7 +55,7 @@ class OnTheFlyPrimeTable : public PrimeTable {
   bool IsPrime(int n) const override {
     if (n <= 1) return false;
 
-    for (int i = 2; i*i <= n; i++) {
+    for (int i = 2; i * i <= n; i++) {
       // n is divisible by an integer other than 1 and itself.
       if ((n % i) == 0) return false;
     }
@@ -104,13 +102,13 @@ class PreCalculatedPrimeTable : public PrimeTable {
 
     // Checks every candidate for prime number (we know that 2 is the only even
     // prime).
-    for (int i = 2; i*i <= max; i += i%2+1) {
+    for (int i = 2; i * i <= max; i += i % 2 + 1) {
       if (!is_prime_[i]) continue;
 
       // Marks all multiples of i (except i itself) as non-prime.
       // We are starting here from i-th multiplier, because all smaller
       // complex numbers were already marked.
-      for (int j = i*i; j <= max; j += i) {
+      for (int j = i * i; j <= max; j += i) {
         is_prime_[j] = false;
       }
     }
index 1d4275979ff61101bf1ae9c3205f41f40830c336..80b69f415c806c0923c831176ef066b350552aa3 100644 (file)
@@ -52,9 +52,9 @@ bool IsPrime(int n) {
   // Now, we have that n is odd and n >= 3.
 
   // Try to divide n by every odd number i, starting from 3
-  for (int i = 3; ; i += 2) {
+  for (int i = 3;; i += 2) {
     // We only have to try i up to the square root of n
-    if (i > n/i) break;
+    if (i > n / i) break;
 
     // Now, we have i <= n/i < n.
     // If n is divisible by i, n is not prime.
index 36cdac2279aeea702e0d3520c77258e9273726a5..95b4811b87d1192f8e545533e18066d3a9b84b90 100644 (file)
@@ -26,7 +26,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.
 
-
 // This sample shows how to use Google Test listener API to implement
 // a primitive leak checker.
 
@@ -104,14 +103,15 @@ TEST(ListenersTest, LeaksWater) {
 }
 }  // namespace
 
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
   InitGoogleTest(&argc, argv);
 
   bool check_for_leaks = false;
-  if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0 )
+  if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0)
     check_for_leaks = true;
   else
-    printf("%s\n", "Run this program with --check_for_leaks to enable "
+    printf("%s\n",
+           "Run this program with --check_for_leaks to enable "
            "custom leak checking in the tests.");
 
   // If we are given the --check_for_leaks command line flag, installs the
index cb08b61a59a9e16b3657861f1c9609001d2096b2..60f2770ca0e7a3983d87c04b6fe502390df5c551 100644 (file)
 //
 // Writing a unit test using Google C++ testing framework is easy as 1-2-3:
 
-
 // Step 1. Include necessary header files such that the stuff your
 // test logic needs is declared.
 //
 // Don't forget gtest.h, which declares the testing framework.
 
-#include <limits.h>
 #include "sample1.h"
+
+#include <limits.h>
+
 #include "gtest/gtest.h"
 namespace {
 
@@ -69,7 +70,6 @@ namespace {
 //
 // </TechnicalDetails>
 
-
 // Tests Factorial().
 
 // Tests factorial of negative numbers.
@@ -97,9 +97,7 @@ TEST(FactorialTest, Negative) {
 }
 
 // Tests factorial of 0.
-TEST(FactorialTest, Zero) {
-  EXPECT_EQ(1, Factorial(0));
-}
+TEST(FactorialTest, Zero) { EXPECT_EQ(1, Factorial(0)); }
 
 // Tests factorial of positive numbers.
 TEST(FactorialTest, Positive) {
@@ -109,7 +107,6 @@ TEST(FactorialTest, Positive) {
   EXPECT_EQ(40320, Factorial(8));
 }
 
-
 // Tests IsPrime()
 
 // Tests negative input.
index d8e8723965a1dc01ea7f656619b71fb5069849da..be7c4c9949f8ac975a25f303287994b4a5be5aef 100644 (file)
@@ -38,7 +38,7 @@ const char* MyString::CloneCString(const char* a_c_string) {
   if (a_c_string == nullptr) return nullptr;
 
   const size_t len = strlen(a_c_string);
-  char* const clone = new char[ len + 1 ];
+  char* const clone = new char[len + 1];
   memcpy(clone, a_c_string, len + 1);
 
   return clone;
index 0f9868959d215760f4567fe6165e077739947432..15a1ce7781a95fdd991c74c13cd934184aeab3b4 100644 (file)
@@ -34,7 +34,6 @@
 
 #include <string.h>
 
-
 // A simple string class.
 class MyString {
  private:
index 41e31c1767dee55cc5d5c0bea2df267c5d81176d..cd734f943a08726ddde2eb0266e82b5d6eca046e 100644 (file)
@@ -38,6 +38,7 @@
 // needed.
 
 #include "sample2.h"
+
 #include "gtest/gtest.h"
 namespace {
 // In this example, we test the MyString class (a simple string).
@@ -77,8 +78,7 @@ const char kHelloString[] = "Hello, world!";
 TEST(MyString, ConstructorFromCString) {
   const MyString s(kHelloString);
   EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));
-  EXPECT_EQ(sizeof(kHelloString)/sizeof(kHelloString[0]) - 1,
-            s.Length());
+  EXPECT_EQ(sizeof(kHelloString) / sizeof(kHelloString[0]) - 1, s.Length());
 }
 
 // Tests the copy c'tor.
index 659e0f0bb5df62905bb35f9ab038f2c38d3c0e66..bc3ffb9c409348298c2ee3dc0ff58d8912f7019b 100644 (file)
@@ -34,7 +34,6 @@
 
 #include <stddef.h>
 
-
 // Queue is a simple queue implemented as a singled-linked list.
 //
 // The element type must support copy constructor.
@@ -62,7 +61,7 @@ class QueueNode {
       : element_(an_element), next_(nullptr) {}
 
   // We disable the default assignment operator and copy c'tor.
-  const QueueNode& operator = (const QueueNode&);
+  const QueueNode& operator=(const QueueNode&);
   QueueNode(const QueueNode&);
 
   E element_;
@@ -84,7 +83,7 @@ class Queue {
       // 1. Deletes every node.
       QueueNode<E>* node = head_;
       QueueNode<E>* next = node->next();
-      for (; ;) {
+      for (;;) {
         delete node;
         node = next;
         if (node == nullptr) break;
@@ -162,11 +161,11 @@ class Queue {
  private:
   QueueNode<E>* head_;  // The first node of the queue.
   QueueNode<E>* last_;  // The last node of the queue.
-  size_t size_;  // The number of elements in the queue.
+  size_t size_;         // The number of elements in the queue.
 
   // We disallow copying a queue.
   Queue(const Queue&);
-  const Queue& operator = (const Queue&);
+  const Queue& operator=(const Queue&);
 };
 
 #endif  // GOOGLETEST_SAMPLES_SAMPLE3_INL_H_
index b19416d53c95f084efe51bf8ef23cc693f3c5d40..71609c6a09864bdf735de55f431290afda03e28d 100644 (file)
@@ -67,7 +67,6 @@ namespace {
 class QueueTestSmpl3 : public testing::Test {
  protected:  // You should make the members protected s.t. they can be
              // accessed from sub-classes.
-
   // virtual void SetUp() will be called before each test is run.  You
   // should define it if you need to initialize the variables.
   // Otherwise, this can be skipped.
@@ -85,15 +84,13 @@ class QueueTestSmpl3 : public testing::Test {
   // }
 
   // A helper function that some test uses.
-  static int Double(int n) {
-    return 2*n;
-  }
+  static int Double(int n) { return 2 * n; }
 
   // A helper function for testing Queue::Map().
-  void MapTester(const Queue<int> * q) {
+  void MapTester(const Queue<int>* q) {
     // Creates a new queue, where each element is twice as big as the
     // corresponding one in q.
-    const Queue<int> * const new_q = q->Map(Double);
+    const Queue<int>* const new_q = q->Map(Double);
 
     // Verifies that the new queue has the same size as q.
     ASSERT_EQ(q->Size(), new_q->Size());
@@ -124,7 +121,7 @@ TEST_F(QueueTestSmpl3, DefaultConstructor) {
 
 // Tests Dequeue().
 TEST_F(QueueTestSmpl3, Dequeue) {
-  int * n = q0_.Dequeue();
+  int* n = q0_.Dequeue();
   EXPECT_TRUE(n == nullptr);
 
   n = q1_.Dequeue();
index b0ee6093b4a250cf11936ccc8208a612291b8140..489c89b0d34bbfaaac30761e871a0c2f8d7e4e65 100644 (file)
 
 // A sample program demonstrating using Google C++ testing framework.
 
-#include <stdio.h>
-
 #include "sample4.h"
 
+#include <stdio.h>
+
 // Returns the current counter value, and increments it.
-int Counter::Increment() {
-  return counter_++;
-}
+int Counter::Increment() { return counter_++; }
 
 // Returns the current counter value, and decrements it.
 // counter can not be less than 0, return 0 in this case
 int Counter::Decrement() {
   if (counter_ == 0) {
     return counter_;
-  } else  {
+  } else {
     return counter_--;
   }
 }
 
 // Prints the current counter value to STDOUT.
-void Counter::Print() const {
-  printf("%d", counter_);
-}
+void Counter::Print() const { printf("%d", counter_); }
index d5144c0d00f5c7600693ea025802c0d7d5250d2e..fb9973fe666e5e9a3719b49214b71e650d5b71a5 100644 (file)
@@ -27,8 +27,8 @@
 // (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 "sample4.h"
+
 #include "gtest/gtest.h"
 
 namespace {
index 0a21dd2157707fb32c459248b0c5341609ec0614..cc8c0f012e96eb9edac6401451b2a9cfed27f0aa 100644 (file)
@@ -27,7 +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.
 
-
 // This sample teaches how to reuse a test fixture in multiple test
 // cases by deriving sub-fixtures from it.
 //
 
 #include <limits.h>
 #include <time.h>
-#include "gtest/gtest.h"
+
 #include "sample1.h"
 #include "sample3-inl.h"
+#include "gtest/gtest.h"
 namespace {
 // In this sample, we want to ensure that every test finishes within
 // ~5 seconds.  If a test takes longer to run, we consider it a
@@ -81,7 +81,6 @@ class QuickTest : public testing::Test {
   time_t start_time_;
 };
 
-
 // We derive a fixture named IntegerFunctionTest from the QuickTest
 // fixture.  All tests using this fixture will be automatically
 // required to be quick.
@@ -90,7 +89,6 @@ class IntegerFunctionTest : public QuickTest {
   // Therefore the body is empty.
 };
 
-
 // Now we can write tests in the IntegerFunctionTest test case.
 
 // Tests Factorial()
@@ -110,7 +108,6 @@ TEST_F(IntegerFunctionTest, Factorial) {
   EXPECT_EQ(40320, Factorial(8));
 }
 
-
 // Tests IsPrime()
 TEST_F(IntegerFunctionTest, IsPrime) {
   // Tests negative input.
@@ -131,7 +128,6 @@ TEST_F(IntegerFunctionTest, IsPrime) {
   EXPECT_TRUE(IsPrime(23));
 }
 
-
 // The next test case (named "QueueTest") also needs to be quick, so
 // we derive another fixture from QuickTest.
 //
@@ -163,13 +159,10 @@ class QueueTest : public QuickTest {
   Queue<int> q2_;
 };
 
-
 // Now, let's write tests using the QueueTest fixture.
 
 // Tests the default constructor.
-TEST_F(QueueTest, DefaultConstructor) {
-  EXPECT_EQ(0u, q0_.Size());
-}
+TEST_F(QueueTest, DefaultConstructor) { EXPECT_EQ(0u, q0_.Size()); }
 
 // Tests Dequeue().
 TEST_F(QueueTest, Dequeue) {
index da317eed5a0d258605c89e0d88fc43c17c1eb290..cf576f0a5354fb80367825858f4e7e618399af30 100644 (file)
 // (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 sample shows how to test common properties of multiple
 // implementations of the same interface (aka interface tests).
 
 // The interface and its implementations are in this header.
 #include "prime_tables.h"
-
 #include "gtest/gtest.h"
 namespace {
 // First, we define some factory functions for creating instances of
@@ -151,8 +149,7 @@ using testing::Types;
 // the PrimeTableTest fixture defined earlier:
 
 template <class T>
-class PrimeTableTest2 : public PrimeTableTest<T> {
-};
+class PrimeTableTest2 : public PrimeTableTest<T> {};
 
 // Then, declare the test case.  The argument is the name of the test
 // fixture, and also the name of the test case (as usual).  The _P
index e0efc29e4a2a977e1a50a45bb375243c968547d7..3ad22cab8d12414408d0cc936a07b68e398575dc 100644 (file)
@@ -27,7 +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.
 
-
 // This sample shows how to test common properties of multiple
 // implementations of an interface (aka interface tests) using
 // value-parameterized tests. Each test in the test case has
@@ -36,7 +35,6 @@
 
 // The interface and its implementations are in this header.
 #include "prime_tables.h"
-
 #include "gtest/gtest.h"
 namespace {
 
@@ -50,9 +48,7 @@ using ::testing::Values;
 // SetUp() method and delete them in TearDown() method.
 typedef PrimeTable* CreatePrimeTableFunc();
 
-PrimeTable* CreateOnTheFlyPrimeTable() {
-  return new OnTheFlyPrimeTable();
-}
+PrimeTable* CreateOnTheFlyPrimeTable() { return new OnTheFlyPrimeTable(); }
 
 template <size_t max_precalculated>
 PrimeTable* CreatePreCalculatedPrimeTable() {
index 10488b0ea4509a6591f06b05ac5ae14433b652ee..9717e28608e66c3c902f5cdcb083292576342d36 100644 (file)
 // (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 sample shows how to test code relying on some global flag variables.
 // Combine() helps with generating all possible combinations of such flags,
 // and each test is given one combination as a parameter.
 
 // Use class definitions to test from this header.
 #include "prime_tables.h"
-
 #include "gtest/gtest.h"
 namespace {
 
@@ -79,10 +77,10 @@ class HybridPrimeTable : public PrimeTable {
   int max_precalculated_;
 };
 
-using ::testing::TestWithParam;
 using ::testing::Bool;
-using ::testing::Values;
 using ::testing::Combine;
+using ::testing::TestWithParam;
+using ::testing::Values;
 
 // To test all code paths for HybridPrimeTable we must test it with numbers
 // both within and outside PreCalculatedPrimeTable's capacity and also with
index e502d08d73e7d70bede86cbd711754cd09de841c..d627ea7d5776e4a360d56e9b67329af5426b663e 100644 (file)
 // (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 sample shows how to use Google Test listener API to implement
 // an alternative console output and how to use the UnitTest reflection API
-// to enumerate test cases and tests and to inspect their results.
+// to enumerate test suites and tests and to inspect their results.
 
 #include <stdio.h>
 
 using ::testing::EmptyTestEventListener;
 using ::testing::InitGoogleTest;
 using ::testing::Test;
-using ::testing::TestCase;
 using ::testing::TestEventListeners;
 using ::testing::TestInfo;
 using ::testing::TestPartResult;
+using ::testing::TestSuite;
 using ::testing::UnitTest;
 namespace {
 // Provides alternative output mode which produces minimal amount of
@@ -59,29 +58,23 @@ class TersePrinter : public EmptyTestEventListener {
 
   // Called before a test starts.
   void OnTestStart(const TestInfo& test_info) override {
-    fprintf(stdout,
-            "*** Test %s.%s starting.\n",
-            test_info.test_case_name(),
+    fprintf(stdout, "*** Test %s.%s starting.\n", test_info.test_suite_name(),
             test_info.name());
     fflush(stdout);
   }
 
   // Called after a failed assertion or a SUCCEED() invocation.
   void OnTestPartResult(const TestPartResult& test_part_result) override {
-    fprintf(stdout,
-            "%s in %s:%d\n%s\n",
+    fprintf(stdout, "%s in %s:%d\n%s\n",
             test_part_result.failed() ? "*** Failure" : "Success",
-            test_part_result.file_name(),
-            test_part_result.line_number(),
+            test_part_result.file_name(), test_part_result.line_number(),
             test_part_result.summary());
     fflush(stdout);
   }
 
   // Called after a test ends.
   void OnTestEnd(const TestInfo& test_info) override {
-    fprintf(stdout,
-            "*** Test %s.%s ending.\n",
-            test_info.test_case_name(),
+    fprintf(stdout, "*** Test %s.%s ending.\n", test_info.test_suite_name(),
             test_info.name());
     fflush(stdout);
   }
@@ -101,14 +94,15 @@ TEST(CustomOutputTest, Fails) {
 }
 }  // namespace
 
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
   InitGoogleTest(&argc, argv);
 
   bool terse_output = false;
-  if (argc > 1 && strcmp(argv[1], "--terse_output") == 0 )
+  if (argc > 1 && strcmp(argv[1], "--terse_output") == 0)
     terse_output = true;
   else
-    printf("%s\n", "Run this program with --terse_output to change the way "
+    printf("%s\n",
+           "Run this program with --terse_output to change the way "
            "it prints its output.");
 
   UnitTest& unit_test = *UnitTest::GetInstance();
@@ -149,8 +143,7 @@ int main(int argc, char **argv) {
   }
 
   // Test that were meant to fail should not affect the test program outcome.
-  if (unexpectedly_failed_tests == 0)
-    ret_val = 0;
+  if (unexpectedly_failed_tests == 0) ret_val = 0;
 
   return ret_val;
 }
diff --git a/googletest/scripts/README.md b/googletest/scripts/README.md
deleted file mode 100644 (file)
index fa359fe..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-# Please Note:
-
-Files in this directory are no longer supported by the maintainers. They
-represent mosty historical artifacts and supported by the community only. There
-is no guarantee whatsoever that these scripts still work.
diff --git a/googletest/scripts/common.py b/googletest/scripts/common.py
deleted file mode 100644 (file)
index 3c0347a..0000000
+++ /dev/null
@@ -1,83 +0,0 @@
-# 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.
-
-"""Shared utilities for writing scripts for Google Test/Mock."""
-
-__author__ = 'wan@google.com (Zhanyong Wan)'
-
-
-import os
-import re
-
-
-# Matches the line from 'svn info .' output that describes what SVN
-# path the current local directory corresponds to.  For example, in
-# a googletest SVN workspace's trunk/test directory, the output will be:
-#
-# URL: https://googletest.googlecode.com/svn/trunk/test
-_SVN_INFO_URL_RE = re.compile(r'^URL: https://(\w+)\.googlecode\.com/svn(.*)')
-
-
-def GetCommandOutput(command):
-  """Runs the shell command and returns its stdout as a list of lines."""
-
-  f = os.popen(command, 'r')
-  lines = [line.strip() for line in f.readlines()]
-  f.close()
-  return lines
-
-
-def GetSvnInfo():
-  """Returns the project name and the current SVN workspace's root path."""
-
-  for line in GetCommandOutput('svn info .'):
-    m = _SVN_INFO_URL_RE.match(line)
-    if m:
-      project = m.group(1)  # googletest or googlemock
-      rel_path = m.group(2)
-      root = os.path.realpath(rel_path.count('/') * '../')
-      return project, root
-
-  return None, None
-
-
-def GetSvnTrunk():
-  """Returns the current SVN workspace's trunk root path."""
-
-  _, root = GetSvnInfo()
-  return root + '/trunk' if root else None
-
-
-def IsInGTestSvn():
-  project, _ = GetSvnInfo()
-  return project == 'googletest'
-
-
-def IsInGMockSvn():
-  project, _ = GetSvnInfo()
-  return project == 'googlemock'
diff --git a/googletest/scripts/fuse_gtest_files.py b/googletest/scripts/fuse_gtest_files.py
deleted file mode 100755 (executable)
index d0dd464..0000000
+++ /dev/null
@@ -1,253 +0,0 @@
-#!/usr/bin/env python
-#
-# 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.
-
-"""fuse_gtest_files.py v0.2.0
-Fuses Google Test source code into a .h file and a .cc file.
-
-SYNOPSIS
-       fuse_gtest_files.py [GTEST_ROOT_DIR] OUTPUT_DIR
-
-       Scans GTEST_ROOT_DIR for Google Test source code, and generates
-       two files: OUTPUT_DIR/gtest/gtest.h and OUTPUT_DIR/gtest/gtest-all.cc.
-       Then you can build your tests by adding OUTPUT_DIR to the include
-       search path and linking with OUTPUT_DIR/gtest/gtest-all.cc.  These
-       two files contain everything you need to use Google Test.  Hence
-       you can "install" Google Test by copying them to wherever you want.
-
-       GTEST_ROOT_DIR can be omitted and defaults to the parent
-       directory of the directory holding this script.
-
-EXAMPLES
-       ./fuse_gtest_files.py fused_gtest
-       ./fuse_gtest_files.py path/to/unpacked/gtest fused_gtest
-
-This tool is experimental.  In particular, it assumes that there is no
-conditional inclusion of Google Test headers.  Please report any
-problems to googletestframework@googlegroups.com.  You can read
-https://github.com/google/googletest/blob/master/googletest/docs/advanced.md for
-more information.
-"""
-
-__author__ = 'wan@google.com (Zhanyong Wan)'
-
-import os
-import re
-try:
-  from sets import Set as set  # For Python 2.3 compatibility
-except ImportError:
-  pass
-import sys
-
-# We assume that this file is in the scripts/ directory in the Google
-# Test root directory.
-DEFAULT_GTEST_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
-
-# Regex for matching '#include "gtest/..."'.
-INCLUDE_GTEST_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gtest/.+)"')
-
-# Regex for matching '#include "src/..."'.
-INCLUDE_SRC_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(src/.+)"')
-
-# Where to find the source seed files.
-GTEST_H_SEED = 'include/gtest/gtest.h'
-GTEST_SPI_H_SEED = 'include/gtest/gtest-spi.h'
-GTEST_ALL_CC_SEED = 'src/gtest-all.cc'
-
-# Where to put the generated files.
-GTEST_H_OUTPUT = 'gtest/gtest.h'
-GTEST_ALL_CC_OUTPUT = 'gtest/gtest-all.cc'
-
-
-def VerifyFileExists(directory, relative_path):
-  """Verifies that the given file exists; aborts on failure.
-
-  relative_path is the file path relative to the given directory.
-  """
-
-  if not os.path.isfile(os.path.join(directory, relative_path)):
-    print('ERROR: Cannot find %s in directory %s.' % (relative_path,
-                                                      directory))
-    print('Please either specify a valid project root directory '
-          'or omit it on the command line.')
-    sys.exit(1)
-
-
-def ValidateGTestRootDir(gtest_root):
-  """Makes sure gtest_root points to a valid gtest root directory.
-
-  The function aborts the program on failure.
-  """
-
-  VerifyFileExists(gtest_root, GTEST_H_SEED)
-  VerifyFileExists(gtest_root, GTEST_ALL_CC_SEED)
-
-
-def VerifyOutputFile(output_dir, relative_path):
-  """Verifies that the given output file path is valid.
-
-  relative_path is relative to the output_dir directory.
-  """
-
-  # Makes sure the output file either doesn't exist or can be overwritten.
-  output_file = os.path.join(output_dir, relative_path)
-  if os.path.exists(output_file):
-    # TODO(wan@google.com): The following user-interaction doesn't
-    # work with automated processes.  We should provide a way for the
-    # Makefile to force overwriting the files.
-    print('%s already exists in directory %s - overwrite it? (y/N) ' %
-          (relative_path, output_dir))
-    answer = sys.stdin.readline().strip()
-    if answer not in ['y', 'Y']:
-      print('ABORTED.')
-      sys.exit(1)
-
-  # Makes sure the directory holding the output file exists; creates
-  # it and all its ancestors if necessary.
-  parent_directory = os.path.dirname(output_file)
-  if not os.path.isdir(parent_directory):
-    os.makedirs(parent_directory)
-
-
-def ValidateOutputDir(output_dir):
-  """Makes sure output_dir points to a valid output directory.
-
-  The function aborts the program on failure.
-  """
-
-  VerifyOutputFile(output_dir, GTEST_H_OUTPUT)
-  VerifyOutputFile(output_dir, GTEST_ALL_CC_OUTPUT)
-
-
-def FuseGTestH(gtest_root, output_dir):
-  """Scans folder gtest_root to generate gtest/gtest.h in output_dir."""
-
-  output_file = open(os.path.join(output_dir, GTEST_H_OUTPUT), 'w')
-  processed_files = set()  # Holds all gtest headers we've processed.
-
-  def ProcessFile(gtest_header_path):
-    """Processes the given gtest header file."""
-
-    # We don't process the same header twice.
-    if gtest_header_path in processed_files:
-      return
-
-    processed_files.add(gtest_header_path)
-
-    # Reads each line in the given gtest header.
-    for line in open(os.path.join(gtest_root, gtest_header_path), 'r'):
-      m = INCLUDE_GTEST_FILE_REGEX.match(line)
-      if m:
-        # It's '#include "gtest/..."' - let's process it recursively.
-        ProcessFile('include/' + m.group(1))
-      else:
-        # Otherwise we copy the line unchanged to the output file.
-        output_file.write(line)
-
-  ProcessFile(GTEST_H_SEED)
-  output_file.close()
-
-
-def FuseGTestAllCcToFile(gtest_root, output_file):
-  """Scans folder gtest_root to generate gtest/gtest-all.cc in output_file."""
-
-  processed_files = set()
-
-  def ProcessFile(gtest_source_file):
-    """Processes the given gtest source file."""
-
-    # We don't process the same #included file twice.
-    if gtest_source_file in processed_files:
-      return
-
-    processed_files.add(gtest_source_file)
-
-    # Reads each line in the given gtest source file.
-    for line in open(os.path.join(gtest_root, gtest_source_file), 'r'):
-      m = INCLUDE_GTEST_FILE_REGEX.match(line)
-      if m:
-        if 'include/' + m.group(1) == GTEST_SPI_H_SEED:
-          # It's '#include "gtest/gtest-spi.h"'.  This file is not
-          # #included by "gtest/gtest.h", so we need to process it.
-          ProcessFile(GTEST_SPI_H_SEED)
-        else:
-          # It's '#include "gtest/foo.h"' where foo is not gtest-spi.
-          # We treat it as '#include "gtest/gtest.h"', as all other
-          # gtest headers are being fused into gtest.h and cannot be
-          # #included directly.
-
-          # There is no need to #include "gtest/gtest.h" more than once.
-          if not GTEST_H_SEED in processed_files:
-            processed_files.add(GTEST_H_SEED)
-            output_file.write('#include "%s"\n' % (GTEST_H_OUTPUT,))
-      else:
-        m = INCLUDE_SRC_FILE_REGEX.match(line)
-        if m:
-          # It's '#include "src/foo"' - let's process it recursively.
-          ProcessFile(m.group(1))
-        else:
-          output_file.write(line)
-
-  ProcessFile(GTEST_ALL_CC_SEED)
-
-
-def FuseGTestAllCc(gtest_root, output_dir):
-  """Scans folder gtest_root to generate gtest/gtest-all.cc in output_dir."""
-
-  output_file = open(os.path.join(output_dir, GTEST_ALL_CC_OUTPUT), 'w')
-  FuseGTestAllCcToFile(gtest_root, output_file)
-  output_file.close()
-
-
-def FuseGTest(gtest_root, output_dir):
-  """Fuses gtest.h and gtest-all.cc."""
-
-  ValidateGTestRootDir(gtest_root)
-  ValidateOutputDir(output_dir)
-
-  FuseGTestH(gtest_root, output_dir)
-  FuseGTestAllCc(gtest_root, output_dir)
-
-
-def main():
-  argc = len(sys.argv)
-  if argc == 2:
-    # fuse_gtest_files.py OUTPUT_DIR
-    FuseGTest(DEFAULT_GTEST_ROOT_DIR, sys.argv[1])
-  elif argc == 3:
-    # fuse_gtest_files.py GTEST_ROOT_DIR OUTPUT_DIR
-    FuseGTest(sys.argv[1], sys.argv[2])
-  else:
-    print(__doc__)
-    sys.exit(1)
-
-
-if __name__ == '__main__':
-  main()
diff --git a/googletest/scripts/gen_gtest_pred_impl.py b/googletest/scripts/gen_gtest_pred_impl.py
deleted file mode 100755 (executable)
index e09a6e0..0000000
+++ /dev/null
@@ -1,733 +0,0 @@
-#!/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.
-
-"""gen_gtest_pred_impl.py v0.1
-
-Generates the implementation of Google Test predicate assertions and
-accompanying tests.
-
-Usage:
-
-  gen_gtest_pred_impl.py MAX_ARITY
-
-where MAX_ARITY is a positive integer.
-
-The command generates the implementation of up-to MAX_ARITY-ary
-predicate assertions, and writes it to file gtest_pred_impl.h in the
-directory where the script is.  It also generates the accompanying
-unit test in file gtest_pred_impl_unittest.cc.
-"""
-
-__author__ = 'wan@google.com (Zhanyong Wan)'
-
-import os
-import sys
-import time
-
-# Where this script is.
-SCRIPT_DIR = os.path.dirname(sys.argv[0])
-
-# Where to store the generated header.
-HEADER = os.path.join(SCRIPT_DIR, '../include/gtest/gtest_pred_impl.h')
-
-# Where to store the generated unit test.
-UNIT_TEST = os.path.join(SCRIPT_DIR, '../test/gtest_pred_impl_unittest.cc')
-
-
-def HeaderPreamble(n):
-  """Returns the preamble for the header file.
-
-  Args:
-    n:  the maximum arity of the predicate macros to be generated.
-  """
-
-  # A map that defines the values used in the preamble template.
-  DEFS = {
-    'today' : time.strftime('%m/%d/%Y'),
-    'year' : time.strftime('%Y'),
-    'command' : '%s %s' % (os.path.basename(sys.argv[0]), n),
-    'n' : n
-    }
-
-  return (
-  """// Copyright 2006, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// This file is AUTOMATICALLY GENERATED on %(today)s by command
-// '%(command)s'.  DO NOT EDIT BY HAND!
-//
-// Implements a family of generic predicate assertion macros.
-// GOOGLETEST_CM0001 DO NOT DELETE
-
-
-#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
-#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
-
-#include "gtest/gtest.h"
-
-namespace testing {
-
-// This header implements a family of generic predicate assertion
-// macros:
-//
-//   ASSERT_PRED_FORMAT1(pred_format, v1)
-//   ASSERT_PRED_FORMAT2(pred_format, v1, v2)
-//   ...
-//
-// where pred_format is a function or functor that takes n (in the
-// case of ASSERT_PRED_FORMATn) values and their source expression
-// text, and returns a testing::AssertionResult.  See the definition
-// of ASSERT_EQ in gtest.h for an example.
-//
-// If you don't care about formatting, you can use the more
-// restrictive version:
-//
-//   ASSERT_PRED1(pred, v1)
-//   ASSERT_PRED2(pred, v1, v2)
-//   ...
-//
-// where pred is an n-ary function or functor that returns bool,
-// and the values v1, v2, ..., must support the << operator for
-// streaming to std::ostream.
-//
-// We also define the EXPECT_* variations.
-//
-// For now we only support predicates whose arity is at most %(n)s.
-// Please email googletestframework@googlegroups.com if you need
-// support for higher arities.
-
-// GTEST_ASSERT_ is the basic statement to which all of the assertions
-// in this file reduce.  Don't use this in your code.
-
-#define GTEST_ASSERT_(expression, on_failure) \\
-  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \\
-  if (const ::testing::AssertionResult gtest_ar = (expression)) \\
-    ; \\
-  else \\
-    on_failure(gtest_ar.failure_message())
-""" % DEFS)
-
-
-def Arity(n):
-  """Returns the English name of the given arity."""
-
-  if n < 0:
-    return None
-  elif n <= 3:
-    return ['nullary', 'unary', 'binary', 'ternary'][n]
-  else:
-    return '%s-ary' % n
-
-
-def Title(word):
-  """Returns the given word in title case.  The difference between
-  this and string's title() method is that Title('4-ary') is '4-ary'
-  while '4-ary'.title() is '4-Ary'."""
-
-  return word[0].upper() + word[1:]
-
-
-def OneTo(n):
-  """Returns the list [1, 2, 3, ..., n]."""
-
-  return range(1, n + 1)
-
-
-def Iter(n, format, sep=''):
-  """Given a positive integer n, a format string that contains 0 or
-  more '%s' format specs, and optionally a separator string, returns
-  the join of n strings, each formatted with the format string on an
-  iterator ranged from 1 to n.
-
-  Example:
-
-  Iter(3, 'v%s', sep=', ') returns 'v1, v2, v3'.
-  """
-
-  # How many '%s' specs are in format?
-  spec_count = len(format.split('%s')) - 1
-  return sep.join([format % (spec_count * (i,)) for i in OneTo(n)])
-
-
-def ImplementationForArity(n):
-  """Returns the implementation of n-ary predicate assertions."""
-
-  # A map the defines the values used in the implementation template.
-  DEFS = {
-    'n' : str(n),
-    'vs' : Iter(n, 'v%s', sep=', '),
-    'vts' : Iter(n, '#v%s', sep=', '),
-    'arity' : Arity(n),
-    'Arity' : Title(Arity(n))
-    }
-
-  impl = """
-
-// Helper function for implementing {EXPECT|ASSERT}_PRED%(n)s.  Don't use
-// this in your code.
-template <typename Pred""" % DEFS
-
-  impl += Iter(n, """,
-          typename T%s""")
-
-  impl += """>
-AssertionResult AssertPred%(n)sHelper(const char* pred_text""" % DEFS
-
-  impl += Iter(n, """,
-                                  const char* e%s""")
-
-  impl += """,
-                                  Pred pred"""
-
-  impl += Iter(n, """,
-                                  const T%s& v%s""")
-
-  impl += """) {
-  if (pred(%(vs)s)) return AssertionSuccess();
-
-""" % DEFS
-
-  impl += '  return AssertionFailure() << pred_text << "("'
-
-  impl += Iter(n, """
-                            << e%s""", sep=' << ", "')
-
-  impl += ' << ") evaluates to false, where"'
-
-  impl += Iter(
-      n, """
-      << "\\n" << e%s << " evaluates to " << ::testing::PrintToString(v%s)"""
-  )
-
-  impl += """;
-}
-
-// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
-// Don't use this in your code.
-#define GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, on_failure)\\
-  GTEST_ASSERT_(pred_format(%(vts)s, %(vs)s), \\
-                on_failure)
-
-// Internal macro for implementing {EXPECT|ASSERT}_PRED%(n)s.  Don't use
-// this in your code.
-#define GTEST_PRED%(n)s_(pred, %(vs)s, on_failure)\\
-  GTEST_ASSERT_(::testing::AssertPred%(n)sHelper(#pred""" % DEFS
-
-  impl += Iter(n, """, \\
-                                             #v%s""")
-
-  impl += """, \\
-                                             pred"""
-
-  impl += Iter(n, """, \\
-                                             v%s""")
-
-  impl += """), on_failure)
-
-// %(Arity)s predicate assertion macros.
-#define EXPECT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
-  GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_NONFATAL_FAILURE_)
-#define EXPECT_PRED%(n)s(pred, %(vs)s) \\
-  GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_NONFATAL_FAILURE_)
-#define ASSERT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\
-  GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_FATAL_FAILURE_)
-#define ASSERT_PRED%(n)s(pred, %(vs)s) \\
-  GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_FATAL_FAILURE_)
-
-""" % DEFS
-
-  return impl
-
-
-def HeaderPostamble():
-  """Returns the postamble for the header file."""
-
-  return """
-
-}  // namespace testing
-
-#endif  // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
-"""
-
-
-def GenerateFile(path, content):
-  """Given a file path and a content string
-     overwrites it with the given content.
-  """
-  print 'Updating file %s . . .' % path
-  f = file(path, 'w+')
-  print >>f, content,
-  f.close()
-
-  print 'File %s has been updated.' % path
-
-
-def GenerateHeader(n):
-  """Given the maximum arity n, updates the header file that implements
-  the predicate assertions.
-  """
-  GenerateFile(HEADER,
-               HeaderPreamble(n)
-               + ''.join([ImplementationForArity(i) for i in OneTo(n)])
-               + HeaderPostamble())
-
-
-def UnitTestPreamble():
-  """Returns the preamble for the unit test file."""
-
-  # A map that defines the values used in the preamble template.
-  DEFS = {
-    'today' : time.strftime('%m/%d/%Y'),
-    'year' : time.strftime('%Y'),
-    'command' : '%s %s' % (os.path.basename(sys.argv[0]), sys.argv[1]),
-    }
-
-  return (
-  """// Copyright 2006, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// This file is AUTOMATICALLY GENERATED on %(today)s by command
-// '%(command)s'.  DO NOT EDIT BY HAND!
-
-// Regression test for gtest_pred_impl.h
-//
-// This file is generated by a script and quite long.  If you intend to
-// learn how Google Test works by reading its unit tests, read
-// gtest_unittest.cc instead.
-//
-// This is intended as a regression test for the Google Test predicate
-// assertions.  We compile it as part of the gtest_unittest target
-// only to keep the implementation tidy and compact, as it is quite
-// involved to set up the stage for testing Google Test using Google
-// Test itself.
-//
-// Currently, gtest_unittest takes ~11 seconds to run in the testing
-// daemon.  In the future, if it grows too large and needs much more
-// time to finish, we should consider separating this file into a
-// stand-alone regression test.
-
-#include <iostream>
-
-#include "gtest/gtest.h"
-#include "gtest/gtest-spi.h"
-
-// A user-defined data type.
-struct Bool {
-  explicit Bool(int val) : value(val != 0) {}
-
-  bool operator>(int n) const { return value > Bool(n).value; }
-
-  Bool operator+(const Bool& rhs) const { return Bool(value + rhs.value); }
-
-  bool operator==(const Bool& rhs) const { return value == rhs.value; }
-
-  bool value;
-};
-
-// Enables Bool to be used in assertions.
-std::ostream& operator<<(std::ostream& os, const Bool& x) {
-  return os << (x.value ? "true" : "false");
-}
-
-""" % DEFS)
-
-
-def TestsForArity(n):
-  """Returns the tests for n-ary predicate assertions."""
-
-  # A map that defines the values used in the template for the tests.
-  DEFS = {
-    'n' : n,
-    'es' : Iter(n, 'e%s', sep=', '),
-    'vs' : Iter(n, 'v%s', sep=', '),
-    'vts' : Iter(n, '#v%s', sep=', '),
-    'tvs' : Iter(n, 'T%s v%s', sep=', '),
-    'int_vs' : Iter(n, 'int v%s', sep=', '),
-    'Bool_vs' : Iter(n, 'Bool v%s', sep=', '),
-    'types' : Iter(n, 'typename T%s', sep=', '),
-    'v_sum' : Iter(n, 'v%s', sep=' + '),
-    'arity' : Arity(n),
-    'Arity' : Title(Arity(n)),
-    }
-
-  tests = (
-  """// Sample functions/functors for testing %(arity)s predicate assertions.
-
-// A %(arity)s predicate function.
-template <%(types)s>
-bool PredFunction%(n)s(%(tvs)s) {
-  return %(v_sum)s > 0;
-}
-
-// The following two functions are needed because a compiler doesn't have
-// a context yet to know which template function must be instantiated.
-bool PredFunction%(n)sInt(%(int_vs)s) {
-  return %(v_sum)s > 0;
-}
-bool PredFunction%(n)sBool(%(Bool_vs)s) {
-  return %(v_sum)s > 0;
-}
-""" % DEFS)
-
-  tests += """
-// A %(arity)s predicate functor.
-struct PredFunctor%(n)s {
-  template <%(types)s>
-  bool operator()(""" % DEFS
-
-  tests += Iter(n, 'const T%s& v%s', sep=""",
-                  """)
-
-  tests += """) {
-    return %(v_sum)s > 0;
-  }
-};
-""" % DEFS
-
-  tests += """
-// A %(arity)s predicate-formatter function.
-template <%(types)s>
-testing::AssertionResult PredFormatFunction%(n)s(""" % DEFS
-
-  tests += Iter(n, 'const char* e%s', sep=""",
-                                             """)
-
-  tests += Iter(n, """,
-                                             const T%s& v%s""")
-
-  tests += """) {
-  if (PredFunction%(n)s(%(vs)s))
-    return testing::AssertionSuccess();
-
-  return testing::AssertionFailure()
-      << """ % DEFS
-
-  tests += Iter(n, 'e%s', sep=' << " + " << ')
-
-  tests += """
-      << " is expected to be positive, but evaluates to "
-      << %(v_sum)s << ".";
-}
-""" % DEFS
-
-  tests += """
-// A %(arity)s predicate-formatter functor.
-struct PredFormatFunctor%(n)s {
-  template <%(types)s>
-  testing::AssertionResult operator()(""" % DEFS
-
-  tests += Iter(n, 'const char* e%s', sep=""",
-                                      """)
-
-  tests += Iter(n, """,
-                                      const T%s& v%s""")
-
-  tests += """) const {
-    return PredFormatFunction%(n)s(%(es)s, %(vs)s);
-  }
-};
-""" % DEFS
-
-  tests += """
-// Tests for {EXPECT|ASSERT}_PRED_FORMAT%(n)s.
-
-class Predicate%(n)sTest : public testing::Test {
- protected:
-  void SetUp() override {
-    expected_to_finish_ = true;
-    finished_ = false;""" % DEFS
-
-  tests += """
-    """ + Iter(n, 'n%s_ = ') + """0;
-  }
-"""
-
-  tests += """
-  void TearDown() override {
-    // Verifies that each of the predicate's arguments was evaluated
-    // exactly once."""
-
-  tests += ''.join(["""
-    EXPECT_EQ(1, n%s_) <<
-        "The predicate assertion didn't evaluate argument %s "
-        "exactly once.";""" % (i, i + 1) for i in OneTo(n)])
-
-  tests += """
-
-    // Verifies that the control flow in the test function is expected.
-    if (expected_to_finish_ && !finished_) {
-      FAIL() << "The predicate assertion unexpactedly aborted the test.";
-    } else if (!expected_to_finish_ && finished_) {
-      FAIL() << "The failed predicate assertion didn't abort the test "
-                "as expected.";
-    }
-  }
-
-  // true if and only if the test function is expected to run to finish.
-  static bool expected_to_finish_;
-
-  // true if and only if the test function did run to finish.
-  static bool finished_;
-""" % DEFS
-
-  tests += Iter(n, """
-  static int n%s_;""")
-
-  tests += """
-};
-
-bool Predicate%(n)sTest::expected_to_finish_;
-bool Predicate%(n)sTest::finished_;
-""" % DEFS
-
-  tests += Iter(n, """int Predicate%%(n)sTest::n%s_;
-""") % DEFS
-
-  tests += """
-typedef Predicate%(n)sTest EXPECT_PRED_FORMAT%(n)sTest;
-typedef Predicate%(n)sTest ASSERT_PRED_FORMAT%(n)sTest;
-typedef Predicate%(n)sTest EXPECT_PRED%(n)sTest;
-typedef Predicate%(n)sTest ASSERT_PRED%(n)sTest;
-""" % DEFS
-
-  def GenTest(use_format, use_assert, expect_failure,
-              use_functor, use_user_type):
-    """Returns the test for a predicate assertion macro.
-
-    Args:
-      use_format:     true if and only if the assertion is a *_PRED_FORMAT*.
-      use_assert:     true if and only if the assertion is a ASSERT_*.
-      expect_failure: true if and only if the assertion is expected to fail.
-      use_functor:    true if and only if the first argument of the assertion is
-                      a functor (as opposed to a function)
-      use_user_type:  true if and only if the predicate functor/function takes
-                      argument(s) of a user-defined type.
-
-    Example:
-
-      GenTest(1, 0, 0, 1, 0) returns a test that tests the behavior
-      of a successful EXPECT_PRED_FORMATn() that takes a functor
-      whose arguments have built-in types."""
-
-    if use_assert:
-      assrt = 'ASSERT'  # 'assert' is reserved, so we cannot use
-      # that identifier here.
-    else:
-      assrt = 'EXPECT'
-
-    assertion = assrt + '_PRED'
-
-    if use_format:
-      pred_format = 'PredFormat'
-      assertion += '_FORMAT'
-    else:
-      pred_format = 'Pred'
-
-    assertion += '%(n)s' % DEFS
-
-    if use_functor:
-      pred_format_type = 'functor'
-      pred_format += 'Functor%(n)s()'
-    else:
-      pred_format_type = 'function'
-      pred_format += 'Function%(n)s'
-      if not use_format:
-        if use_user_type:
-          pred_format += 'Bool'
-        else:
-          pred_format += 'Int'
-
-    test_name = pred_format_type.title()
-
-    if use_user_type:
-      arg_type = 'user-defined type (Bool)'
-      test_name += 'OnUserType'
-      if expect_failure:
-        arg = 'Bool(n%s_++)'
-      else:
-        arg = 'Bool(++n%s_)'
-    else:
-      arg_type = 'built-in type (int)'
-      test_name += 'OnBuiltInType'
-      if expect_failure:
-        arg = 'n%s_++'
-      else:
-        arg = '++n%s_'
-
-    if expect_failure:
-      successful_or_failed = 'failed'
-      expected_or_not = 'expected.'
-      test_name +=  'Failure'
-    else:
-      successful_or_failed = 'successful'
-      expected_or_not = 'UNEXPECTED!'
-      test_name +=  'Success'
-
-    # A map that defines the values used in the test template.
-    defs = DEFS.copy()
-    defs.update({
-      'assert' : assrt,
-      'assertion' : assertion,
-      'test_name' : test_name,
-      'pf_type' : pred_format_type,
-      'pf' : pred_format,
-      'arg_type' : arg_type,
-      'arg' : arg,
-      'successful' : successful_or_failed,
-      'expected' : expected_or_not,
-      })
-
-    test = """
-// Tests a %(successful)s %(assertion)s where the
-// predicate-formatter is a %(pf_type)s on a %(arg_type)s.
-TEST_F(%(assertion)sTest, %(test_name)s) {""" % defs
-
-    indent = (len(assertion) + 3)*' '
-    extra_indent = ''
-
-    if expect_failure:
-      extra_indent = '  '
-      if use_assert:
-        test += """
-  expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT"""
-      else:
-        test += """
-  EXPECT_NONFATAL_FAILURE({  // NOLINT"""
-
-    test += '\n' + extra_indent + """  %(assertion)s(%(pf)s""" % defs
-
-    test = test % defs
-    test += Iter(n, ',\n' + indent + extra_indent + '%(arg)s' % defs)
-    test += ');\n' + extra_indent + '  finished_ = true;\n'
-
-    if expect_failure:
-      test += '  }, "");\n'
-
-    test += '}\n'
-    return test
-
-  # Generates tests for all 2**6 = 64 combinations.
-  tests += ''.join([GenTest(use_format, use_assert, expect_failure,
-                            use_functor, use_user_type)
-                    for use_format in [0, 1]
-                    for use_assert in [0, 1]
-                    for expect_failure in [0, 1]
-                    for use_functor in [0, 1]
-                    for use_user_type in [0, 1]
-                    ])
-
-  return tests
-
-
-def UnitTestPostamble():
-  """Returns the postamble for the tests."""
-
-  return ''
-
-
-def GenerateUnitTest(n):
-  """Returns the tests for up-to n-ary predicate assertions."""
-
-  GenerateFile(UNIT_TEST,
-               UnitTestPreamble()
-               + ''.join([TestsForArity(i) for i in OneTo(n)])
-               + UnitTestPostamble())
-
-
-def _Main():
-  """The entry point of the script.  Generates the header file and its
-  unit test."""
-
-  if len(sys.argv) != 2:
-    print __doc__
-    print 'Author: ' + __author__
-    sys.exit(1)
-
-  n = int(sys.argv[1])
-  GenerateHeader(n)
-  GenerateUnitTest(n)
-
-
-if __name__ == '__main__':
-  _Main()
diff --git a/googletest/scripts/gtest-config.in b/googletest/scripts/gtest-config.in
deleted file mode 100755 (executable)
index 780f843..0000000
+++ /dev/null
@@ -1,274 +0,0 @@
-#!/bin/sh
-
-# These variables are automatically filled in by the configure script.
-name="@PACKAGE_TARNAME@"
-version="@PACKAGE_VERSION@"
-
-show_usage()
-{
-  echo "Usage: gtest-config [OPTIONS...]"
-}
-
-show_help()
-{
-  show_usage
-  cat <<\EOF
-
-The `gtest-config' script provides access to the necessary compile and linking
-flags to connect with Google C++ Testing Framework, both in a build prior to
-installation, and on the system proper after installation. The installation
-overrides may be issued in combination with any other queries, but will only
-affect installation queries if called on a built but not installed gtest. The
-installation queries may not be issued with any other types of queries, and
-only one installation query may be made at a time. The version queries and
-compiler flag queries may be combined as desired but not mixed. Different
-version queries are always combined with logical "and" semantics, and only the
-last of any particular query is used while all previous ones ignored. All
-versions must be specified as a sequence of numbers separated by periods.
-Compiler flag queries output the union of the sets of flags when combined.
-
- Examples:
-  gtest-config --min-version=1.0 || echo "Insufficient Google Test version."
-
-  g++ $(gtest-config --cppflags --cxxflags) -o foo.o -c foo.cpp
-  g++ $(gtest-config --ldflags --libs) -o foo foo.o
-
-  # When using a built but not installed Google Test:
-  g++ $(../../my_gtest_build/scripts/gtest-config ...) ...
-
-  # When using an installed Google Test, but with installation overrides:
-  export GTEST_PREFIX="/opt"
-  g++ $(gtest-config --libdir="/opt/lib64" ...) ...
-
- Help:
-  --usage                    brief usage information
-  --help                     display this help message
-
- Installation Overrides:
-  --prefix=<dir>             overrides the installation prefix
-  --exec-prefix=<dir>        overrides the executable installation prefix
-  --libdir=<dir>             overrides the library installation prefix
-  --includedir=<dir>         overrides the header file installation prefix
-
- Installation Queries:
-  --prefix                   installation prefix
-  --exec-prefix              executable installation prefix
-  --libdir                   library installation directory
-  --includedir               header file installation directory
-  --version                  the version of the Google Test installation
-
- Version Queries:
-  --min-version=VERSION      return 0 if the version is at least VERSION
-  --exact-version=VERSION    return 0 if the version is exactly VERSION
-  --max-version=VERSION      return 0 if the version is at most VERSION
-
- Compilation Flag Queries:
-  --cppflags                 compile flags specific to the C-like preprocessors
-  --cxxflags                 compile flags appropriate for C++ programs
-  --ldflags                  linker flags
-  --libs                     libraries for linking
-
-EOF
-}
-
-# This function bounds our version with a min and a max. It uses some clever
-# POSIX-compliant variable expansion to portably do all the work in the shell
-# and avoid any dependency on a particular "sed" or "awk" implementation.
-# Notable is that it will only ever compare the first 3 components of versions.
-# Further components will be cleanly stripped off. All versions must be
-# unadorned, so "v1.0" will *not* work. The minimum version must be in $1, and
-# the max in $2. TODO(chandlerc@google.com): If this ever breaks, we should
-# investigate expanding this via autom4te from AS_VERSION_COMPARE rather than
-# continuing to maintain our own shell version.
-check_versions()
-{
-  major_version=${version%%.*}
-  minor_version="0"
-  point_version="0"
-  if test "${version#*.}" != "${version}"; then
-    minor_version=${version#*.}
-    minor_version=${minor_version%%.*}
-  fi
-  if test "${version#*.*.}" != "${version}"; then
-    point_version=${version#*.*.}
-    point_version=${point_version%%.*}
-  fi
-
-  min_version="$1"
-  min_major_version=${min_version%%.*}
-  min_minor_version="0"
-  min_point_version="0"
-  if test "${min_version#*.}" != "${min_version}"; then
-    min_minor_version=${min_version#*.}
-    min_minor_version=${min_minor_version%%.*}
-  fi
-  if test "${min_version#*.*.}" != "${min_version}"; then
-    min_point_version=${min_version#*.*.}
-    min_point_version=${min_point_version%%.*}
-  fi
-
-  max_version="$2"
-  max_major_version=${max_version%%.*}
-  max_minor_version="0"
-  max_point_version="0"
-  if test "${max_version#*.}" != "${max_version}"; then
-    max_minor_version=${max_version#*.}
-    max_minor_version=${max_minor_version%%.*}
-  fi
-  if test "${max_version#*.*.}" != "${max_version}"; then
-    max_point_version=${max_version#*.*.}
-    max_point_version=${max_point_version%%.*}
-  fi
-
-  test $(($major_version)) -lt $(($min_major_version)) && exit 1
-  if test $(($major_version)) -eq $(($min_major_version)); then
-    test $(($minor_version)) -lt $(($min_minor_version)) && exit 1
-    if test $(($minor_version)) -eq $(($min_minor_version)); then
-      test $(($point_version)) -lt $(($min_point_version)) && exit 1
-    fi
-  fi
-
-  test $(($major_version)) -gt $(($max_major_version)) && exit 1
-  if test $(($major_version)) -eq $(($max_major_version)); then
-    test $(($minor_version)) -gt $(($max_minor_version)) && exit 1
-    if test $(($minor_version)) -eq $(($max_minor_version)); then
-      test $(($point_version)) -gt $(($max_point_version)) && exit 1
-    fi
-  fi
-
-  exit 0
-}
-
-# Show the usage line when no arguments are specified.
-if test $# -eq 0; then
-  show_usage
-  exit 1
-fi
-
-while test $# -gt 0; do
-  case $1 in
-    --usage)          show_usage;         exit 0;;
-    --help)           show_help;          exit 0;;
-
-    # Installation overrides
-    --prefix=*)       GTEST_PREFIX=${1#--prefix=};;
-    --exec-prefix=*)  GTEST_EXEC_PREFIX=${1#--exec-prefix=};;
-    --libdir=*)       GTEST_LIBDIR=${1#--libdir=};;
-    --includedir=*)   GTEST_INCLUDEDIR=${1#--includedir=};;
-
-    # Installation queries
-    --prefix|--exec-prefix|--libdir|--includedir|--version)
-      if test -n "${do_query}"; then
-        show_usage
-        exit 1
-      fi
-      do_query=${1#--}
-      ;;
-
-    # Version checking
-    --min-version=*)
-      do_check_versions=yes
-      min_version=${1#--min-version=}
-      ;;
-    --max-version=*)
-      do_check_versions=yes
-      max_version=${1#--max-version=}
-      ;;
-    --exact-version=*)
-      do_check_versions=yes
-      exact_version=${1#--exact-version=}
-      ;;
-
-    # Compiler flag output
-    --cppflags)       echo_cppflags=yes;;
-    --cxxflags)       echo_cxxflags=yes;;
-    --ldflags)        echo_ldflags=yes;;
-    --libs)           echo_libs=yes;;
-
-    # Everything else is an error
-    *)                show_usage;         exit 1;;
-  esac
-  shift
-done
-
-# These have defaults filled in by the configure script but can also be
-# overridden by environment variables or command line parameters.
-prefix="${GTEST_PREFIX:-@prefix@}"
-exec_prefix="${GTEST_EXEC_PREFIX:-@exec_prefix@}"
-libdir="${GTEST_LIBDIR:-@libdir@}"
-includedir="${GTEST_INCLUDEDIR:-@includedir@}"
-
-# We try and detect if our binary is not located at its installed location. If
-# it's not, we provide variables pointing to the source and build tree rather
-# than to the install tree. This allows building against a just-built gtest
-# rather than an installed gtest.
-bindir="@bindir@"
-this_relative_bindir=`dirname $0`
-this_bindir=`cd ${this_relative_bindir}; pwd -P`
-if test "${this_bindir}" = "${this_bindir%${bindir}}"; then
-  # The path to the script doesn't end in the bindir sequence from Autoconf,
-  # assume that we are in a build tree.
-  build_dir=`dirname ${this_bindir}`
-  src_dir=`cd ${this_bindir}; cd @top_srcdir@; pwd -P`
-
-  # TODO(chandlerc@google.com): This is a dangerous dependency on libtool, we
-  # should work to remove it, and/or remove libtool altogether, replacing it
-  # with direct references to the library and a link path.
-  gtest_libs="${build_dir}/lib/libgtest.la @PTHREAD_CFLAGS@ @PTHREAD_LIBS@"
-  gtest_ldflags=""
-
-  # We provide hooks to include from either the source or build dir, where the
-  # build dir is always preferred. This will potentially allow us to write
-  # build rules for generated headers and have them automatically be preferred
-  # over provided versions.
-  gtest_cppflags="-I${build_dir}/include -I${src_dir}/include"
-  gtest_cxxflags="@PTHREAD_CFLAGS@"
-else
-  # We're using an installed gtest, although it may be staged under some
-  # prefix. Assume (as our own libraries do) that we can resolve the prefix,
-  # and are present in the dynamic link paths.
-  gtest_ldflags="-L${libdir}"
-  gtest_libs="-l${name} @PTHREAD_CFLAGS@ @PTHREAD_LIBS@"
-  gtest_cppflags="-I${includedir}"
-  gtest_cxxflags="@PTHREAD_CFLAGS@"
-fi
-
-# Do an installation query if requested.
-if test -n "$do_query"; then
-  case $do_query in
-    prefix)           echo $prefix;       exit 0;;
-    exec-prefix)      echo $exec_prefix;  exit 0;;
-    libdir)           echo $libdir;       exit 0;;
-    includedir)       echo $includedir;   exit 0;;
-    version)          echo $version;      exit 0;;
-    *)                show_usage;         exit 1;;
-  esac
-fi
-
-# Do a version check if requested.
-if test "$do_check_versions" = "yes"; then
-  # Make sure we didn't receive a bad combination of parameters.
-  test "$echo_cppflags" = "yes" && show_usage && exit 1
-  test "$echo_cxxflags" = "yes" && show_usage && exit 1
-  test "$echo_ldflags" = "yes"  && show_usage && exit 1
-  test "$echo_libs" = "yes"     && show_usage && exit 1
-
-  if test "$exact_version" != ""; then
-    check_versions $exact_version $exact_version
-    # unreachable
-  else
-    check_versions ${min_version:-0.0.0} ${max_version:-9999.9999.9999}
-    # unreachable
-  fi
-fi
-
-# Do the output in the correct order so that these can be used in-line of
-# a compiler invocation.
-output=""
-test "$echo_cppflags" = "yes" && output="$output $gtest_cppflags"
-test "$echo_cxxflags" = "yes" && output="$output $gtest_cxxflags"
-test "$echo_ldflags" = "yes"  && output="$output $gtest_ldflags"
-test "$echo_libs" = "yes"     && output="$output $gtest_libs"
-echo $output
-
-exit 0
diff --git a/googletest/scripts/release_docs.py b/googletest/scripts/release_docs.py
deleted file mode 100755 (executable)
index 8d24f28..0000000
+++ /dev/null
@@ -1,158 +0,0 @@
-#!/usr/bin/env python
-#
-# 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.
-
-"""Script for branching Google Test/Mock wiki pages for a new version.
-
-SYNOPSIS
-       release_docs.py NEW_RELEASE_VERSION
-
-       Google Test and Google Mock's external user documentation is in
-       interlinked wiki files.  When we release a new version of
-       Google Test or Google Mock, we need to branch the wiki files
-       such that users of a specific version of Google Test/Mock can
-       look up documentation relevant for that version.  This script
-       automates that process by:
-
-         - branching the current wiki pages (which document the
-           behavior of the SVN trunk head) to pages for the specified
-           version (e.g. branching FAQ.wiki to V2_6_FAQ.wiki when
-           NEW_RELEASE_VERSION is 2.6);
-         - updating the links in the branched files to point to the branched
-           version (e.g. a link in V2_6_FAQ.wiki that pointed to
-           Primer.wiki#Anchor will now point to V2_6_Primer.wiki#Anchor).
-
-       NOTE: NEW_RELEASE_VERSION must be a NEW version number for
-       which the wiki pages don't yet exist; otherwise you'll get SVN
-       errors like "svn: Path 'V1_7_PumpManual.wiki' is not a
-       directory" when running the script.
-
-EXAMPLE
-       $ cd PATH/TO/GTEST_SVN_WORKSPACE/trunk
-       $ scripts/release_docs.py 2.6  # create wiki pages for v2.6
-       $ svn status                   # verify the file list
-       $ svn diff                     # verify the file contents
-       $ svn commit -m "release wiki pages for v2.6"
-"""
-
-__author__ = 'wan@google.com (Zhanyong Wan)'
-
-import os
-import re
-import sys
-
-import common
-
-
-# Wiki pages that shouldn't be branched for every gtest/gmock release.
-GTEST_UNVERSIONED_WIKIS = ['DevGuide.wiki']
-GMOCK_UNVERSIONED_WIKIS = [
-    'DesignDoc.wiki',
-    'DevGuide.wiki',
-    'KnownIssues.wiki'
-    ]
-
-
-def DropWikiSuffix(wiki_filename):
-  """Removes the .wiki suffix (if any) from the given filename."""
-
-  return (wiki_filename[:-len('.wiki')] if wiki_filename.endswith('.wiki')
-          else wiki_filename)
-
-
-class WikiBrancher(object):
-  """Branches ..."""
-
-  def __init__(self, dot_version):
-    self.project, svn_root_path = common.GetSvnInfo()
-    if self.project not in ('googletest', 'googlemock'):
-      sys.exit('This script must be run in a gtest or gmock SVN workspace.')
-    self.wiki_dir = svn_root_path + '/wiki'
-    # Turn '2.6' to 'V2_6_'.
-    self.version_prefix = 'V' + dot_version.replace('.', '_') + '_'
-    self.files_to_branch = self.GetFilesToBranch()
-    page_names = [DropWikiSuffix(f) for f in self.files_to_branch]
-    # A link to Foo.wiki is in one of the following forms:
-    #   [Foo words]
-    #   [Foo#Anchor words]
-    #   [http://code.google.com/.../wiki/Foo words]
-    #   [http://code.google.com/.../wiki/Foo#Anchor words]
-    # We want to replace 'Foo' with 'V2_6_Foo' in the above cases.
-    self.search_for_re = re.compile(
-        # This regex matches either
-        #   [Foo
-        # or
-        #   /wiki/Foo
-        # followed by a space or a #, where Foo is the name of an
-        # unversioned wiki page.
-        r'(\[|/wiki/)(%s)([ #])' % '|'.join(page_names))
-    self.replace_with = r'\1%s\2\3' % (self.version_prefix,)
-
-  def GetFilesToBranch(self):
-    """Returns a list of .wiki file names that need to be branched."""
-
-    unversioned_wikis = (GTEST_UNVERSIONED_WIKIS if self.project == 'googletest'
-                         else GMOCK_UNVERSIONED_WIKIS)
-    return [f for f in os.listdir(self.wiki_dir)
-            if (f.endswith('.wiki') and
-                not re.match(r'^V\d', f) and  # Excluded versioned .wiki files.
-                f not in unversioned_wikis)]
-
-  def BranchFiles(self):
-    """Branches the .wiki files needed to be branched."""
-
-    print 'Branching %d .wiki files:' % (len(self.files_to_branch),)
-    os.chdir(self.wiki_dir)
-    for f in self.files_to_branch:
-      command = 'svn cp %s %s%s' % (f, self.version_prefix, f)
-      print command
-      os.system(command)
-
-  def UpdateLinksInBranchedFiles(self):
-
-    for f in self.files_to_branch:
-      source_file = os.path.join(self.wiki_dir, f)
-      versioned_file = os.path.join(self.wiki_dir, self.version_prefix + f)
-      print 'Updating links in %s.' % (versioned_file,)
-      text = file(source_file, 'r').read()
-      new_text = self.search_for_re.sub(self.replace_with, text)
-      file(versioned_file, 'w').write(new_text)
-
-
-def main():
-  if len(sys.argv) != 2:
-    sys.exit(__doc__)
-
-  brancher = WikiBrancher(sys.argv[1])
-  brancher.BranchFiles()
-  brancher.UpdateLinksInBranchedFiles()
-
-
-if __name__ == '__main__':
-  main()
diff --git a/googletest/scripts/run_with_path.py b/googletest/scripts/run_with_path.py
deleted file mode 100755 (executable)
index d46ab4d..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2010 Google Inc. All Rights Reserved.
-
-"""Runs program specified in the command line with the substituted PATH.
-
-   This script is needed for to support building under Pulse which is unable
-   to override the existing PATH variable.
-"""
-
-import os
-import subprocess
-import sys
-
-SUBST_PATH_ENV_VAR_NAME = "SUBST_PATH"
-
-def main():
-  if SUBST_PATH_ENV_VAR_NAME in os.environ:
-    os.environ["PATH"] = os.environ[SUBST_PATH_ENV_VAR_NAME]
-
-  exit_code = subprocess.Popen(sys.argv[1:]).wait()
-
-  # exit_code is negative (-signal) if the process has been terminated by
-  # a signal. Returning negative exit code is not portable and so we return
-  # 100 instead.
-  if exit_code < 0:
-    exit_code = 100
-
-  sys.exit(exit_code)
-
-if __name__ == "__main__":
-  main()
diff --git a/googletest/scripts/test/Makefile b/googletest/scripts/test/Makefile
deleted file mode 100644 (file)
index cdff584..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-# A Makefile for fusing Google Test and building a sample test against it.
-#
-# SYNOPSIS:
-#
-#   make [all]  - makes everything.
-#   make TARGET - makes the given target.
-#   make check  - makes everything and runs the built sample test.
-#   make clean  - removes all files generated by make.
-
-# Points to the root of fused Google Test, relative to where this file is.
-FUSED_GTEST_DIR = output
-
-# Paths to the fused gtest files.
-FUSED_GTEST_H = $(FUSED_GTEST_DIR)/gtest/gtest.h
-FUSED_GTEST_ALL_CC = $(FUSED_GTEST_DIR)/gtest/gtest-all.cc
-
-# Where to find the sample test.
-SAMPLE_DIR = ../../samples
-
-# Where to find gtest_main.cc.
-GTEST_MAIN_CC = ../../src/gtest_main.cc
-
-# Flags passed to the preprocessor.
-# We have no idea here whether pthreads is available in the system, so
-# disable its use.
-CPPFLAGS += -I$(FUSED_GTEST_DIR) -DGTEST_HAS_PTHREAD=0
-
-# Flags passed to the C++ compiler.
-CXXFLAGS += -g
-
-all : sample1_unittest
-
-check : all
-       ./sample1_unittest
-
-clean :
-       rm -rf $(FUSED_GTEST_DIR) sample1_unittest *.o
-
-$(FUSED_GTEST_H) :
-       ../fuse_gtest_files.py $(FUSED_GTEST_DIR)
-
-$(FUSED_GTEST_ALL_CC) :
-       ../fuse_gtest_files.py $(FUSED_GTEST_DIR)
-
-gtest-all.o : $(FUSED_GTEST_H) $(FUSED_GTEST_ALL_CC)
-       $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(FUSED_GTEST_DIR)/gtest/gtest-all.cc
-
-gtest_main.o : $(FUSED_GTEST_H) $(GTEST_MAIN_CC)
-       $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(GTEST_MAIN_CC)
-
-sample1.o : $(SAMPLE_DIR)/sample1.cc $(SAMPLE_DIR)/sample1.h
-       $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(SAMPLE_DIR)/sample1.cc
-
-sample1_unittest.o : $(SAMPLE_DIR)/sample1_unittest.cc \
-                     $(SAMPLE_DIR)/sample1.h $(FUSED_GTEST_H)
-       $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(SAMPLE_DIR)/sample1_unittest.cc
-
-sample1_unittest : sample1.o sample1_unittest.o gtest-all.o gtest_main.o
-       $(CXX) $(CPPFLAGS) $(CXXFLAGS) $^ -o $@
diff --git a/googletest/scripts/upload.py b/googletest/scripts/upload.py
deleted file mode 100755 (executable)
index eba5711..0000000
+++ /dev/null
@@ -1,1402 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2007, Google Inc.
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-#     * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-#     * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-#     * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-"""Tool for uploading diffs from a version control system to the codereview app.
-
-Usage summary: upload.py [options] [-- diff_options]
-
-Diff options are passed to the diff command of the underlying system.
-
-Supported version control systems:
-  Git
-  Mercurial
-  Subversion
-
-It is important for Git/Mercurial users to specify a tree/node/branch to diff
-against by using the '--rev' option.
-"""
-# This code is derived from appcfg.py in the App Engine SDK (open source),
-# and from ASPN recipe #146306.
-
-import cookielib
-import getpass
-import logging
-import md5
-import mimetypes
-import optparse
-import os
-import re
-import socket
-import subprocess
-import sys
-import urllib
-import urllib2
-import urlparse
-
-try:
-  import readline
-except ImportError:
-  pass
-
-# The logging verbosity:
-#  0: Errors only.
-#  1: Status messages.
-#  2: Info logs.
-#  3: Debug logs.
-verbosity = 1
-
-# Max size of patch or base file.
-MAX_UPLOAD_SIZE = 900 * 1024
-
-
-def GetEmail(prompt):
-  """Prompts the user for their email address and returns it.
-
-  The last used email address is saved to a file and offered up as a suggestion
-  to the user. If the user presses enter without typing in anything the last
-  used email address is used. If the user enters a new address, it is saved
-  for next time we prompt.
-
-  """
-  last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
-  last_email = ""
-  if os.path.exists(last_email_file_name):
-    try:
-      last_email_file = open(last_email_file_name, "r")
-      last_email = last_email_file.readline().strip("\n")
-      last_email_file.close()
-      prompt += " [%s]" % last_email
-    except IOError, e:
-      pass
-  email = raw_input(prompt + ": ").strip()
-  if email:
-    try:
-      last_email_file = open(last_email_file_name, "w")
-      last_email_file.write(email)
-      last_email_file.close()
-    except IOError, e:
-      pass
-  else:
-    email = last_email
-  return email
-
-
-def StatusUpdate(msg):
-  """Print a status message to stdout.
-
-  If 'verbosity' is greater than 0, print the message.
-
-  Args:
-    msg: The string to print.
-  """
-  if verbosity > 0:
-    print msg
-
-
-def ErrorExit(msg):
-  """Print an error message to stderr and exit."""
-  print >>sys.stderr, msg
-  sys.exit(1)
-
-
-class ClientLoginError(urllib2.HTTPError):
-  """Raised to indicate there was an error authenticating with ClientLogin."""
-
-  def __init__(self, url, code, msg, headers, args):
-    urllib2.HTTPError.__init__(self, url, code, msg, headers, None)
-    self.args = args
-    self.reason = args["Error"]
-
-
-class AbstractRpcServer(object):
-  """Provides a common interface for a simple RPC server."""
-
-  def __init__(self, host, auth_function, host_override=None, extra_headers={},
-               save_cookies=False):
-    """Creates a new HttpRpcServer.
-
-    Args:
-      host: The host to send requests to.
-      auth_function: A function that takes no arguments and returns an
-        (email, password) tuple when called. Will be called if authentication
-        is required.
-      host_override: The host header to send to the server (defaults to host).
-      extra_headers: A dict of extra headers to append to every request.
-      save_cookies: If True, save the authentication cookies to local disk.
-        If False, use an in-memory cookiejar instead.  Subclasses must
-        implement this functionality.  Defaults to False.
-    """
-    self.host = host
-    self.host_override = host_override
-    self.auth_function = auth_function
-    self.authenticated = False
-    self.extra_headers = extra_headers
-    self.save_cookies = save_cookies
-    self.opener = self._GetOpener()
-    if self.host_override:
-      logging.info("Server: %s; Host: %s", self.host, self.host_override)
-    else:
-      logging.info("Server: %s", self.host)
-
-  def _GetOpener(self):
-    """Returns an OpenerDirector for making HTTP requests.
-
-    Returns:
-      A urllib2.OpenerDirector object.
-    """
-    raise NotImplementedError()
-
-  def _CreateRequest(self, url, data=None):
-    """Creates a new urllib request."""
-    logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
-    req = urllib2.Request(url, data=data)
-    if self.host_override:
-      req.add_header("Host", self.host_override)
-    for key, value in self.extra_headers.iteritems():
-      req.add_header(key, value)
-    return req
-
-  def _GetAuthToken(self, email, password):
-    """Uses ClientLogin to authenticate the user, returning an auth token.
-
-    Args:
-      email:    The user's email address
-      password: The user's password
-
-    Raises:
-      ClientLoginError: If there was an error authenticating with ClientLogin.
-      HTTPError: If there was some other form of HTTP error.
-
-    Returns:
-      The authentication token returned by ClientLogin.
-    """
-    account_type = "GOOGLE"
-    if self.host.endswith(".google.com"):
-      # Needed for use inside Google.
-      account_type = "HOSTED"
-    req = self._CreateRequest(
-        url="https://www.google.com/accounts/ClientLogin",
-        data=urllib.urlencode({
-            "Email": email,
-            "Passwd": password,
-            "service": "ah",
-            "source": "rietveld-codereview-upload",
-            "accountType": account_type,
-        }),
-    )
-    try:
-      response = self.opener.open(req)
-      response_body = response.read()
-      response_dict = dict(x.split("=")
-                           for x in response_body.split("\n") if x)
-      return response_dict["Auth"]
-    except urllib2.HTTPError, e:
-      if e.code == 403:
-        body = e.read()
-        response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
-        raise ClientLoginError(req.get_full_url(), e.code, e.msg,
-                               e.headers, response_dict)
-      else:
-        raise
-
-  def _GetAuthCookie(self, auth_token):
-    """Fetches authentication cookies for an authentication token.
-
-    Args:
-      auth_token: The authentication token returned by ClientLogin.
-
-    Raises:
-      HTTPError: If there was an error fetching the authentication cookies.
-    """
-    # This is a dummy value to allow us to identify when we're successful.
-    continue_location = "http://localhost/"
-    args = {"continue": continue_location, "auth": auth_token}
-    req = self._CreateRequest("http://%s/_ah/login?%s" %
-                              (self.host, urllib.urlencode(args)))
-    try:
-      response = self.opener.open(req)
-    except urllib2.HTTPError, e:
-      response = e
-    if (response.code != 302 or
-        response.info()["location"] != continue_location):
-      raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg,
-                              response.headers, response.fp)
-    self.authenticated = True
-
-  def _Authenticate(self):
-    """Authenticates the user.
-
-    The authentication process works as follows:
-     1) We get a username and password from the user
-     2) We use ClientLogin to obtain an AUTH token for the user
-        (see https://developers.google.com/identity/protocols/AuthForInstalledApps).
-     3) We pass the auth token to /_ah/login on the server to obtain an
-        authentication cookie. If login was successful, it tries to redirect
-        us to the URL we provided.
-
-    If we attempt to access the upload API without first obtaining an
-    authentication cookie, it returns a 401 response and directs us to
-    authenticate ourselves with ClientLogin.
-    """
-    for i in range(3):
-      credentials = self.auth_function()
-      try:
-        auth_token = self._GetAuthToken(credentials[0], credentials[1])
-      except ClientLoginError, e:
-        if e.reason == "BadAuthentication":
-          print >>sys.stderr, "Invalid username or password."
-          continue
-        if e.reason == "CaptchaRequired":
-          print >>sys.stderr, (
-              "Please go to\n"
-              "https://www.google.com/accounts/DisplayUnlockCaptcha\n"
-              "and verify you are a human.  Then try again.")
-          break
-        if e.reason == "NotVerified":
-          print >>sys.stderr, "Account not verified."
-          break
-        if e.reason == "TermsNotAgreed":
-          print >>sys.stderr, "User has not agreed to TOS."
-          break
-        if e.reason == "AccountDeleted":
-          print >>sys.stderr, "The user account has been deleted."
-          break
-        if e.reason == "AccountDisabled":
-          print >>sys.stderr, "The user account has been disabled."
-          break
-        if e.reason == "ServiceDisabled":
-          print >>sys.stderr, ("The user's access to the service has been "
-                               "disabled.")
-          break
-        if e.reason == "ServiceUnavailable":
-          print >>sys.stderr, "The service is not available; try again later."
-          break
-        raise
-      self._GetAuthCookie(auth_token)
-      return
-
-  def Send(self, request_path, payload=None,
-           content_type="application/octet-stream",
-           timeout=None,
-           **kwargs):
-    """Sends an RPC and returns the response.
-
-    Args:
-      request_path: The path to send the request to, eg /api/appversion/create.
-      payload: The body of the request, or None to send an empty request.
-      content_type: The Content-Type header to use.
-      timeout: timeout in seconds; default None i.e. no timeout.
-        (Note: for large requests on OS X, the timeout doesn't work right.)
-      kwargs: Any keyword arguments are converted into query string parameters.
-
-    Returns:
-      The response body, as a string.
-    """
-    # TODO: Don't require authentication.  Let the server say
-    # whether it is necessary.
-    if not self.authenticated:
-      self._Authenticate()
-
-    old_timeout = socket.getdefaulttimeout()
-    socket.setdefaulttimeout(timeout)
-    try:
-      tries = 0
-      while True:
-        tries += 1
-        args = dict(kwargs)
-        url = "http://%s%s" % (self.host, request_path)
-        if args:
-          url += "?" + urllib.urlencode(args)
-        req = self._CreateRequest(url=url, data=payload)
-        req.add_header("Content-Type", content_type)
-        try:
-          f = self.opener.open(req)
-          response = f.read()
-          f.close()
-          return response
-        except urllib2.HTTPError, e:
-          if tries > 3:
-            raise
-          elif e.code == 401:
-            self._Authenticate()
-##           elif e.code >= 500 and e.code < 600:
-##             # Server Error - try again.
-##             continue
-          else:
-            raise
-    finally:
-      socket.setdefaulttimeout(old_timeout)
-
-
-class HttpRpcServer(AbstractRpcServer):
-  """Provides a simplified RPC-style interface for HTTP requests."""
-
-  def _Authenticate(self):
-    """Save the cookie jar after authentication."""
-    super(HttpRpcServer, self)._Authenticate()
-    if self.save_cookies:
-      StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
-      self.cookie_jar.save()
-
-  def _GetOpener(self):
-    """Returns an OpenerDirector that supports cookies and ignores redirects.
-
-    Returns:
-      A urllib2.OpenerDirector object.
-    """
-    opener = urllib2.OpenerDirector()
-    opener.add_handler(urllib2.ProxyHandler())
-    opener.add_handler(urllib2.UnknownHandler())
-    opener.add_handler(urllib2.HTTPHandler())
-    opener.add_handler(urllib2.HTTPDefaultErrorHandler())
-    opener.add_handler(urllib2.HTTPSHandler())
-    opener.add_handler(urllib2.HTTPErrorProcessor())
-    if self.save_cookies:
-      self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies")
-      self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
-      if os.path.exists(self.cookie_file):
-        try:
-          self.cookie_jar.load()
-          self.authenticated = True
-          StatusUpdate("Loaded authentication cookies from %s" %
-                       self.cookie_file)
-        except (cookielib.LoadError, IOError):
-          # Failed to load cookies - just ignore them.
-          pass
-      else:
-        # Create an empty cookie file with mode 600
-        fd = os.open(self.cookie_file, os.O_CREAT, 0600)
-        os.close(fd)
-      # Always chmod the cookie file
-      os.chmod(self.cookie_file, 0600)
-    else:
-      # Don't save cookies across runs of update.py.
-      self.cookie_jar = cookielib.CookieJar()
-    opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar))
-    return opener
-
-
-parser = optparse.OptionParser(usage="%prog [options] [-- diff_options]")
-parser.add_option("-y", "--assume_yes", action="store_true",
-                  dest="assume_yes", default=False,
-                  help="Assume that the answer to yes/no questions is 'yes'.")
-# Logging
-group = parser.add_option_group("Logging options")
-group.add_option("-q", "--quiet", action="store_const", const=0,
-                 dest="verbose", help="Print errors only.")
-group.add_option("-v", "--verbose", action="store_const", const=2,
-                 dest="verbose", default=1,
-                 help="Print info level logs (default).")
-group.add_option("--noisy", action="store_const", const=3,
-                 dest="verbose", help="Print all logs.")
-# Review server
-group = parser.add_option_group("Review server options")
-group.add_option("-s", "--server", action="store", dest="server",
-                 default="codereview.appspot.com",
-                 metavar="SERVER",
-                 help=("The server to upload to. The format is host[:port]. "
-                       "Defaults to 'codereview.appspot.com'."))
-group.add_option("-e", "--email", action="store", dest="email",
-                 metavar="EMAIL", default=None,
-                 help="The username to use. Will prompt if omitted.")
-group.add_option("-H", "--host", action="store", dest="host",
-                 metavar="HOST", default=None,
-                 help="Overrides the Host header sent with all RPCs.")
-group.add_option("--no_cookies", action="store_false",
-                 dest="save_cookies", default=True,
-                 help="Do not save authentication cookies to local disk.")
-# Issue
-group = parser.add_option_group("Issue options")
-group.add_option("-d", "--description", action="store", dest="description",
-                 metavar="DESCRIPTION", default=None,
-                 help="Optional description when creating an issue.")
-group.add_option("-f", "--description_file", action="store",
-                 dest="description_file", metavar="DESCRIPTION_FILE",
-                 default=None,
-                 help="Optional path of a file that contains "
-                      "the description when creating an issue.")
-group.add_option("-r", "--reviewers", action="store", dest="reviewers",
-                 metavar="REVIEWERS", default=None,
-                 help="Add reviewers (comma separated email addresses).")
-group.add_option("--cc", action="store", dest="cc",
-                 metavar="CC", default=None,
-                 help="Add CC (comma separated email addresses).")
-# Upload options
-group = parser.add_option_group("Patch options")
-group.add_option("-m", "--message", action="store", dest="message",
-                 metavar="MESSAGE", default=None,
-                 help="A message to identify the patch. "
-                      "Will prompt if omitted.")
-group.add_option("-i", "--issue", type="int", action="store",
-                 metavar="ISSUE", default=None,
-                 help="Issue number to which to add. Defaults to new issue.")
-group.add_option("--download_base", action="store_true",
-                 dest="download_base", default=False,
-                 help="Base files will be downloaded by the server "
-                 "(side-by-side diffs may not work on files with CRs).")
-group.add_option("--rev", action="store", dest="revision",
-                 metavar="REV", default=None,
-                 help="Branch/tree/revision to diff against (used by DVCS).")
-group.add_option("--send_mail", action="store_true",
-                 dest="send_mail", default=False,
-                 help="Send notification email to reviewers.")
-
-
-def GetRpcServer(options):
-  """Returns an instance of an AbstractRpcServer.
-
-  Returns:
-    A new AbstractRpcServer, on which RPC calls can be made.
-  """
-
-  rpc_server_class = HttpRpcServer
-
-  def GetUserCredentials():
-    """Prompts the user for a username and password."""
-    email = options.email
-    if email is None:
-      email = GetEmail("Email (login for uploading to %s)" % options.server)
-    password = getpass.getpass("Password for %s: " % email)
-    return (email, password)
-
-  # If this is the dev_appserver, use fake authentication.
-  host = (options.host or options.server).lower()
-  if host == "localhost" or host.startswith("localhost:"):
-    email = options.email
-    if email is None:
-      email = "test@example.com"
-      logging.info("Using debug user %s.  Override with --email" % email)
-    server = rpc_server_class(
-        options.server,
-        lambda: (email, "password"),
-        host_override=options.host,
-        extra_headers={"Cookie":
-                       'dev_appserver_login="%s:False"' % email},
-        save_cookies=options.save_cookies)
-    # Don't try to talk to ClientLogin.
-    server.authenticated = True
-    return server
-
-  return rpc_server_class(options.server, GetUserCredentials,
-                          host_override=options.host,
-                          save_cookies=options.save_cookies)
-
-
-def EncodeMultipartFormData(fields, files):
-  """Encode form fields for multipart/form-data.
-
-  Args:
-    fields: A sequence of (name, value) elements for regular form fields.
-    files: A sequence of (name, filename, value) elements for data to be
-           uploaded as files.
-  Returns:
-    (content_type, body) ready for httplib.HTTP instance.
-
-  Source:
-    https://web.archive.org/web/20160116052001/code.activestate.com/recipes/146306
-  """
-  BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-'
-  CRLF = '\r\n'
-  lines = []
-  for (key, value) in fields:
-    lines.append('--' + BOUNDARY)
-    lines.append('Content-Disposition: form-data; name="%s"' % key)
-    lines.append('')
-    lines.append(value)
-  for (key, filename, value) in files:
-    lines.append('--' + BOUNDARY)
-    lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' %
-             (key, filename))
-    lines.append('Content-Type: %s' % GetContentType(filename))
-    lines.append('')
-    lines.append(value)
-  lines.append('--' + BOUNDARY + '--')
-  lines.append('')
-  body = CRLF.join(lines)
-  content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
-  return content_type, body
-
-
-def GetContentType(filename):
-  """Helper to guess the content-type from the filename."""
-  return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
-
-
-# Use a shell for subcommands on Windows to get a PATH search.
-use_shell = sys.platform.startswith("win")
-
-def RunShellWithReturnCode(command, print_output=False,
-                           universal_newlines=True):
-  """Executes a command and returns the output from stdout and the return code.
-
-  Args:
-    command: Command to execute.
-    print_output: If True, the output is printed to stdout.
-                  If False, both stdout and stderr are ignored.
-    universal_newlines: Use universal_newlines flag (default: True).
-
-  Returns:
-    Tuple (output, return code)
-  """
-  logging.info("Running %s", command)
-  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
-                       shell=use_shell, universal_newlines=universal_newlines)
-  if print_output:
-    output_array = []
-    while True:
-      line = p.stdout.readline()
-      if not line:
-        break
-      print line.strip("\n")
-      output_array.append(line)
-    output = "".join(output_array)
-  else:
-    output = p.stdout.read()
-  p.wait()
-  errout = p.stderr.read()
-  if print_output and errout:
-    print >>sys.stderr, errout
-  p.stdout.close()
-  p.stderr.close()
-  return output, p.returncode
-
-
-def RunShell(command, silent_ok=False, universal_newlines=True,
-             print_output=False):
-  data, retcode = RunShellWithReturnCode(command, print_output,
-                                         universal_newlines)
-  if retcode:
-    ErrorExit("Got error status from %s:\n%s" % (command, data))
-  if not silent_ok and not data:
-    ErrorExit("No output from %s" % command)
-  return data
-
-
-class VersionControlSystem(object):
-  """Abstract base class providing an interface to the VCS."""
-
-  def __init__(self, options):
-    """Constructor.
-
-    Args:
-      options: Command line options.
-    """
-    self.options = options
-
-  def GenerateDiff(self, args):
-    """Return the current diff as a string.
-
-    Args:
-      args: Extra arguments to pass to the diff command.
-    """
-    raise NotImplementedError(
-        "abstract method -- subclass %s must override" % self.__class__)
-
-  def GetUnknownFiles(self):
-    """Return a list of files unknown to the VCS."""
-    raise NotImplementedError(
-        "abstract method -- subclass %s must override" % self.__class__)
-
-  def CheckForUnknownFiles(self):
-    """Show an "are you sure?" prompt if there are unknown files."""
-    unknown_files = self.GetUnknownFiles()
-    if unknown_files:
-      print "The following files are not added to version control:"
-      for line in unknown_files:
-        print line
-      prompt = "Are you sure to continue?(y/N) "
-      answer = raw_input(prompt).strip()
-      if answer != "y":
-        ErrorExit("User aborted")
-
-  def GetBaseFile(self, filename):
-    """Get the content of the upstream version of a file.
-
-    Returns:
-      A tuple (base_content, new_content, is_binary, status)
-        base_content: The contents of the base file.
-        new_content: For text files, this is empty.  For binary files, this is
-          the contents of the new file, since the diff output won't contain
-          information to reconstruct the current file.
-        is_binary: True iff the file is binary.
-        status: The status of the file.
-    """
-
-    raise NotImplementedError(
-        "abstract method -- subclass %s must override" % self.__class__)
-
-
-  def GetBaseFiles(self, diff):
-    """Helper that calls GetBase file for each file in the patch.
-
-    Returns:
-      A dictionary that maps from filename to GetBaseFile's tuple.  Filenames
-      are retrieved based on lines that start with "Index:" or
-      "Property changes on:".
-    """
-    files = {}
-    for line in diff.splitlines(True):
-      if line.startswith('Index:') or line.startswith('Property changes on:'):
-        unused, filename = line.split(':', 1)
-        # On Windows if a file has property changes its filename uses '\'
-        # instead of '/'.
-        filename = filename.strip().replace('\\', '/')
-        files[filename] = self.GetBaseFile(filename)
-    return files
-
-
-  def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options,
-                      files):
-    """Uploads the base files (and if necessary, the current ones as well)."""
-
-    def UploadFile(filename, file_id, content, is_binary, status, is_base):
-      """Uploads a file to the server."""
-      file_too_large = False
-      if is_base:
-        type = "base"
-      else:
-        type = "current"
-      if len(content) > MAX_UPLOAD_SIZE:
-        print ("Not uploading the %s file for %s because it's too large." %
-               (type, filename))
-        file_too_large = True
-        content = ""
-      checksum = md5.new(content).hexdigest()
-      if options.verbose > 0 and not file_too_large:
-        print "Uploading %s file for %s" % (type, filename)
-      url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id)
-      form_fields = [("filename", filename),
-                     ("status", status),
-                     ("checksum", checksum),
-                     ("is_binary", str(is_binary)),
-                     ("is_current", str(not is_base)),
-                    ]
-      if file_too_large:
-        form_fields.append(("file_too_large", "1"))
-      if options.email:
-        form_fields.append(("user", options.email))
-      ctype, body = EncodeMultipartFormData(form_fields,
-                                            [("data", filename, content)])
-      response_body = rpc_server.Send(url, body,
-                                      content_type=ctype)
-      if not response_body.startswith("OK"):
-        StatusUpdate("  --> %s" % response_body)
-        sys.exit(1)
-
-    patches = dict()
-    [patches.setdefault(v, k) for k, v in patch_list]
-    for filename in patches.keys():
-      base_content, new_content, is_binary, status = files[filename]
-      file_id_str = patches.get(filename)
-      if file_id_str.find("nobase") != -1:
-        base_content = None
-        file_id_str = file_id_str[file_id_str.rfind("_") + 1:]
-      file_id = int(file_id_str)
-      if base_content != None:
-        UploadFile(filename, file_id, base_content, is_binary, status, True)
-      if new_content != None:
-        UploadFile(filename, file_id, new_content, is_binary, status, False)
-
-  def IsImage(self, filename):
-    """Returns true if the filename has an image extension."""
-    mimetype =  mimetypes.guess_type(filename)[0]
-    if not mimetype:
-      return False
-    return mimetype.startswith("image/")
-
-
-class SubversionVCS(VersionControlSystem):
-  """Implementation of the VersionControlSystem interface for Subversion."""
-
-  def __init__(self, options):
-    super(SubversionVCS, self).__init__(options)
-    if self.options.revision:
-      match = re.match(r"(\d+)(:(\d+))?", self.options.revision)
-      if not match:
-        ErrorExit("Invalid Subversion revision %s." % self.options.revision)
-      self.rev_start = match.group(1)
-      self.rev_end = match.group(3)
-    else:
-      self.rev_start = self.rev_end = None
-    # Cache output from "svn list -r REVNO dirname".
-    # Keys: dirname, Values: 2-tuple (output for start rev and end rev).
-    self.svnls_cache = {}
-    # SVN base URL is required to fetch files deleted in an older revision.
-    # Result is cached to not guess it over and over again in GetBaseFile().
-    required = self.options.download_base or self.options.revision is not None
-    self.svn_base = self._GuessBase(required)
-
-  def GuessBase(self, required):
-    """Wrapper for _GuessBase."""
-    return self.svn_base
-
-  def _GuessBase(self, required):
-    """Returns the SVN base URL.
-
-    Args:
-      required: If true, exits if the url can't be guessed, otherwise None is
-        returned.
-    """
-    info = RunShell(["svn", "info"])
-    for line in info.splitlines():
-      words = line.split()
-      if len(words) == 2 and words[0] == "URL:":
-        url = words[1]
-        scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
-        username, netloc = urllib.splituser(netloc)
-        if username:
-          logging.info("Removed username from base URL")
-        if netloc.endswith("svn.python.org"):
-          if netloc == "svn.python.org":
-            if path.startswith("/projects/"):
-              path = path[9:]
-          elif netloc != "pythondev@svn.python.org":
-            ErrorExit("Unrecognized Python URL: %s" % url)
-          base = "http://svn.python.org/view/*checkout*%s/" % path
-          logging.info("Guessed Python base = %s", base)
-        elif netloc.endswith("svn.collab.net"):
-          if path.startswith("/repos/"):
-            path = path[6:]
-          base = "http://svn.collab.net/viewvc/*checkout*%s/" % path
-          logging.info("Guessed CollabNet base = %s", base)
-        elif netloc.endswith(".googlecode.com"):
-          path = path + "/"
-          base = urlparse.urlunparse(("http", netloc, path, params,
-                                      query, fragment))
-          logging.info("Guessed Google Code base = %s", base)
-        else:
-          path = path + "/"
-          base = urlparse.urlunparse((scheme, netloc, path, params,
-                                      query, fragment))
-          logging.info("Guessed base = %s", base)
-        return base
-    if required:
-      ErrorExit("Can't find URL in output from svn info")
-    return None
-
-  def GenerateDiff(self, args):
-    cmd = ["svn", "diff"]
-    if self.options.revision:
-      cmd += ["-r", self.options.revision]
-    cmd.extend(args)
-    data = RunShell(cmd)
-    count = 0
-    for line in data.splitlines():
-      if line.startswith("Index:") or line.startswith("Property changes on:"):
-        count += 1
-        logging.info(line)
-    if not count:
-      ErrorExit("No valid patches found in output from svn diff")
-    return data
-
-  def _CollapseKeywords(self, content, keyword_str):
-    """Collapses SVN keywords."""
-    # svn cat translates keywords but svn diff doesn't. As a result of this
-    # behavior patching.PatchChunks() fails with a chunk mismatch error.
-    # This part was originally written by the Review Board development team
-    # who had the same problem (https://reviews.reviewboard.org/r/276/).
-    # Mapping of keywords to known aliases
-    svn_keywords = {
-      # Standard keywords
-      'Date':                ['Date', 'LastChangedDate'],
-      'Revision':            ['Revision', 'LastChangedRevision', 'Rev'],
-      'Author':              ['Author', 'LastChangedBy'],
-      'HeadURL':             ['HeadURL', 'URL'],
-      'Id':                  ['Id'],
-
-      # Aliases
-      'LastChangedDate':     ['LastChangedDate', 'Date'],
-      'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'],
-      'LastChangedBy':       ['LastChangedBy', 'Author'],
-      'URL':                 ['URL', 'HeadURL'],
-    }
-
-    def repl(m):
-       if m.group(2):
-         return "$%s::%s$" % (m.group(1), " " * len(m.group(3)))
-       return "$%s$" % m.group(1)
-    keywords = [keyword
-                for name in keyword_str.split(" ")
-                for keyword in svn_keywords.get(name, [])]
-    return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content)
-
-  def GetUnknownFiles(self):
-    status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True)
-    unknown_files = []
-    for line in status.split("\n"):
-      if line and line[0] == "?":
-        unknown_files.append(line)
-    return unknown_files
-
-  def ReadFile(self, filename):
-    """Returns the contents of a file."""
-    file = open(filename, 'rb')
-    result = ""
-    try:
-      result = file.read()
-    finally:
-      file.close()
-    return result
-
-  def GetStatus(self, filename):
-    """Returns the status of a file."""
-    if not self.options.revision:
-      status = RunShell(["svn", "status", "--ignore-externals", filename])
-      if not status:
-        ErrorExit("svn status returned no output for %s" % filename)
-      status_lines = status.splitlines()
-      # If file is in a cl, the output will begin with
-      # "\n--- Changelist 'cl_name':\n".  See
-      # https://web.archive.org/web/20090918234815/svn.collab.net/repos/svn/trunk/notes/changelist-design.txt
-      if (len(status_lines) == 3 and
-          not status_lines[0] and
-          status_lines[1].startswith("--- Changelist")):
-        status = status_lines[2]
-      else:
-        status = status_lines[0]
-    # If we have a revision to diff against we need to run "svn list"
-    # for the old and the new revision and compare the results to get
-    # the correct status for a file.
-    else:
-      dirname, relfilename = os.path.split(filename)
-      if dirname not in self.svnls_cache:
-        cmd = ["svn", "list", "-r", self.rev_start, dirname or "."]
-        out, returncode = RunShellWithReturnCode(cmd)
-        if returncode:
-          ErrorExit("Failed to get status for %s." % filename)
-        old_files = out.splitlines()
-        args = ["svn", "list"]
-        if self.rev_end:
-          args += ["-r", self.rev_end]
-        cmd = args + [dirname or "."]
-        out, returncode = RunShellWithReturnCode(cmd)
-        if returncode:
-          ErrorExit("Failed to run command %s" % cmd)
-        self.svnls_cache[dirname] = (old_files, out.splitlines())
-      old_files, new_files = self.svnls_cache[dirname]
-      if relfilename in old_files and relfilename not in new_files:
-        status = "D   "
-      elif relfilename in old_files and relfilename in new_files:
-        status = "M   "
-      else:
-        status = "A   "
-    return status
-
-  def GetBaseFile(self, filename):
-    status = self.GetStatus(filename)
-    base_content = None
-    new_content = None
-
-    # If a file is copied its status will be "A  +", which signifies
-    # "addition-with-history".  See "svn st" for more information.  We need to
-    # upload the original file or else diff parsing will fail if the file was
-    # edited.
-    if status[0] == "A" and status[3] != "+":
-      # We'll need to upload the new content if we're adding a binary file
-      # since diff's output won't contain it.
-      mimetype = RunShell(["svn", "propget", "svn:mime-type", filename],
-                          silent_ok=True)
-      base_content = ""
-      is_binary = mimetype and not mimetype.startswith("text/")
-      if is_binary and self.IsImage(filename):
-        new_content = self.ReadFile(filename)
-    elif (status[0] in ("M", "D", "R") or
-          (status[0] == "A" and status[3] == "+") or  # Copied file.
-          (status[0] == " " and status[1] == "M")):  # Property change.
-      args = []
-      if self.options.revision:
-        url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
-      else:
-        # Don't change filename, it's needed later.
-        url = filename
-        args += ["-r", "BASE"]
-      cmd = ["svn"] + args + ["propget", "svn:mime-type", url]
-      mimetype, returncode = RunShellWithReturnCode(cmd)
-      if returncode:
-        # File does not exist in the requested revision.
-        # Reset mimetype, it contains an error message.
-        mimetype = ""
-      get_base = False
-      is_binary = mimetype and not mimetype.startswith("text/")
-      if status[0] == " ":
-        # Empty base content just to force an upload.
-        base_content = ""
-      elif is_binary:
-        if self.IsImage(filename):
-          get_base = True
-          if status[0] == "M":
-            if not self.rev_end:
-              new_content = self.ReadFile(filename)
-            else:
-              url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end)
-              new_content = RunShell(["svn", "cat", url],
-                                     universal_newlines=True, silent_ok=True)
-        else:
-          base_content = ""
-      else:
-        get_base = True
-
-      if get_base:
-        if is_binary:
-          universal_newlines = False
-        else:
-          universal_newlines = True
-        if self.rev_start:
-          # "svn cat -r REV delete_file.txt" doesn't work. cat requires
-          # the full URL with "@REV" appended instead of using "-r" option.
-          url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
-          base_content = RunShell(["svn", "cat", url],
-                                  universal_newlines=universal_newlines,
-                                  silent_ok=True)
-        else:
-          base_content = RunShell(["svn", "cat", filename],
-                                  universal_newlines=universal_newlines,
-                                  silent_ok=True)
-        if not is_binary:
-          args = []
-          if self.rev_start:
-            url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
-          else:
-            url = filename
-            args += ["-r", "BASE"]
-          cmd = ["svn"] + args + ["propget", "svn:keywords", url]
-          keywords, returncode = RunShellWithReturnCode(cmd)
-          if keywords and not returncode:
-            base_content = self._CollapseKeywords(base_content, keywords)
-    else:
-      StatusUpdate("svn status returned unexpected output: %s" % status)
-      sys.exit(1)
-    return base_content, new_content, is_binary, status[0:5]
-
-
-class GitVCS(VersionControlSystem):
-  """Implementation of the VersionControlSystem interface for Git."""
-
-  def __init__(self, options):
-    super(GitVCS, self).__init__(options)
-    # Map of filename -> hash of base file.
-    self.base_hashes = {}
-
-  def GenerateDiff(self, extra_args):
-    # This is more complicated than svn's GenerateDiff because we must convert
-    # the diff output to include an svn-style "Index:" line as well as record
-    # the hashes of the base files, so we can upload them along with our diff.
-    if self.options.revision:
-      extra_args = [self.options.revision] + extra_args
-    gitdiff = RunShell(["git", "diff", "--full-index"] + extra_args)
-    svndiff = []
-    filecount = 0
-    filename = None
-    for line in gitdiff.splitlines():
-      match = re.match(r"diff --git a/(.*) b/.*$", line)
-      if match:
-        filecount += 1
-        filename = match.group(1)
-        svndiff.append("Index: %s\n" % filename)
-      else:
-        # The "index" line in a git diff looks like this (long hashes elided):
-        #   index 82c0d44..b2cee3f 100755
-        # We want to save the left hash, as that identifies the base file.
-        match = re.match(r"index (\w+)\.\.", line)
-        if match:
-          self.base_hashes[filename] = match.group(1)
-      svndiff.append(line + "\n")
-    if not filecount:
-      ErrorExit("No valid patches found in output from git diff")
-    return "".join(svndiff)
-
-  def GetUnknownFiles(self):
-    status = RunShell(["git", "ls-files", "--exclude-standard", "--others"],
-                      silent_ok=True)
-    return status.splitlines()
-
-  def GetBaseFile(self, filename):
-    hash = self.base_hashes[filename]
-    base_content = None
-    new_content = None
-    is_binary = False
-    if hash == "0" * 40:  # All-zero hash indicates no base file.
-      status = "A"
-      base_content = ""
-    else:
-      status = "M"
-      base_content, returncode = RunShellWithReturnCode(["git", "show", hash])
-      if returncode:
-        ErrorExit("Got error status from 'git show %s'" % hash)
-    return (base_content, new_content, is_binary, status)
-
-
-class MercurialVCS(VersionControlSystem):
-  """Implementation of the VersionControlSystem interface for Mercurial."""
-
-  def __init__(self, options, repo_dir):
-    super(MercurialVCS, self).__init__(options)
-    # Absolute path to repository (we can be in a subdir)
-    self.repo_dir = os.path.normpath(repo_dir)
-    # Compute the subdir
-    cwd = os.path.normpath(os.getcwd())
-    assert cwd.startswith(self.repo_dir)
-    self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/")
-    if self.options.revision:
-      self.base_rev = self.options.revision
-    else:
-      self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip()
-
-  def _GetRelPath(self, filename):
-    """Get relative path of a file according to the current directory,
-    given its logical path in the repo."""
-    assert filename.startswith(self.subdir), filename
-    return filename[len(self.subdir):].lstrip(r"\/")
-
-  def GenerateDiff(self, extra_args):
-    # If no file specified, restrict to the current subdir
-    extra_args = extra_args or ["."]
-    cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args
-    data = RunShell(cmd, silent_ok=True)
-    svndiff = []
-    filecount = 0
-    for line in data.splitlines():
-      m = re.match("diff --git a/(\S+) b/(\S+)", line)
-      if m:
-        # Modify line to make it look like as it comes from svn diff.
-        # With this modification no changes on the server side are required
-        # to make upload.py work with Mercurial repos.
-        # NOTE: for proper handling of moved/copied files, we have to use
-        # the second filename.
-        filename = m.group(2)
-        svndiff.append("Index: %s" % filename)
-        svndiff.append("=" * 67)
-        filecount += 1
-        logging.info(line)
-      else:
-        svndiff.append(line)
-    if not filecount:
-      ErrorExit("No valid patches found in output from hg diff")
-    return "\n".join(svndiff) + "\n"
-
-  def GetUnknownFiles(self):
-    """Return a list of files unknown to the VCS."""
-    args = []
-    status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."],
-        silent_ok=True)
-    unknown_files = []
-    for line in status.splitlines():
-      st, fn = line.split(" ", 1)
-      if st == "?":
-        unknown_files.append(fn)
-    return unknown_files
-
-  def GetBaseFile(self, filename):
-    # "hg status" and "hg cat" both take a path relative to the current subdir
-    # rather than to the repo root, but "hg diff" has given us the full path
-    # to the repo root.
-    base_content = ""
-    new_content = None
-    is_binary = False
-    oldrelpath = relpath = self._GetRelPath(filename)
-    # "hg status -C" returns two lines for moved/copied files, one otherwise
-    out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath])
-    out = out.splitlines()
-    # HACK: strip error message about missing file/directory if it isn't in
-    # the working copy
-    if out[0].startswith('%s: ' % relpath):
-      out = out[1:]
-    if len(out) > 1:
-      # Moved/copied => considered as modified, use old filename to
-      # retrieve base contents
-      oldrelpath = out[1].strip()
-      status = "M"
-    else:
-      status, _ = out[0].split(' ', 1)
-    if status != "A":
-      base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath],
-        silent_ok=True)
-      is_binary = "\0" in base_content  # Mercurial's heuristic
-    if status != "R":
-      new_content = open(relpath, "rb").read()
-      is_binary = is_binary or "\0" in new_content
-    if is_binary and base_content:
-      # Fetch again without converting newlines
-      base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath],
-        silent_ok=True, universal_newlines=False)
-    if not is_binary or not self.IsImage(relpath):
-      new_content = None
-    return base_content, new_content, is_binary, status
-
-
-# NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync.
-def SplitPatch(data):
-  """Splits a patch into separate pieces for each file.
-
-  Args:
-    data: A string containing the output of svn diff.
-
-  Returns:
-    A list of 2-tuple (filename, text) where text is the svn diff output
-      pertaining to filename.
-  """
-  patches = []
-  filename = None
-  diff = []
-  for line in data.splitlines(True):
-    new_filename = None
-    if line.startswith('Index:'):
-      unused, new_filename = line.split(':', 1)
-      new_filename = new_filename.strip()
-    elif line.startswith('Property changes on:'):
-      unused, temp_filename = line.split(':', 1)
-      # When a file is modified, paths use '/' between directories, however
-      # when a property is modified '\' is used on Windows.  Make them the same
-      # otherwise the file shows up twice.
-      temp_filename = temp_filename.strip().replace('\\', '/')
-      if temp_filename != filename:
-        # File has property changes but no modifications, create a new diff.
-        new_filename = temp_filename
-    if new_filename:
-      if filename and diff:
-        patches.append((filename, ''.join(diff)))
-      filename = new_filename
-      diff = [line]
-      continue
-    if diff is not None:
-      diff.append(line)
-  if filename and diff:
-    patches.append((filename, ''.join(diff)))
-  return patches
-
-
-def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
-  """Uploads a separate patch for each file in the diff output.
-
-  Returns a list of [patch_key, filename] for each file.
-  """
-  patches = SplitPatch(data)
-  rv = []
-  for patch in patches:
-    if len(patch[1]) > MAX_UPLOAD_SIZE:
-      print ("Not uploading the patch for " + patch[0] +
-             " because the file is too large.")
-      continue
-    form_fields = [("filename", patch[0])]
-    if not options.download_base:
-      form_fields.append(("content_upload", "1"))
-    files = [("data", "data.diff", patch[1])]
-    ctype, body = EncodeMultipartFormData(form_fields, files)
-    url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
-    print "Uploading patch for " + patch[0]
-    response_body = rpc_server.Send(url, body, content_type=ctype)
-    lines = response_body.splitlines()
-    if not lines or lines[0] != "OK":
-      StatusUpdate("  --> %s" % response_body)
-      sys.exit(1)
-    rv.append([lines[1], patch[0]])
-  return rv
-
-
-def GuessVCS(options):
-  """Helper to guess the version control system.
-
-  This examines the current directory, guesses which VersionControlSystem
-  we're using, and returns an instance of the appropriate class.  Exit with an
-  error if we can't figure it out.
-
-  Returns:
-    A VersionControlSystem instance. Exits if the VCS can't be guessed.
-  """
-  # Mercurial has a command to get the base directory of a repository
-  # Try running it, but don't die if we don't have hg installed.
-  # NOTE: we try Mercurial first as it can sit on top of an SVN working copy.
-  try:
-    out, returncode = RunShellWithReturnCode(["hg", "root"])
-    if returncode == 0:
-      return MercurialVCS(options, out.strip())
-  except OSError, (errno, message):
-    if errno != 2:  # ENOENT -- they don't have hg installed.
-      raise
-
-  # Subversion has a .svn in all working directories.
-  if os.path.isdir('.svn'):
-    logging.info("Guessed VCS = Subversion")
-    return SubversionVCS(options)
-
-  # Git has a command to test if you're in a git tree.
-  # Try running it, but don't die if we don't have git installed.
-  try:
-    out, returncode = RunShellWithReturnCode(["git", "rev-parse",
-                                              "--is-inside-work-tree"])
-    if returncode == 0:
-      return GitVCS(options)
-  except OSError, (errno, message):
-    if errno != 2:  # ENOENT -- they don't have git installed.
-      raise
-
-  ErrorExit(("Could not guess version control system. "
-             "Are you in a working copy directory?"))
-
-
-def RealMain(argv, data=None):
-  """The real main function.
-
-  Args:
-    argv: Command line arguments.
-    data: Diff contents. If None (default) the diff is generated by
-      the VersionControlSystem implementation returned by GuessVCS().
-
-  Returns:
-    A 2-tuple (issue id, patchset id).
-    The patchset id is None if the base files are not uploaded by this
-    script (applies only to SVN checkouts).
-  """
-  logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:"
-                              "%(lineno)s %(message)s "))
-  os.environ['LC_ALL'] = 'C'
-  options, args = parser.parse_args(argv[1:])
-  global verbosity
-  verbosity = options.verbose
-  if verbosity >= 3:
-    logging.getLogger().setLevel(logging.DEBUG)
-  elif verbosity >= 2:
-    logging.getLogger().setLevel(logging.INFO)
-  vcs = GuessVCS(options)
-  if isinstance(vcs, SubversionVCS):
-    # base field is only allowed for Subversion.
-    # Note: Fetching base files may become deprecated in future releases.
-    base = vcs.GuessBase(options.download_base)
-  else:
-    base = None
-  if not base and options.download_base:
-    options.download_base = True
-    logging.info("Enabled upload of base file")
-  if not options.assume_yes:
-    vcs.CheckForUnknownFiles()
-  if data is None:
-    data = vcs.GenerateDiff(args)
-  files = vcs.GetBaseFiles(data)
-  if verbosity >= 1:
-    print "Upload server:", options.server, "(change with -s/--server)"
-  if options.issue:
-    prompt = "Message describing this patch set: "
-  else:
-    prompt = "New issue subject: "
-  message = options.message or raw_input(prompt).strip()
-  if not message:
-    ErrorExit("A non-empty message is required")
-  rpc_server = GetRpcServer(options)
-  form_fields = [("subject", message)]
-  if base:
-    form_fields.append(("base", base))
-  if options.issue:
-    form_fields.append(("issue", str(options.issue)))
-  if options.email:
-    form_fields.append(("user", options.email))
-  if options.reviewers:
-    for reviewer in options.reviewers.split(','):
-      if "@" in reviewer and not reviewer.split("@")[1].count(".") == 1:
-        ErrorExit("Invalid email address: %s" % reviewer)
-    form_fields.append(("reviewers", options.reviewers))
-  if options.cc:
-    for cc in options.cc.split(','):
-      if "@" in cc and not cc.split("@")[1].count(".") == 1:
-        ErrorExit("Invalid email address: %s" % cc)
-    form_fields.append(("cc", options.cc))
-  description = options.description
-  if options.description_file:
-    if options.description:
-      ErrorExit("Can't specify description and description_file")
-    file = open(options.description_file, 'r')
-    description = file.read()
-    file.close()
-  if description:
-    form_fields.append(("description", description))
-  # Send a hash of all the base file so the server can determine if a copy
-  # already exists in an earlier patchset.
-  base_hashes = ""
-  for file, info in files.iteritems():
-    if not info[0] is None:
-      checksum = md5.new(info[0]).hexdigest()
-      if base_hashes:
-        base_hashes += "|"
-      base_hashes += checksum + ":" + file
-  form_fields.append(("base_hashes", base_hashes))
-  # If we're uploading base files, don't send the email before the uploads, so
-  # that it contains the file status.
-  if options.send_mail and options.download_base:
-    form_fields.append(("send_mail", "1"))
-  if not options.download_base:
-    form_fields.append(("content_upload", "1"))
-  if len(data) > MAX_UPLOAD_SIZE:
-    print "Patch is large, so uploading file patches separately."
-    uploaded_diff_file = []
-    form_fields.append(("separate_patches", "1"))
-  else:
-    uploaded_diff_file = [("data", "data.diff", data)]
-  ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file)
-  response_body = rpc_server.Send("/upload", body, content_type=ctype)
-  patchset = None
-  if not options.download_base or not uploaded_diff_file:
-    lines = response_body.splitlines()
-    if len(lines) >= 2:
-      msg = lines[0]
-      patchset = lines[1].strip()
-      patches = [x.split(" ", 1) for x in lines[2:]]
-    else:
-      msg = response_body
-  else:
-    msg = response_body
-  StatusUpdate(msg)
-  if not response_body.startswith("Issue created.") and \
-  not response_body.startswith("Issue updated."):
-    sys.exit(0)
-  issue = msg[msg.rfind("/")+1:]
-
-  if not uploaded_diff_file:
-    result = UploadSeparatePatches(issue, rpc_server, patchset, data, options)
-    if not options.download_base:
-      patches = result
-
-  if not options.download_base:
-    vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files)
-    if options.send_mail:
-      rpc_server.Send("/" + issue + "/mail", payload="")
-  return issue, patchset
-
-
-def main():
-  try:
-    RealMain(sys.argv)
-  except KeyboardInterrupt:
-    print
-    StatusUpdate("Interrupted.")
-    sys.exit(1)
-
-
-if __name__ == "__main__":
-  main()
diff --git a/googletest/scripts/upload_gtest.py b/googletest/scripts/upload_gtest.py
deleted file mode 100755 (executable)
index be19ae8..0000000
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/env python
-#
-# 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.
-
-"""upload_gtest.py v0.1.0 -- uploads a Google Test patch for review.
-
-This simple wrapper passes all command line flags and
---cc=googletestframework@googlegroups.com to upload.py.
-
-USAGE: upload_gtest.py [options for upload.py]
-"""
-
-__author__ = 'wan@google.com (Zhanyong Wan)'
-
-import os
-import sys
-
-CC_FLAG = '--cc='
-GTEST_GROUP = 'googletestframework@googlegroups.com'
-
-
-def main():
-  # Finds the path to upload.py, assuming it is in the same directory
-  # as this file.
-  my_dir = os.path.dirname(os.path.abspath(__file__))
-  upload_py_path = os.path.join(my_dir, 'upload.py')
-
-  # Adds Google Test discussion group to the cc line if it's not there
-  # already.
-  upload_py_argv = [upload_py_path]
-  found_cc_flag = False
-  for arg in sys.argv[1:]:
-    if arg.startswith(CC_FLAG):
-      found_cc_flag = True
-      cc_line = arg[len(CC_FLAG):]
-      cc_list = [addr for addr in cc_line.split(',') if addr]
-      if GTEST_GROUP not in cc_list:
-        cc_list.append(GTEST_GROUP)
-      upload_py_argv.append(CC_FLAG + ','.join(cc_list))
-    else:
-      upload_py_argv.append(arg)
-
-  if not found_cc_flag:
-    upload_py_argv.append(CC_FLAG + GTEST_GROUP)
-
-  # Invokes upload.py with the modified command line flags.
-  os.execv(upload_py_path, upload_py_argv)
-
-
-if __name__ == '__main__':
-  main()
index ad292905cf381d69eba9008f5196cf6477a56c1a..2a70ed88c7841a58f0bd54e6e8cc5c14f47dce48 100644 (file)
@@ -38,7 +38,7 @@
 #include "gtest/gtest.h"
 
 // The following lines pull in the real gtest *.cc files.
-#include "src/gtest.cc"
+#include "src/gtest-assertion-result.cc"
 #include "src/gtest-death-test.cc"
 #include "src/gtest-filepath.cc"
 #include "src/gtest-matchers.cc"
@@ -46,3 +46,4 @@
 #include "src/gtest-printers.cc"
 #include "src/gtest-test-part.cc"
 #include "src/gtest-typed-test.cc"
+#include "src/gtest.cc"
diff --git a/googletest/src/gtest-assertion-result.cc b/googletest/src/gtest-assertion-result.cc
new file mode 100644 (file)
index 0000000..f1c0b10
--- /dev/null
@@ -0,0 +1,77 @@
+// Copyright 2005, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// The Google C++ Testing and Mocking Framework (Google Test)
+//
+// This file defines the AssertionResult type.
+
+#include "gtest/gtest-assertion-result.h"
+
+#include <string>
+#include <utility>
+
+#include "gtest/gtest-message.h"
+
+namespace testing {
+
+// AssertionResult constructors.
+// Used in EXPECT_TRUE/FALSE(assertion_result).
+AssertionResult::AssertionResult(const AssertionResult& other)
+    : success_(other.success_),
+      message_(other.message_.get() != nullptr
+                   ? new ::std::string(*other.message_)
+                   : static_cast< ::std::string*>(nullptr)) {}
+
+// Swaps two AssertionResults.
+void AssertionResult::swap(AssertionResult& other) {
+  using std::swap;
+  swap(success_, other.success_);
+  swap(message_, other.message_);
+}
+
+// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
+AssertionResult AssertionResult::operator!() const {
+  AssertionResult negation(!success_);
+  if (message_.get() != nullptr) negation << *message_;
+  return negation;
+}
+
+// Makes a successful assertion result.
+AssertionResult AssertionSuccess() { return AssertionResult(true); }
+
+// Makes a failed assertion result.
+AssertionResult AssertionFailure() { return AssertionResult(false); }
+
+// Makes a failed assertion result with the given failure message.
+// Deprecated; use AssertionFailure() << message.
+AssertionResult AssertionFailure(const Message& message) {
+  return AssertionFailure() << message;
+}
+
+}  // namespace testing
index bf4f6331dac129b49d5f5ae2f23c33dd8b6adbd6..e6abc6278ae4b36a6533d307814fce786908e093 100644 (file)
 #include <functional>
 #include <utility>
 
-#include "gtest/internal/gtest-port.h"
 #include "gtest/internal/custom/gtest.h"
+#include "gtest/internal/gtest-port.h"
 
 #if GTEST_HAS_DEATH_TEST
 
-# if GTEST_OS_MAC
-#  include <crt_externs.h>
-# endif  // GTEST_OS_MAC
-
-# include <errno.h>
-# include <fcntl.h>
-# include <limits.h>
-
-# if GTEST_OS_LINUX
-#  include <signal.h>
-# endif  // GTEST_OS_LINUX
-
-# include <stdarg.h>
-
-# if GTEST_OS_WINDOWS
-#  include <windows.h>
-# else
-#  include <sys/mman.h>
-#  include <sys/wait.h>
-# endif  // GTEST_OS_WINDOWS
-
-# if GTEST_OS_QNX
-#  include <spawn.h>
-# endif  // GTEST_OS_QNX
-
-# if GTEST_OS_FUCHSIA
-#  include <lib/fdio/fd.h>
-#  include <lib/fdio/io.h>
-#  include <lib/fdio/spawn.h>
-#  include <lib/zx/channel.h>
-#  include <lib/zx/port.h>
-#  include <lib/zx/process.h>
-#  include <lib/zx/socket.h>
-#  include <zircon/processargs.h>
-#  include <zircon/syscalls.h>
-#  include <zircon/syscalls/policy.h>
-#  include <zircon/syscalls/port.h>
-# endif  // GTEST_OS_FUCHSIA
+#if GTEST_OS_MAC
+#include <crt_externs.h>
+#endif  // GTEST_OS_MAC
+
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+
+#if GTEST_OS_LINUX
+#include <signal.h>
+#endif  // GTEST_OS_LINUX
+
+#include <stdarg.h>
+
+#if GTEST_OS_WINDOWS
+#include <windows.h>
+#else
+#include <sys/mman.h>
+#include <sys/wait.h>
+#endif  // GTEST_OS_WINDOWS
+
+#if GTEST_OS_QNX
+#include <spawn.h>
+#endif  // GTEST_OS_QNX
+
+#if GTEST_OS_FUCHSIA
+#include <lib/fdio/fd.h>
+#include <lib/fdio/io.h>
+#include <lib/fdio/spawn.h>
+#include <lib/zx/channel.h>
+#include <lib/zx/port.h>
+#include <lib/zx/process.h>
+#include <lib/zx/socket.h>
+#include <zircon/processargs.h>
+#include <zircon/syscalls.h>
+#include <zircon/syscalls/policy.h>
+#include <zircon/syscalls/port.h>
+#endif  // GTEST_OS_FUCHSIA
 
 #endif  // GTEST_HAS_DEATH_TEST
 
@@ -96,9 +96,12 @@ namespace testing {
 // used internally at Google, is "threadsafe".
 static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;
 
+}  // namespace testing
+
 GTEST_DEFINE_string_(
     death_test_style,
-    internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
+    testing::internal::StringFromGTestEnv("death_test_style",
+                                          testing::kDefaultDeathTestStyle),
     "Indicates how to run a death test in a forked child process: "
     "\"threadsafe\" (child process re-executes the test binary "
     "from the beginning, running only the specific death test) or "
@@ -107,7 +110,7 @@ GTEST_DEFINE_string_(
 
 GTEST_DEFINE_bool_(
     death_test_use_fork,
-    internal::BoolFromGTestEnv("death_test_use_fork", false),
+    testing::internal::BoolFromGTestEnv("death_test_use_fork", false),
     "Instructs to use fork()/_exit() instead of clone() in death tests. "
     "Ignored and always uses fork() on POSIX systems where clone() is not "
     "implemented. Useful when running under valgrind or similar tools if "
@@ -117,7 +120,6 @@ GTEST_DEFINE_bool_(
     "work in 99% of the cases. Once valgrind is fixed, this flag will "
     "most likely be removed.");
 
-namespace internal {
 GTEST_DEFINE_string_(
     internal_run_death_test, "",
     "Indicates the file, line number, temporal index of "
@@ -126,7 +128,8 @@ GTEST_DEFINE_string_(
     "the '|' characters.  This flag is specified if and only if the "
     "current process is a sub-process launched for running a thread-safe "
     "death test.  FOR INTERNAL USE ONLY.");
-}  // namespace internal
+
+namespace testing {
 
 #if GTEST_HAS_DEATH_TEST
 
@@ -134,9 +137,9 @@ namespace internal {
 
 // Valid only for fast death tests. Indicates the code is running in the
 // child process of a fast style death test.
-# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
+#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
 static bool g_in_fast_death_test_child = false;
-# endif
+#endif
 
 // Returns a Boolean value indicating whether the caller is currently
 // executing in the context of the death test child process.  Tools such as
@@ -144,16 +147,16 @@ static bool g_in_fast_death_test_child = false;
 // tests.  IMPORTANT: This is an internal utility.  Using it may break the
 // implementation of death tests.  User code MUST NOT use it.
 bool InDeathTestChild() {
-# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
+#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
 
   // On Windows and Fuchsia, death tests are thread-safe regardless of the value
   // of the death_test_style flag.
-  return !GTEST_FLAG(internal_run_death_test).empty();
+  return !GTEST_FLAG_GET(internal_run_death_test).empty();
 
-# else
+#else
 
-  if (GTEST_FLAG(death_test_style) == "threadsafe")
-    return !GTEST_FLAG(internal_run_death_test).empty();
+  if (GTEST_FLAG_GET(death_test_style) == "threadsafe")
+    return !GTEST_FLAG_GET(internal_run_death_test).empty();
   else
     return g_in_fast_death_test_child;
 #endif
@@ -162,40 +165,38 @@ bool InDeathTestChild() {
 }  // namespace internal
 
 // ExitedWithCode constructor.
-ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
-}
+ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {}
 
 // ExitedWithCode function-call operator.
 bool ExitedWithCode::operator()(int exit_status) const {
-# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
+#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
 
   return exit_status == exit_code_;
 
-# else
+#else
 
   return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
 
-# endif  // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
+#endif  // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
 }
 
-# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
+#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
 // KilledBySignal constructor.
-KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
-}
+KilledBySignal::KilledBySignal(int signum) : signum_(signum) {}
 
 // KilledBySignal function-call operator.
 bool KilledBySignal::operator()(int exit_status) const {
-#  if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
+#if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
   {
     bool result;
     if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
       return result;
     }
   }
-#  endif  // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
+#endif  // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
   return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
 }
-# endif  // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
+#endif  // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
 
 namespace internal {
 
@@ -206,23 +207,23 @@ namespace internal {
 static std::string ExitSummary(int exit_code) {
   Message m;
 
-# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
+#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
 
   m << "Exited with exit status " << exit_code;
 
-# else
+#else
 
   if (WIFEXITED(exit_code)) {
     m << "Exited with exit status " << WEXITSTATUS(exit_code);
   } else if (WIFSIGNALED(exit_code)) {
     m << "Terminated by signal " << WTERMSIG(exit_code);
   }
-#  ifdef WCOREDUMP
+#ifdef WCOREDUMP
   if (WCOREDUMP(exit_code)) {
     m << " (core dumped)";
   }
-#  endif
-# endif  // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
+#endif
+#endif  // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
 
   return m.GetString();
 }
@@ -233,7 +234,7 @@ bool ExitedUnsuccessfully(int exit_status) {
   return !ExitedWithCode(0)(exit_status);
 }
 
-# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
+#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
 // Generates a textual failure message when a death test finds more than
 // one thread running, or cannot determine the number of threads, prior
 // to executing the given statement.  It is the responsibility of the
@@ -254,7 +255,7 @@ static std::string DeathTestThreadWarning(size_t thread_count) {
       << " this is the last message you see before your test times out.";
   return msg.GetString();
 }
-# endif  // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
+#endif  // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
 
 // Flag characters for reporting a death test that did not die.
 static const char kDeathTestLived = 'L';
@@ -304,14 +305,14 @@ static void DeathTestAbort(const std::string& message) {
 
 // A replacement for CHECK that calls DeathTestAbort if the assertion
 // fails.
-# define GTEST_DEATH_TEST_CHECK_(expression) \
-  do { \
-    if (!::testing::internal::IsTrue(expression)) { \
-      DeathTestAbort( \
-          ::std::string("CHECK failed: File ") + __FILE__ +  ", line " \
-          + ::testing::internal::StreamableToString(__LINE__) + ": " \
-          + #expression); \
-    } \
+#define GTEST_DEATH_TEST_CHECK_(expression)                              \
+  do {                                                                   \
+    if (!::testing::internal::IsTrue(expression)) {                      \
+      DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ +   \
+                     ", line " +                                         \
+                     ::testing::internal::StreamableToString(__LINE__) + \
+                     ": " + #expression);                                \
+    }                                                                    \
   } while (::testing::internal::AlwaysFalse())
 
 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
@@ -321,23 +322,23 @@ static void DeathTestAbort(const std::string& message) {
 // evaluates the expression as long as it evaluates to -1 and sets
 // errno to EINTR.  If the expression evaluates to -1 but errno is
 // something other than EINTR, DeathTestAbort is called.
-# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
-  do { \
-    int gtest_retval; \
-    do { \
-      gtest_retval = (expression); \
-    } while (gtest_retval == -1 && errno == EINTR); \
-    if (gtest_retval == -1) { \
-      DeathTestAbort( \
-          ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
-          + ::testing::internal::StreamableToString(__LINE__) + ": " \
-          + #expression + " != -1"); \
-    } \
+#define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression)                      \
+  do {                                                                   \
+    int gtest_retval;                                                    \
+    do {                                                                 \
+      gtest_retval = (expression);                                       \
+    } while (gtest_retval == -1 && errno == EINTR);                      \
+    if (gtest_retval == -1) {                                            \
+      DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ +   \
+                     ", line " +                                         \
+                     ::testing::internal::StreamableToString(__LINE__) + \
+                     ": " + #expression + " != -1");                     \
+    }                                                                    \
   } while (::testing::internal::AlwaysFalse())
 
 // Returns the message describing the last system error in errno.
 std::string GetLastErrnoDescription() {
-    return errno == 0 ? "" : posix::StrError(errno);
+  return errno == 0 ? "" : posix::StrError(errno);
 }
 
 // This is called from a death test parent process to read a failure
@@ -370,8 +371,9 @@ static void FailFromInternalError(int fd) {
 DeathTest::DeathTest() {
   TestInfo* const info = GetUnitTestImpl()->current_test_info();
   if (info == nullptr) {
-    DeathTestAbort("Cannot run a death test outside of a TEST or "
-                   "TEST_F construct");
+    DeathTestAbort(
+        "Cannot run a death test outside of a TEST or "
+        "TEST_F construct");
   }
 }
 
@@ -500,9 +502,7 @@ void DeathTestImpl::ReadAndInterpretStatusByte() {
   set_read_fd(-1);
 }
 
-std::string DeathTestImpl::GetErrorLogs() {
-  return GetCapturedStderr();
-}
+std::string DeathTestImpl::GetErrorLogs() { return GetCapturedStderr(); }
 
 // Signals that the death test code which should have exited, didn't.
 // Should be called only in a death test child process.
@@ -512,9 +512,9 @@ void DeathTestImpl::Abort(AbortReason reason) {
   // The parent process considers the death test to be a failure if
   // it finds any data in our pipe.  So, here we write a single flag byte
   // to the pipe, then exit.
-  const char status_ch =
-      reason == TEST_DID_NOT_DIE ? kDeathTestLived :
-      reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
+  const char status_ch = reason == TEST_DID_NOT_DIE       ? kDeathTestLived
+                         : reason == TEST_THREW_EXCEPTION ? kDeathTestThrew
+                                                          : kDeathTestReturned;
 
   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
   // We are leaking the descriptor here because on some platforms (i.e.,
@@ -533,7 +533,7 @@ void DeathTestImpl::Abort(AbortReason reason) {
 // much easier.
 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
   ::std::string ret;
-  for (size_t at = 0; ; ) {
+  for (size_t at = 0;;) {
     const size_t line_end = output.find('\n', at);
     ret += "[  DEATH   ] ";
     if (line_end == ::std::string::npos) {
@@ -568,8 +568,7 @@ static ::std::string FormatDeathTestOutput(const ::std::string& output) {
 // the first failing condition, in the order given above, is the one that is
 // reported. Also sets the last death test message string.
 bool DeathTestImpl::Passed(bool status_ok) {
-  if (!spawned())
-    return false;
+  if (!spawned()) return false;
 
   const std::string error_message = GetErrorLogs();
 
@@ -580,15 +579,18 @@ bool DeathTestImpl::Passed(bool status_ok) {
   switch (outcome()) {
     case LIVED:
       buffer << "    Result: failed to die.\n"
-             << " Error msg:\n" << FormatDeathTestOutput(error_message);
+             << " Error msg:\n"
+             << FormatDeathTestOutput(error_message);
       break;
     case THREW:
       buffer << "    Result: threw an exception.\n"
-             << " Error msg:\n" << FormatDeathTestOutput(error_message);
+             << " Error msg:\n"
+             << FormatDeathTestOutput(error_message);
       break;
     case RETURNED:
       buffer << "    Result: illegal return in test statement.\n"
-             << " Error msg:\n" << FormatDeathTestOutput(error_message);
+             << " Error msg:\n"
+             << FormatDeathTestOutput(error_message);
       break;
     case DIED:
       if (status_ok) {
@@ -605,7 +607,8 @@ bool DeathTestImpl::Passed(bool status_ok) {
       } else {
         buffer << "    Result: died but not with expected exit code:\n"
                << "            " << ExitSummary(status()) << "\n"
-               << "Actual msg:\n" << FormatDeathTestOutput(error_message);
+               << "Actual msg:\n"
+               << FormatDeathTestOutput(error_message);
       }
       break;
     case IN_PROGRESS:
@@ -618,7 +621,7 @@ bool DeathTestImpl::Passed(bool status_ok) {
   return success;
 }
 
-# if GTEST_OS_WINDOWS
+#if GTEST_OS_WINDOWS
 // WindowsDeathTest implements death tests on Windows. Due to the
 // specifics of starting new processes on Windows, death tests there are
 // always threadsafe, and Google Test considers the
@@ -679,14 +682,12 @@ class WindowsDeathTest : public DeathTestImpl {
 // status, or 0 if no child process exists.  As a side effect, sets the
 // outcome data member.
 int WindowsDeathTest::Wait() {
-  if (!spawned())
-    return 0;
+  if (!spawned()) return 0;
 
   // Wait until the child either signals that it has acquired the write end
   // of the pipe or it dies.
-  const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
-  switch (::WaitForMultipleObjects(2,
-                                   wait_handles,
+  const HANDLE wait_handles[2] = {child_handle_.Get(), event_handle_.Get()};
+  switch (::WaitForMultipleObjects(2, wait_handles,
                                    FALSE,  // Waits for any of the handles.
                                    INFINITE)) {
     case WAIT_OBJECT_0:
@@ -707,9 +708,8 @@ int WindowsDeathTest::Wait() {
   // returns immediately if the child has already exited, regardless of
   // whether previous calls to WaitForMultipleObjects synchronized on this
   // handle or not.
-  GTEST_DEATH_TEST_CHECK_(
-      WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
-                                             INFINITE));
+  GTEST_DEATH_TEST_CHECK_(WAIT_OBJECT_0 ==
+                          ::WaitForSingleObject(child_handle_.Get(), INFINITE));
   DWORD status_code;
   GTEST_DEATH_TEST_CHECK_(
       ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
@@ -742,12 +742,12 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
   SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),
                                                  nullptr, TRUE};
   HANDLE read_handle, write_handle;
-  GTEST_DEATH_TEST_CHECK_(
-      ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
-                   0)  // Default buffer size.
-      != FALSE);
-  set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
-                                O_RDONLY));
+  GTEST_DEATH_TEST_CHECK_(::CreatePipe(&read_handle, &write_handle,
+                                       &handles_are_inheritable,
+                                       0)  // Default buffer size.
+                          != FALSE);
+  set_read_fd(
+      ::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), O_RDONLY));
   write_handle_.Reset(write_handle);
   event_handle_.Reset(::CreateEvent(
       &handles_are_inheritable,
@@ -756,27 +756,26 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
       nullptr));  // The even is unnamed.
   GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr);
   const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
-                                  kFilterFlag + "=" + info->test_suite_name() +
-                                  "." + info->name();
+                                  "filter=" + info->test_suite_name() + "." +
+                                  info->name();
   const std::string internal_flag =
-      std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
-      "=" + file_ + "|" + StreamableToString(line_) + "|" +
-      StreamableToString(death_test_index) + "|" +
+      std::string("--") + GTEST_FLAG_PREFIX_ +
+      "internal_run_death_test=" + file_ + "|" + StreamableToString(line_) +
+      "|" + StreamableToString(death_test_index) + "|" +
       StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
       // size_t has the same width as pointers on both 32-bit and 64-bit
       // Windows platforms.
       // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
-      "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
-      "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
+      "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) + "|" +
+      StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
 
   char executable_path[_MAX_PATH + 1];  // NOLINT
   GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr,
                                                                 executable_path,
                                                                 _MAX_PATH));
 
-  std::string command_line =
-      std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
-      internal_flag + "\"";
+  std::string command_line = std::string(::GetCommandLineA()) + " " +
+                             filter_flag + " \"" + internal_flag + "\"";
 
   DeathTest::set_last_death_test_message("");
 
@@ -796,8 +795,8 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
   GTEST_DEATH_TEST_CHECK_(
       ::CreateProcessA(
           executable_path, const_cast<char*>(command_line.c_str()),
-          nullptr,  // Retuned process handle is not inheritable.
-          nullptr,  // Retuned thread handle is not inheritable.
+          nullptr,  // Returned process handle is not inheritable.
+          nullptr,  // Returned thread handle is not inheritable.
           TRUE,  // Child inherits all inheritable handles (for write_handle_).
           0x0,   // Default creation flags.
           nullptr,  // Inherit the parent's environment.
@@ -809,7 +808,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
   return OVERSEE_TEST;
 }
 
-# elif GTEST_OS_FUCHSIA
+#elif GTEST_OS_FUCHSIA
 
 class FuchsiaDeathTest : public DeathTestImpl {
  public:
@@ -855,18 +854,13 @@ class Arguments {
   template <typename Str>
   void AddArguments(const ::std::vector<Str>& arguments) {
     for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
-         i != arguments.end();
-         ++i) {
+         i != arguments.end(); ++i) {
       args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
     }
   }
-  char* const* Argv() {
-    return &args_[0];
-  }
+  char* const* Argv() { return &args_[0]; }
 
-  int size() {
-    return static_cast<int>(args_.size()) - 1;
-  }
+  int size() { return static_cast<int>(args_.size()) - 1; }
 
  private:
   std::vector<char*> args_;
@@ -880,8 +874,7 @@ int FuchsiaDeathTest::Wait() {
   const int kSocketKey = 1;
   const int kExceptionKey = 2;
 
-  if (!spawned())
-    return 0;
+  if (!spawned()) return 0;
 
   // Create a port to wait for socket/task/exception events.
   zx_status_t status_zx;
@@ -890,8 +883,8 @@ int FuchsiaDeathTest::Wait() {
   GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
 
   // Register to wait for the child process to terminate.
-  status_zx = child_process_.wait_async(
-      port, kProcessKey, ZX_PROCESS_TERMINATED, 0);
+  status_zx =
+      child_process_.wait_async(port, kProcessKey, ZX_PROCESS_TERMINATED, 0);
   GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
 
   // Register to wait for the socket to be readable or closed.
@@ -900,8 +893,8 @@ int FuchsiaDeathTest::Wait() {
   GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
 
   // Register to wait for an exception.
-  status_zx = exception_channel_.wait_async(
-      port, kExceptionKey, ZX_CHANNEL_READABLE, 0);
+  status_zx = exception_channel_.wait_async(port, kExceptionKey,
+                                            ZX_CHANNEL_READABLE, 0);
   GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
 
   bool process_terminated = false;
@@ -931,9 +924,9 @@ int FuchsiaDeathTest::Wait() {
           size_t old_length = captured_stderr_.length();
           size_t bytes_read = 0;
           captured_stderr_.resize(old_length + kBufferSize);
-          status_zx = stderr_socket_.read(
-              0, &captured_stderr_.front() + old_length, kBufferSize,
-              &bytes_read);
+          status_zx =
+              stderr_socket_.read(0, &captured_stderr_.front() + old_length,
+                                  kBufferSize, &bytes_read);
           captured_stderr_.resize(old_length + bytes_read);
         } while (status_zx == ZX_OK);
         if (status_zx == ZX_ERR_PEER_CLOSED) {
@@ -987,13 +980,12 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
 
   // Build the child process command line.
   const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
-                                  kFilterFlag + "=" + info->test_suite_name() +
-                                  "." + info->name();
-  const std::string internal_flag =
-      std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
-      + file_ + "|"
-      + StreamableToString(line_) + "|"
-      + StreamableToString(death_test_index);
+                                  "filter=" + info->test_suite_name() + "." +
+                                  info->name();
+  const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
+                                    kInternalRunDeathTestFlag + "=" + file_ +
+                                    "|" + StreamableToString(line_) + "|" +
+                                    StreamableToString(death_test_index);
   Arguments args;
   args.AddArguments(GetInjectableArgvs());
   args.AddArgument(filter_flag.c_str());
@@ -1016,8 +1008,7 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
 
   // Create a socket pair will be used to receive the child process' stderr.
   zx::socket stderr_producer_socket;
-  status =
-      zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
+  status = zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);
   GTEST_DEATH_TEST_CHECK_(status >= 0);
   int stderr_producer_fd = -1;
   status =
@@ -1034,35 +1025,32 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
 
   // Create a child job.
   zx_handle_t child_job = ZX_HANDLE_INVALID;
-  status = zx_job_create(zx_job_default(), 0, & child_job);
+  status = zx_job_create(zx_job_default(), 0, &child_job);
   GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
   zx_policy_basic_t policy;
   policy.condition = ZX_POL_NEW_ANY;
   policy.policy = ZX_POL_ACTION_ALLOW;
-  status = zx_job_set_policy(
-      child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1);
+  status = zx_job_set_policy(child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC,
+                             &policy, 1);
   GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
 
   // Create an exception channel attached to the |child_job|, to allow
   // us to suppress the system default exception handler from firing.
-  status =
-      zx_task_create_exception_channel(
-          child_job, 0, exception_channel_.reset_and_get_address());
+  status = zx_task_create_exception_channel(
+      child_job, 0, exception_channel_.reset_and_get_address());
   GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
 
   // Spawn the child process.
-  status = fdio_spawn_etc(
-      child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr,
-      2, spawn_actions, child_process_.reset_and_get_address(), nullptr);
+  status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0],
+                          args.Argv(), nullptr, 2, spawn_actions,
+                          child_process_.reset_and_get_address(), nullptr);
   GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
 
   set_spawned(true);
   return OVERSEE_TEST;
 }
 
-std::string FuchsiaDeathTest::GetErrorLogs() {
-  return captured_stderr_;
-}
+std::string FuchsiaDeathTest::GetErrorLogs() { return captured_stderr_; }
 
 #else  // We are neither on Windows, nor on Fuchsia.
 
@@ -1093,8 +1081,7 @@ ForkingDeathTest::ForkingDeathTest(const char* a_statement,
 // status, or 0 if no child process exists.  As a side effect, sets the
 // outcome data member.
 int ForkingDeathTest::Wait() {
-  if (!spawned())
-    return 0;
+  if (!spawned()) return 0;
 
   ReadAndInterpretStatusByte();
 
@@ -1173,11 +1160,11 @@ class ExecDeathTest : public ForkingDeathTest {
  private:
   static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {
     ::std::vector<std::string> args = GetInjectableArgvs();
-#  if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
+#if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
     ::std::vector<std::string> extra_args =
         GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
     args.insert(args.end(), extra_args.begin(), extra_args.end());
-#  endif  // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
+#endif  // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
     return args;
   }
   // The name of the file in which the death test is located.
@@ -1204,14 +1191,11 @@ class Arguments {
   template <typename Str>
   void AddArguments(const ::std::vector<Str>& arguments) {
     for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
-         i != arguments.end();
-         ++i) {
+         i != arguments.end(); ++i) {
       args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
     }
   }
-  char* const* Argv() {
-    return &args_[0];
-  }
+  char* const* Argv() { return &args_[0]; }
 
  private:
   std::vector<char*> args_;
@@ -1224,9 +1208,9 @@ struct ExecDeathTestArgs {
   int close_fd;       // File descriptor to close; the read end of a pipe
 };
 
-#  if GTEST_OS_QNX
+#if GTEST_OS_QNX
 extern "C" char** environ;
-#  else  // GTEST_OS_QNX
+#else   // GTEST_OS_QNX
 // The main function for a threadsafe-style death test child process.
 // This function is called in a clone()-ed process and thus must avoid
 // any potentially unsafe operations like malloc or libc functions.
@@ -1241,8 +1225,8 @@ static int ExecDeathTestChildMain(void* child_arg) {
       UnitTest::GetInstance()->original_working_dir();
   // We can safely call chdir() as it's a direct system call.
   if (chdir(original_dir) != 0) {
-    DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
-                   GetLastErrnoDescription());
+    DeathTestAbort(std::string("chdir(\"") + original_dir +
+                   "\") failed: " + GetLastErrnoDescription());
     return EXIT_FAILURE;
   }
 
@@ -1253,13 +1237,12 @@ static int ExecDeathTestChildMain(void* child_arg) {
   // one path separator.
   execv(args->argv[0], args->argv);
   DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " +
-                 original_dir + " failed: " +
-                 GetLastErrnoDescription());
+                 original_dir + " failed: " + GetLastErrnoDescription());
   return EXIT_FAILURE;
 }
-#  endif  // GTEST_OS_QNX
+#endif  // GTEST_OS_QNX
 
-#  if GTEST_HAS_CLONE
+#if GTEST_HAS_CLONE
 // Two utility routines that together determine the direction the stack
 // grows.
 // This could be accomplished more elegantly by a single recursive
@@ -1293,7 +1276,7 @@ static bool StackGrowsDown() {
   StackLowerThanAddress(&dummy, &result);
   return result;
 }
-#  endif  // GTEST_HAS_CLONE
+#endif  // GTEST_HAS_CLONE
 
 // Spawns a child process with the same executable as the current process in
 // a thread-safe manner and instructs it to run the death test.  The
@@ -1303,10 +1286,10 @@ static bool StackGrowsDown() {
 // spawn(2) there instead.  The function dies with an error message if
 // anything goes wrong.
 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
-  ExecDeathTestArgs args = { argv, close_fd };
+  ExecDeathTestArgs args = {argv, close_fd};
   pid_t child_pid = -1;
 
-#  if GTEST_OS_QNX
+#if GTEST_OS_QNX
   // Obtains the current directory and sets it to be closed in the child
   // process.
   const int cwd_fd = open(".", O_RDONLY);
@@ -1319,16 +1302,16 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
       UnitTest::GetInstance()->original_working_dir();
   // We can safely call chdir() as it's a direct system call.
   if (chdir(original_dir) != 0) {
-    DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
-                   GetLastErrnoDescription());
+    DeathTestAbort(std::string("chdir(\"") + original_dir +
+                   "\") failed: " + GetLastErrnoDescription());
     return EXIT_FAILURE;
   }
 
   int fd_flags;
   // Set close_fd to be closed after spawn.
   GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
-  GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
-                                        fd_flags | FD_CLOEXEC));
+  GTEST_DEATH_TEST_CHECK_SYSCALL_(
+      fcntl(close_fd, F_SETFD, fd_flags | FD_CLOEXEC));
   struct inheritance inherit = {0};
   // spawn is a system call.
   child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ);
@@ -1336,8 +1319,8 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
   GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
 
-#  else   // GTEST_OS_QNX
-#   if GTEST_OS_LINUX
+#else  // GTEST_OS_QNX
+#if GTEST_OS_LINUX
   // When a SIGPROF signal is received while fork() or clone() are executing,
   // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
   // it after the call to fork()/clone() is complete.
@@ -1346,12 +1329,12 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
   memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
   sigemptyset(&ignore_sigprof_action.sa_mask);
   ignore_sigprof_action.sa_handler = SIG_IGN;
-  GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
-      SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
-#   endif  // GTEST_OS_LINUX
+  GTEST_DEATH_TEST_CHECK_SYSCALL_(
+      sigaction(SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
+#endif  // GTEST_OS_LINUX
 
-#   if GTEST_HAS_CLONE
-  const bool use_fork = GTEST_FLAG(death_test_use_fork);
+#if GTEST_HAS_CLONE
+  const bool use_fork = GTEST_FLAG_GET(death_test_use_fork);
 
   if (!use_fork) {
     static const bool stack_grows_down = StackGrowsDown();
@@ -1370,7 +1353,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
     const size_t kMaxStackAlignment = 64;
     void* const stack_top =
         static_cast<char*>(stack) +
-            (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
+        (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
     GTEST_DEATH_TEST_CHECK_(
         static_cast<size_t>(stack_size) > kMaxStackAlignment &&
         reinterpret_cast<uintptr_t>(stack_top) % kMaxStackAlignment == 0);
@@ -1379,19 +1362,19 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
 
     GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
   }
-#   else
+#else
   const bool use_fork = true;
-#   endif  // GTEST_HAS_CLONE
+#endif  // GTEST_HAS_CLONE
 
   if (use_fork && (child_pid = fork()) == 0) {
-      ExecDeathTestChildMain(&args);
-      _exit(0);
+    ExecDeathTestChildMain(&args);
+    _exit(0);
   }
-#  endif  // GTEST_OS_QNX
-#  if GTEST_OS_LINUX
+#endif  // GTEST_OS_QNX
+#if GTEST_OS_LINUX
   GTEST_DEATH_TEST_CHECK_SYSCALL_(
       sigaction(SIGPROF, &saved_sigprof_action, nullptr));
-#  endif  // GTEST_OS_LINUX
+#endif  // GTEST_OS_LINUX
 
   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
   return child_pid;
@@ -1420,13 +1403,13 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() {
   GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
 
   const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
-                                  kFilterFlag + "=" + info->test_suite_name() +
-                                  "." + info->name();
-  const std::string internal_flag =
-      std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
-      + file_ + "|" + StreamableToString(line_) + "|"
-      + StreamableToString(death_test_index) + "|"
-      + StreamableToString(pipe_fd[1]);
+                                  "filter=" + info->test_suite_name() + "." +
+                                  info->name();
+  const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
+                                    "internal_run_death_test=" + file_ + "|" +
+                                    StreamableToString(line_) + "|" +
+                                    StreamableToString(death_test_index) + "|" +
+                                    StreamableToString(pipe_fd[1]);
   Arguments args;
   args.AddArguments(GetArgvsForDeathTestChildProcess());
   args.AddArgument(filter_flag.c_str());
@@ -1447,7 +1430,7 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() {
   return OVERSEE_TEST;
 }
 
-# endif  // !GTEST_OS_WINDOWS
+#endif  // !GTEST_OS_WINDOWS
 
 // Creates a concrete DeathTest-derived class that depends on the
 // --gtest_death_test_style flag, and sets the pointer pointed to
@@ -1461,15 +1444,15 @@ bool DefaultDeathTestFactory::Create(const char* statement,
   UnitTestImpl* const impl = GetUnitTestImpl();
   const InternalRunDeathTestFlag* const flag =
       impl->internal_run_death_test_flag();
-  const int death_test_index = impl->current_test_info()
-      ->increment_death_test_count();
+  const int death_test_index =
+      impl->current_test_info()->increment_death_test_count();
 
   if (flag != nullptr) {
     if (death_test_index > flag->index()) {
       DeathTest::set_last_death_test_message(
-          "Death test count (" + StreamableToString(death_test_index)
-          + ") somehow exceeded expected maximum ("
-          StreamableToString(flag->index()) + ")");
+          "Death test count (" + StreamableToString(death_test_index) +
+          ") somehow exceeded expected maximum (" +
+          StreamableToString(flag->index()) + ")");
       return false;
     }
 
@@ -1480,50 +1463,50 @@ bool DefaultDeathTestFactory::Create(const char* statement,
     }
   }
 
-# if GTEST_OS_WINDOWS
+#if GTEST_OS_WINDOWS
 
-  if (GTEST_FLAG(death_test_style) == "threadsafe" ||
-      GTEST_FLAG(death_test_style) == "fast") {
+  if (GTEST_FLAG_GET(death_test_style) == "threadsafe" ||
+      GTEST_FLAG_GET(death_test_style) == "fast") {
     *test = new WindowsDeathTest(statement, std::move(matcher), file, line);
   }
 
-# elif GTEST_OS_FUCHSIA
+#elif GTEST_OS_FUCHSIA
 
-  if (GTEST_FLAG(death_test_style) == "threadsafe" ||
-      GTEST_FLAG(death_test_style) == "fast") {
+  if (GTEST_FLAG_GET(death_test_style) == "threadsafe" ||
+      GTEST_FLAG_GET(death_test_style) == "fast") {
     *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line);
   }
 
-# else
+#else
 
-  if (GTEST_FLAG(death_test_style) == "threadsafe") {
+  if (GTEST_FLAG_GET(death_test_style) == "threadsafe") {
     *test = new ExecDeathTest(statement, std::move(matcher), file, line);
-  } else if (GTEST_FLAG(death_test_style) == "fast") {
+  } else if (GTEST_FLAG_GET(death_test_style) == "fast") {
     *test = new NoExecDeathTest(statement, std::move(matcher));
   }
 
-# endif  // GTEST_OS_WINDOWS
+#endif  // GTEST_OS_WINDOWS
 
   else {  // NOLINT - this is more readable than unbalanced brackets inside #if.
-    DeathTest::set_last_death_test_message(
-        "Unknown death test style \"" + GTEST_FLAG(death_test_style)
-        + "\" encountered");
+    DeathTest::set_last_death_test_message("Unknown death test style \"" +
+                                           GTEST_FLAG_GET(death_test_style) +
+                                           "\" encountered");
     return false;
   }
 
   return true;
 }
 
-# if GTEST_OS_WINDOWS
+#if GTEST_OS_WINDOWS
 // Recreates the pipe and event handles from the provided parameters,
 // signals the event, and returns a file descriptor wrapped around the pipe
 // handle. This function is called in the child process only.
 static int GetStatusFileDescriptor(unsigned int parent_process_id,
-                            size_t write_handle_as_size_t,
-                            size_t event_handle_as_size_t) {
+                                   size_t write_handle_as_size_t,
+                                   size_t event_handle_as_size_t) {
   AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
-                                                   FALSE,  // Non-inheritable.
-                                                   parent_process_id));
+                                                 FALSE,  // Non-inheritable.
+                                                 parent_process_id));
   if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
     DeathTestAbort("Unable to open parent process " +
                    StreamableToString(parent_process_id));
@@ -1531,8 +1514,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id,
 
   GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
 
-  const HANDLE write_handle =
-      reinterpret_cast<HANDLE>(write_handle_as_size_t);
+  const HANDLE write_handle = reinterpret_cast<HANDLE>(write_handle_as_size_t);
   HANDLE dup_write_handle;
 
   // The newly initialized handle is accessible only in the parent
@@ -1554,9 +1536,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id,
   HANDLE dup_event_handle;
 
   if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
-                         ::GetCurrentProcess(), &dup_event_handle,
-                         0x0,
-                         FALSE,
+                         ::GetCurrentProcess(), &dup_event_handle, 0x0, FALSE,
                          DUPLICATE_SAME_ACCESS)) {
     DeathTestAbort("Unable to duplicate the event handle " +
                    StreamableToString(event_handle_as_size_t) +
@@ -1578,61 +1558,57 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id,
 
   return write_fd;
 }
-# endif  // GTEST_OS_WINDOWS
+#endif  // GTEST_OS_WINDOWS
 
 // Returns a newly created InternalRunDeathTestFlag object with fields
 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
 // the flag is specified; otherwise returns NULL.
 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
-  if (GTEST_FLAG(internal_run_death_test) == "") return nullptr;
+  if (GTEST_FLAG_GET(internal_run_death_test) == "") return nullptr;
 
   // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
   // can use it here.
   int line = -1;
   int index = -1;
   ::std::vector< ::std::string> fields;
-  SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
+  SplitString(GTEST_FLAG_GET(internal_run_death_test), '|', &fields);
   int write_fd = -1;
 
-# if GTEST_OS_WINDOWS
+#if GTEST_OS_WINDOWS
 
   unsigned int parent_process_id = 0;
   size_t write_handle_as_size_t = 0;
   size_t event_handle_as_size_t = 0;
 
-  if (fields.size() != 6
-      || !ParseNaturalNumber(fields[1], &line)
-      || !ParseNaturalNumber(fields[2], &index)
-      || !ParseNaturalNumber(fields[3], &parent_process_id)
-      || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
-      || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
+  if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) ||
+      !ParseNaturalNumber(fields[2], &index) ||
+      !ParseNaturalNumber(fields[3], &parent_process_id) ||
+      !ParseNaturalNumber(fields[4], &write_handle_as_size_t) ||
+      !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
     DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
-                   GTEST_FLAG(internal_run_death_test));
+                   GTEST_FLAG_GET(internal_run_death_test));
   }
-  write_fd = GetStatusFileDescriptor(parent_process_id,
-                                     write_handle_as_size_t,
+  write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t,
                                      event_handle_as_size_t);
 
-# elif GTEST_OS_FUCHSIA
+#elif GTEST_OS_FUCHSIA
 
-  if (fields.size() != 3
-      || !ParseNaturalNumber(fields[1], &line)
-      || !ParseNaturalNumber(fields[2], &index)) {
-    DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
-        + GTEST_FLAG(internal_run_death_test));
+  if (fields.size() != 3 || !ParseNaturalNumber(fields[1], &line) ||
+      !ParseNaturalNumber(fields[2], &index)) {
+    DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
+                   GTEST_FLAG_GET(internal_run_death_test));
   }
 
-# else
+#else
 
-  if (fields.size() != 4
-      || !ParseNaturalNumber(fields[1], &line)
-      || !ParseNaturalNumber(fields[2], &index)
-      || !ParseNaturalNumber(fields[3], &write_fd)) {
-    DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
-        + GTEST_FLAG(internal_run_death_test));
+  if (fields.size() != 4 || !ParseNaturalNumber(fields[1], &line) ||
+      !ParseNaturalNumber(fields[2], &index) ||
+      !ParseNaturalNumber(fields[3], &write_fd)) {
+    DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
+                   GTEST_FLAG_GET(internal_run_death_test));
   }
 
-# endif  // GTEST_OS_WINDOWS
+#endif  // GTEST_OS_WINDOWS
 
   return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
 }
index 0b5629401b5a87c894fa1e2b95554c08874ace87..f6ee90cdb7c7e5f05ebb43baa4b23aa7c4ea3ed8 100644 (file)
 #include "gtest/internal/gtest-filepath.h"
 
 #include <stdlib.h>
-#include "gtest/internal/gtest-port.h"
+
 #include "gtest/gtest-message.h"
+#include "gtest/internal/gtest-port.h"
 
 #if GTEST_OS_WINDOWS_MOBILE
-# include <windows.h>
+#include <windows.h>
 #elif GTEST_OS_WINDOWS
-# include <direct.h>
-# include <io.h>
+#include <direct.h>
+#include <io.h>
 #else
-# include <limits.h>
-# include <climits>  // Some Linux distributions define PATH_MAX here.
-#endif  // GTEST_OS_WINDOWS_MOBILE
+#include <limits.h>
+
+#include <climits>  // Some Linux distributions define PATH_MAX here.
+#endif              // GTEST_OS_WINDOWS_MOBILE
 
 #include "gtest/internal/gtest-string.h"
 
 #if GTEST_OS_WINDOWS
-# define GTEST_PATH_MAX_ _MAX_PATH
+#define GTEST_PATH_MAX_ _MAX_PATH
 #elif defined(PATH_MAX)
-# define GTEST_PATH_MAX_ PATH_MAX
+#define GTEST_PATH_MAX_ PATH_MAX
 #elif defined(_XOPEN_PATH_MAX)
-# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
+#define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
 #else
-# define GTEST_PATH_MAX_ _POSIX_PATH_MAX
+#define GTEST_PATH_MAX_ _POSIX_PATH_MAX
 #endif  // GTEST_OS_WINDOWS
 
 namespace testing {
@@ -66,16 +68,16 @@ namespace internal {
 const char kPathSeparator = '\\';
 const char kAlternatePathSeparator = '/';
 const char kAlternatePathSeparatorString[] = "/";
-# if GTEST_OS_WINDOWS_MOBILE
+#if GTEST_OS_WINDOWS_MOBILE
 // Windows CE doesn't have a current directory. You should not use
 // the current directory in tests on Windows CE, but this at least
 // provides a reasonable fallback.
 const char kCurrentDirectoryString[] = "\\";
 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
 const DWORD kInvalidFileAttributes = 0xffffffff;
-# else
+#else
 const char kCurrentDirectoryString[] = ".\\";
-# endif  // GTEST_OS_WINDOWS_MOBILE
+#endif  // GTEST_OS_WINDOWS_MOBILE
 #else
 const char kPathSeparator = '/';
 const char kCurrentDirectoryString[] = "./";
@@ -99,17 +101,17 @@ FilePath FilePath::GetCurrentDir() {
   // something reasonable.
   return FilePath(kCurrentDirectoryString);
 #elif GTEST_OS_WINDOWS
-  char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
+  char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
   return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
 #else
-  char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
+  char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
   char* result = getcwd(cwd, sizeof(cwd));
-# if GTEST_OS_NACL
+#if GTEST_OS_NACL
   // getcwd will likely fail in NaCl due to the sandbox, so return something
   // reasonable. The user may have provided a shim implementation for getcwd,
   // however, so fallback only when failure is detected.
   return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
-# endif  // GTEST_OS_NACL
+#endif  // GTEST_OS_NACL
   return FilePath(result == nullptr ? "" : cwd);
 #endif  // GTEST_OS_WINDOWS_MOBILE
 }
@@ -121,8 +123,8 @@ FilePath FilePath::GetCurrentDir() {
 FilePath FilePath::RemoveExtension(const char* extension) const {
   const std::string dot_extension = std::string(".") + extension;
   if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
-    return FilePath(pathname_.substr(
-        0, pathname_.length() - dot_extension.length()));
+    return FilePath(
+        pathname_.substr(0, pathname_.length() - dot_extension.length()));
   }
   return *this;
 }
@@ -178,15 +180,14 @@ FilePath FilePath::RemoveFileName() const {
 // than zero (e.g., 12), returns "dir/test_12.xml".
 // On Windows platform, uses \ as the separator rather than /.
 FilePath FilePath::MakeFileName(const FilePath& directory,
-                                const FilePath& base_name,
-                                int number,
+                                const FilePath& base_name, int number,
                                 const char* extension) {
   std::string file;
   if (number == 0) {
     file = base_name.string() + "." + extension;
   } else {
-    file = base_name.string() + "_" + StreamableToString(number)
-        + "." + extension;
+    file =
+        base_name.string() + "_" + StreamableToString(number) + "." + extension;
   }
   return ConcatPaths(directory, FilePath(file));
 }
@@ -195,8 +196,7 @@ FilePath FilePath::MakeFileName(const FilePath& directory,
 // On Windows, uses \ as the separator rather than /.
 FilePath FilePath::ConcatPaths(const FilePath& directory,
                                const FilePath& relative_path) {
-  if (directory.IsEmpty())
-    return relative_path;
+  if (directory.IsEmpty()) return relative_path;
   const FilePath dir(directory.RemoveTrailingPathSeparator());
   return FilePath(dir.string() + kPathSeparator + relative_path.string());
 }
@@ -207,7 +207,7 @@ bool FilePath::FileOrDirectoryExists() const {
 #if GTEST_OS_WINDOWS_MOBILE
   LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
   const DWORD attributes = GetFileAttributes(unicode);
-  delete [] unicode;
+  delete[] unicode;
   return attributes != kInvalidFileAttributes;
 #else
   posix::StatStruct file_stat{};
@@ -222,8 +222,8 @@ bool FilePath::DirectoryExists() const {
 #if GTEST_OS_WINDOWS
   // Don't strip off trailing separator if path is a root directory on
   // Windows (like "C:\\").
-  const FilePath& path(IsRootDirectory() ? *this :
-                                           RemoveTrailingPathSeparator());
+  const FilePath& path(IsRootDirectory() ? *this
+                                         : RemoveTrailingPathSeparator());
 #else
   const FilePath& path(*this);
 #endif
@@ -231,15 +231,15 @@ bool FilePath::DirectoryExists() const {
 #if GTEST_OS_WINDOWS_MOBILE
   LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
   const DWORD attributes = GetFileAttributes(unicode);
-  delete [] unicode;
+  delete[] unicode;
   if ((attributes != kInvalidFileAttributes) &&
       (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
     result = true;
   }
 #else
   posix::StatStruct file_stat{};
-  result = posix::Stat(path.c_str(), &file_stat) == 0 &&
-      posix::IsDir(file_stat);
+  result =
+      posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat);
 #endif  // GTEST_OS_WINDOWS_MOBILE
 
   return result;
@@ -260,10 +260,9 @@ bool FilePath::IsAbsolutePath() const {
   const char* const name = pathname_.c_str();
 #if GTEST_OS_WINDOWS
   return pathname_.length() >= 3 &&
-     ((name[0] >= 'a' && name[0] <= 'z') ||
-      (name[0] >= 'A' && name[0] <= 'Z')) &&
-     name[1] == ':' &&
-     IsPathSeparator(name[2]);
+         ((name[0] >= 'a' && name[0] <= 'z') ||
+          (name[0] >= 'A' && name[0] <= 'Z')) &&
+         name[1] == ':' && IsPathSeparator(name[2]);
 #else
   return IsPathSeparator(name[0]);
 #endif
@@ -321,7 +320,7 @@ bool FilePath::CreateFolder() const {
   FilePath removed_sep(this->RemoveTrailingPathSeparator());
   LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
   int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
-  delete [] unicode;
+  delete[] unicode;
 #elif GTEST_OS_WINDOWS
   int result = _mkdir(pathname_.c_str());
 #elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA
@@ -341,9 +340,8 @@ bool FilePath::CreateFolder() const {
 // name, otherwise return the name string unmodified.
 // On Windows platform, uses \ as the separator, other platforms use /.
 FilePath FilePath::RemoveTrailingPathSeparator() const {
-  return IsDirectory()
-      ? FilePath(pathname_.substr(0, pathname_.length() - 1))
-      : *this;
+  return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1))
+                       : *this;
 }
 
 // Removes any redundant separators that might be in the pathname.
index 6d8cecbbb3828786e56e222999aeccffa1ee23fe..0b9e929c6899562d1b6cdb6a89f145880a3f39a6 100644 (file)
@@ -35,7 +35,7 @@
 #define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
 
 #ifndef _WIN32_WCE
-# include <errno.h>
+#include <errno.h>
 #endif  // !_WIN32_WCE
 #include <stddef.h>
 #include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
 #include "gtest/internal/gtest-port.h"
 
 #if GTEST_CAN_STREAM_RESULTS_
-# include <arpa/inet.h>  // NOLINT
-# include <netdb.h>  // NOLINT
+#include <arpa/inet.h>  // NOLINT
+#include <netdb.h>      // NOLINT
 #endif
 
 #if GTEST_OS_WINDOWS
-# include <windows.h>  // NOLINT
-#endif  // GTEST_OS_WINDOWS
+#include <windows.h>  // NOLINT
+#endif                // GTEST_OS_WINDOWS
 
-#include "gtest/gtest.h"
 #include "gtest/gtest-spi.h"
+#include "gtest/gtest.h"
 
 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
 /* class A needs to have dll-interface to be used by clients of class B */)
 
-namespace testing {
-
 // Declares the flags.
 //
 // We don't want the users to modify this flag in the code, but want
@@ -73,32 +71,13 @@ namespace testing {
 // declare it here as opposed to in gtest.h.
 GTEST_DECLARE_bool_(death_test_use_fork);
 
+namespace testing {
 namespace internal {
 
 // The value of GetTestTypeId() as seen from within the Google Test
 // library.  This is solely for testing GetTestTypeId().
 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
 
-// Names of the flags (needed for parsing Google Test flags).
-const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
-const char kBreakOnFailureFlag[] = "break_on_failure";
-const char kCatchExceptionsFlag[] = "catch_exceptions";
-const char kColorFlag[] = "color";
-const char kFailFast[] = "fail_fast";
-const char kFilterFlag[] = "filter";
-const char kListTestsFlag[] = "list_tests";
-const char kOutputFlag[] = "output";
-const char kBriefFlag[] = "brief";
-const char kPrintTimeFlag[] = "print_time";
-const char kPrintUTF8Flag[] = "print_utf8";
-const char kRandomSeedFlag[] = "random_seed";
-const char kRepeatFlag[] = "repeat";
-const char kShuffleFlag[] = "shuffle";
-const char kStackTraceDepthFlag[] = "stack_trace_depth";
-const char kStreamResultToFlag[] = "stream_result_to";
-const char kThrowOnFailureFlag[] = "throw_on_failure";
-const char kFlagfileFlag[] = "flagfile";
-
 // A valid random seed must be in [1, kMaxRandomSeed].
 const int kMaxRandomSeed = 99999;
 
@@ -125,21 +104,21 @@ GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
 //
 // On success, stores the value of the flag in *value, and returns
 // true.  On failure, returns false without changing *value.
-GTEST_API_ bool ParseInt32Flag(
-    const char* str, const char* flag, int32_t* value);
+GTEST_API_ bool ParseFlag(const char* str, const char* flag, int32_t* value);
 
 // Returns a random seed in range [1, kMaxRandomSeed] based on the
 // given --gtest_random_seed flag value.
 inline int GetRandomSeedFromFlag(int32_t random_seed_flag) {
-  const unsigned int raw_seed = (random_seed_flag == 0) ?
-      static_cast<unsigned int>(GetTimeInMillis()) :
-      static_cast<unsigned int>(random_seed_flag);
+  const unsigned int raw_seed =
+      (random_seed_flag == 0) ? static_cast<unsigned int>(GetTimeInMillis())
+                              : static_cast<unsigned int>(random_seed_flag);
 
   // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
   // it's easy to type.
   const int normalized_seed =
       static_cast<int>((raw_seed - 1U) %
-                       static_cast<unsigned int>(kMaxRandomSeed)) + 1;
+                       static_cast<unsigned int>(kMaxRandomSeed)) +
+      1;
   return normalized_seed;
 }
 
@@ -160,50 +139,54 @@ class GTestFlagSaver {
  public:
   // The c'tor.
   GTestFlagSaver() {
-    also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
-    break_on_failure_ = GTEST_FLAG(break_on_failure);
-    catch_exceptions_ = GTEST_FLAG(catch_exceptions);
-    color_ = GTEST_FLAG(color);
-    death_test_style_ = GTEST_FLAG(death_test_style);
-    death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
-    fail_fast_ = GTEST_FLAG(fail_fast);
-    filter_ = GTEST_FLAG(filter);
-    internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
-    list_tests_ = GTEST_FLAG(list_tests);
-    output_ = GTEST_FLAG(output);
-    brief_ = GTEST_FLAG(brief);
-    print_time_ = GTEST_FLAG(print_time);
-    print_utf8_ = GTEST_FLAG(print_utf8);
-    random_seed_ = GTEST_FLAG(random_seed);
-    repeat_ = GTEST_FLAG(repeat);
-    shuffle_ = GTEST_FLAG(shuffle);
-    stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
-    stream_result_to_ = GTEST_FLAG(stream_result_to);
-    throw_on_failure_ = GTEST_FLAG(throw_on_failure);
+    also_run_disabled_tests_ = GTEST_FLAG_GET(also_run_disabled_tests);
+    break_on_failure_ = GTEST_FLAG_GET(break_on_failure);
+    catch_exceptions_ = GTEST_FLAG_GET(catch_exceptions);
+    color_ = GTEST_FLAG_GET(color);
+    death_test_style_ = GTEST_FLAG_GET(death_test_style);
+    death_test_use_fork_ = GTEST_FLAG_GET(death_test_use_fork);
+    fail_fast_ = GTEST_FLAG_GET(fail_fast);
+    filter_ = GTEST_FLAG_GET(filter);
+    internal_run_death_test_ = GTEST_FLAG_GET(internal_run_death_test);
+    list_tests_ = GTEST_FLAG_GET(list_tests);
+    output_ = GTEST_FLAG_GET(output);
+    brief_ = GTEST_FLAG_GET(brief);
+    print_time_ = GTEST_FLAG_GET(print_time);
+    print_utf8_ = GTEST_FLAG_GET(print_utf8);
+    random_seed_ = GTEST_FLAG_GET(random_seed);
+    repeat_ = GTEST_FLAG_GET(repeat);
+    recreate_environments_when_repeating_ =
+        GTEST_FLAG_GET(recreate_environments_when_repeating);
+    shuffle_ = GTEST_FLAG_GET(shuffle);
+    stack_trace_depth_ = GTEST_FLAG_GET(stack_trace_depth);
+    stream_result_to_ = GTEST_FLAG_GET(stream_result_to);
+    throw_on_failure_ = GTEST_FLAG_GET(throw_on_failure);
   }
 
   // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
   ~GTestFlagSaver() {
-    GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
-    GTEST_FLAG(break_on_failure) = break_on_failure_;
-    GTEST_FLAG(catch_exceptions) = catch_exceptions_;
-    GTEST_FLAG(color) = color_;
-    GTEST_FLAG(death_test_style) = death_test_style_;
-    GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
-    GTEST_FLAG(filter) = filter_;
-    GTEST_FLAG(fail_fast) = fail_fast_;
-    GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
-    GTEST_FLAG(list_tests) = list_tests_;
-    GTEST_FLAG(output) = output_;
-    GTEST_FLAG(brief) = brief_;
-    GTEST_FLAG(print_time) = print_time_;
-    GTEST_FLAG(print_utf8) = print_utf8_;
-    GTEST_FLAG(random_seed) = random_seed_;
-    GTEST_FLAG(repeat) = repeat_;
-    GTEST_FLAG(shuffle) = shuffle_;
-    GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
-    GTEST_FLAG(stream_result_to) = stream_result_to_;
-    GTEST_FLAG(throw_on_failure) = throw_on_failure_;
+    GTEST_FLAG_SET(also_run_disabled_tests, also_run_disabled_tests_);
+    GTEST_FLAG_SET(break_on_failure, break_on_failure_);
+    GTEST_FLAG_SET(catch_exceptions, catch_exceptions_);
+    GTEST_FLAG_SET(color, color_);
+    GTEST_FLAG_SET(death_test_style, death_test_style_);
+    GTEST_FLAG_SET(death_test_use_fork, death_test_use_fork_);
+    GTEST_FLAG_SET(filter, filter_);
+    GTEST_FLAG_SET(fail_fast, fail_fast_);
+    GTEST_FLAG_SET(internal_run_death_test, internal_run_death_test_);
+    GTEST_FLAG_SET(list_tests, list_tests_);
+    GTEST_FLAG_SET(output, output_);
+    GTEST_FLAG_SET(brief, brief_);
+    GTEST_FLAG_SET(print_time, print_time_);
+    GTEST_FLAG_SET(print_utf8, print_utf8_);
+    GTEST_FLAG_SET(random_seed, random_seed_);
+    GTEST_FLAG_SET(repeat, repeat_);
+    GTEST_FLAG_SET(recreate_environments_when_repeating,
+                   recreate_environments_when_repeating_);
+    GTEST_FLAG_SET(shuffle, shuffle_);
+    GTEST_FLAG_SET(stack_trace_depth, stack_trace_depth_);
+    GTEST_FLAG_SET(stream_result_to, stream_result_to_);
+    GTEST_FLAG_SET(throw_on_failure, throw_on_failure_);
   }
 
  private:
@@ -224,6 +207,7 @@ class GTestFlagSaver {
   bool print_utf8_;
   int32_t random_seed_;
   int32_t repeat_;
+  bool recreate_environments_when_repeating_;
   bool shuffle_;
   int32_t stack_trace_depth_;
   std::string stream_result_to_;
@@ -278,8 +262,8 @@ GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val);
 // returns true if and only if the test should be run on this shard. The test id
 // is some arbitrary but unique non-negative integer assigned to each test
 // method. Assumes that 0 <= shard_index < total_shards.
-GTEST_API_ bool ShouldRunTestOnShard(
-    int total_shards, int shard_index, int test_id);
+GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index,
+                                     int test_id);
 
 // STL container utilities.
 
@@ -290,9 +274,8 @@ inline int CountIf(const Container& c, Predicate predicate) {
   // Implemented as an explicit loop since std::count_if() in libCstd on
   // Solaris has a non-standard signature.
   int count = 0;
-  for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
-    if (predicate(*it))
-      ++count;
+  for (auto it = c.begin(); it != c.end(); ++it) {
+    if (predicate(*it)) ++count;
   }
   return count;
 }
@@ -441,7 +424,9 @@ class OsStackTraceGetterInterface {
   static const char* const kElidedFramesMarker;
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
+  OsStackTraceGetterInterface(const OsStackTraceGetterInterface&) = delete;
+  OsStackTraceGetterInterface& operator=(const OsStackTraceGetterInterface&) =
+      delete;
 };
 
 // A working implementation of the OsStackTraceGetterInterface interface.
@@ -463,7 +448,8 @@ class OsStackTraceGetter : public OsStackTraceGetterInterface {
   void* caller_frame_ = nullptr;
 #endif  // GTEST_HAS_ABSL
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
+  OsStackTraceGetter(const OsStackTraceGetter&) = delete;
+  OsStackTraceGetter& operator=(const OsStackTraceGetter&) = delete;
 };
 
 // Information about a Google Test trace point.
@@ -476,7 +462,7 @@ struct TraceInfo {
 // This is the default global test part result reporter used in UnitTestImpl.
 // This class should only be used by UnitTestImpl.
 class DefaultGlobalTestPartResultReporter
-  : public TestPartResultReporterInterface {
+    : public TestPartResultReporterInterface {
  public:
   explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
   // Implements the TestPartResultReporterInterface. Reports the test part
@@ -486,7 +472,10 @@ class DefaultGlobalTestPartResultReporter
  private:
   UnitTestImpl* const unit_test_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
+  DefaultGlobalTestPartResultReporter(
+      const DefaultGlobalTestPartResultReporter&) = delete;
+  DefaultGlobalTestPartResultReporter& operator=(
+      const DefaultGlobalTestPartResultReporter&) = delete;
 };
 
 // This is the default per thread test part result reporter used in
@@ -502,7 +491,10 @@ class DefaultPerThreadTestPartResultReporter
  private:
   UnitTestImpl* const unit_test_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
+  DefaultPerThreadTestPartResultReporter(
+      const DefaultPerThreadTestPartResultReporter&) = delete;
+  DefaultPerThreadTestPartResultReporter& operator=(
+      const DefaultPerThreadTestPartResultReporter&) = delete;
 };
 
 // The private implementation of the UnitTest class.  We don't protect
@@ -640,7 +632,8 @@ class GTEST_API_ UnitTestImpl {
   // For example, if Foo() calls Bar(), which in turn calls
   // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
   // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
-  std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
+  std::string CurrentOsStackTraceExceptTop(int skip_count)
+      GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_;
 
   // Finds and returns a TestSuite with the given name.  If one doesn't
   // exist, creates one and returns it.
@@ -744,9 +737,7 @@ class GTEST_API_ UnitTestImpl {
   }
 
   // Clears the results of ad-hoc test assertions.
-  void ClearAdHocTestResult() {
-    ad_hoc_test_result_.Clear();
-  }
+  void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); }
 
   // Adds a TestProperty to the current TestResult object when invoked in a
   // context of a test or a test suite, or to the global property set. If the
@@ -754,10 +745,7 @@ class GTEST_API_ UnitTestImpl {
   // updated.
   void RecordProperty(const TestProperty& test_property);
 
-  enum ReactionToSharding {
-    HONOR_SHARDING_PROTOCOL,
-    IGNORE_SHARDING_PROTOCOL
-  };
+  enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL };
 
   // Matches the full name of each test against the user-specified
   // filter to decide whether the test should run, then records the
@@ -963,7 +951,8 @@ class GTEST_API_ UnitTestImpl {
   // starts.
   bool catch_exceptions_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
+  UnitTestImpl(const UnitTestImpl&) = delete;
+  UnitTestImpl& operator=(const UnitTestImpl&) = delete;
 };  // class UnitTestImpl
 
 // Convenience function for accessing the global UnitTest
@@ -986,8 +975,9 @@ GTEST_API_ bool IsValidEscape(char ch);
 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
 GTEST_API_ bool ValidateRegex(const char* regex);
 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
-GTEST_API_ bool MatchRepetitionAndRegexAtHead(
-    bool escaped, char ch, char repeat, const char* regex, const char* str);
+GTEST_API_ bool MatchRepetitionAndRegexAtHead(bool escaped, char ch,
+                                              char repeat, const char* regex,
+                                              const char* str);
 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
 
 #endif  // GTEST_USES_SIMPLE_RE
@@ -1089,8 +1079,7 @@ class StreamingListener : public EmptyTestEventListener {
     }
 
     ~SocketWriter() override {
-      if (sockfd_ != -1)
-        CloseConnection();
+      if (sockfd_ != -1) CloseConnection();
     }
 
     // Sends a string to the socket.
@@ -1100,9 +1089,8 @@ class StreamingListener : public EmptyTestEventListener {
 
       const auto len = static_cast<size_t>(message.length());
       if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) {
-        GTEST_LOG_(WARNING)
-            << "stream_result_to: failed to stream to "
-            << host_name_ << ":" << port_num_;
+        GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to "
+                            << host_name_ << ":" << port_num_;
       }
     }
 
@@ -1123,7 +1111,8 @@ class StreamingListener : public EmptyTestEventListener {
     const std::string host_name_;
     const std::string port_num_;
 
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
+    SocketWriter(const SocketWriter&) = delete;
+    SocketWriter& operator=(const SocketWriter&) = delete;
   };  // class SocketWriter
 
   // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
@@ -1135,7 +1124,9 @@ class StreamingListener : public EmptyTestEventListener {
   }
 
   explicit StreamingListener(AbstractSocketWriter* socket_writer)
-      : socket_writer_(socket_writer) { Start(); }
+      : socket_writer_(socket_writer) {
+    Start();
+  }
 
   void OnTestProgramStart(const UnitTest& /* unit_test */) override {
     SendLn("event=TestProgramStart");
@@ -1158,22 +1149,22 @@ class StreamingListener : public EmptyTestEventListener {
 
   void OnTestIterationEnd(const UnitTest& unit_test,
                           int /* iteration */) override {
-    SendLn("event=TestIterationEnd&passed=" +
-           FormatBool(unit_test.Passed()) + "&elapsed_time=" +
-           StreamableToString(unit_test.elapsed_time()) + "ms");
+    SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) +
+           "&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) +
+           "ms");
   }
 
   // Note that "event=TestCaseStart" is a wire format and has to remain
   // "case" for compatibility
-  void OnTestCaseStart(const TestCase& test_case) override {
-    SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
+  void OnTestSuiteStart(const TestSuite& test_suite) override {
+    SendLn(std::string("event=TestCaseStart&name=") + test_suite.name());
   }
 
   // Note that "event=TestCaseEnd" is a wire format and has to remain
   // "case" for compatibility
-  void OnTestCaseEnd(const TestCase& test_case) override {
-    SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) +
-           "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) +
+  void OnTestSuiteEnd(const TestSuite& test_suite) override {
+    SendLn("event=TestCaseEnd&passed=" + FormatBool(test_suite.Passed()) +
+           "&elapsed_time=" + StreamableToString(test_suite.elapsed_time()) +
            "ms");
   }
 
@@ -1183,8 +1174,7 @@ class StreamingListener : public EmptyTestEventListener {
 
   void OnTestEnd(const TestInfo& test_info) override {
     SendLn("event=TestEnd&passed=" +
-           FormatBool((test_info.result())->Passed()) +
-           "&elapsed_time=" +
+           FormatBool((test_info.result())->Passed()) + "&elapsed_time=" +
            StreamableToString((test_info.result())->elapsed_time()) + "ms");
   }
 
@@ -1208,7 +1198,8 @@ class StreamingListener : public EmptyTestEventListener {
 
   const std::unique_ptr<AbstractSocketWriter> socket_writer_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
+  StreamingListener(const StreamingListener&) = delete;
+  StreamingListener& operator=(const StreamingListener&) = delete;
 };  // class StreamingListener
 
 #endif  // GTEST_CAN_STREAM_RESULTS_
index 65104ebab1ba9af06327fc94c0a038b6806d4206..7e3bcc0cff3806c1151357ab1f31da2a0b5b9dbc 100644 (file)
 // This file implements just enough of the matcher interface to allow
 // EXPECT_DEATH and friends to accept a matcher argument.
 
-#include "gtest/internal/gtest-internal.h"
-#include "gtest/internal/gtest-port.h"
 #include "gtest/gtest-matchers.h"
 
 #include <string>
 
+#include "gtest/internal/gtest-internal.h"
+#include "gtest/internal/gtest-port.h"
+
 namespace testing {
 
 // Constructs a matcher that matches a const std::string& whose value is
index 53a4d37f97d2ef1355cd2e5788569d8aab11f84a..d797fe4d5866c7da296a64428ad4da352c1e7fe4 100644 (file)
 // (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/internal/gtest-port.h"
 
 #include <limits.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+
 #include <cstdint>
 #include <fstream>
 #include <memory>
 
 #if GTEST_OS_WINDOWS
-# include <windows.h>
-# include <io.h>
-# include <sys/stat.h>
-# include <map>  // Used in ThreadLocal.
-# ifdef _MSC_VER
-#  include <crtdbg.h>
-# endif  // _MSC_VER
+#include <io.h>
+#include <sys/stat.h>
+#include <windows.h>
+
+#include <map>  // Used in ThreadLocal.
+#ifdef _MSC_VER
+#include <crtdbg.h>
+#endif  // _MSC_VER
 #else
-# include <unistd.h>
+#include <unistd.h>
 #endif  // GTEST_OS_WINDOWS
 
 #if GTEST_OS_MAC
-# include <mach/mach_init.h>
-# include <mach/task.h>
-# include <mach/vm_map.h>
+#include <mach/mach_init.h>
+#include <mach/task.h>
+#include <mach/vm_map.h>
 #endif  // GTEST_OS_MAC
 
 #if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
     GTEST_OS_NETBSD || GTEST_OS_OPENBSD
-# include <sys/sysctl.h>
-# if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
-#  include <sys/user.h>
-# endif
+#include <sys/sysctl.h>
+#if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
+#include <sys/user.h>
+#endif
 #endif
 
 #if GTEST_OS_QNX
-# include <devctl.h>
-# include <fcntl.h>
-# include <sys/procfs.h>
+#include <devctl.h>
+#include <fcntl.h>
+#include <sys/procfs.h>
 #endif  // GTEST_OS_QNX
 
 #if GTEST_OS_AIX
-# include <procinfo.h>
-# include <sys/types.h>
+#include <procinfo.h>
+#include <sys/types.h>
 #endif  // GTEST_OS_AIX
 
 #if GTEST_OS_FUCHSIA
-# include <zircon/process.h>
-# include <zircon/syscalls.h>
+#include <zircon/process.h>
+#include <zircon/syscalls.h>
 #endif  // GTEST_OS_FUCHSIA
 
-#include "gtest/gtest-spi.h"
 #include "gtest/gtest-message.h"
+#include "gtest/gtest-spi.h"
 #include "gtest/internal/gtest-internal.h"
 #include "gtest/internal/gtest-string.h"
 #include "src/gtest-internal-inl.h"
 namespace testing {
 namespace internal {
 
-#if defined(_MSC_VER) || defined(__BORLANDC__)
-// MSVC and C++Builder do not provide a definition of STDERR_FILENO.
-const int kStdOutFileno = 1;
-const int kStdErrFileno = 2;
-#else
-const int kStdOutFileno = STDOUT_FILENO;
-const int kStdErrFileno = STDERR_FILENO;
-#endif  // _MSC_VER
-
-#if GTEST_OS_LINUX
+#if GTEST_OS_LINUX || GTEST_OS_GNU_HURD
 
 namespace {
 template <typename T>
@@ -131,8 +123,7 @@ size_t GetThreadCount() {
   if (status == KERN_SUCCESS) {
     // task_threads allocates resources in thread_list and we need to free them
     // to avoid leaks.
-    vm_deallocate(task,
-                  reinterpret_cast<vm_address_t>(thread_list),
+    vm_deallocate(task, reinterpret_cast<vm_address_t>(thread_list),
                   sizeof(thread_t) * thread_count);
     return static_cast<size_t>(thread_count);
   } else {
@@ -141,7 +132,7 @@ size_t GetThreadCount() {
 }
 
 #elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
-      GTEST_OS_NETBSD
+    GTEST_OS_NETBSD
 
 #if GTEST_OS_NETBSD
 #undef KERN_PROC
@@ -184,12 +175,12 @@ size_t GetThreadCount() {
 // we cannot detect it.
 size_t GetThreadCount() {
   int mib[] = {
-    CTL_KERN,
-    KERN_PROC,
-    KERN_PROC_PID | KERN_PROC_SHOW_THREADS,
-    getpid(),
-    sizeof(struct kinfo_proc),
-    0,
+      CTL_KERN,
+      KERN_PROC,
+      KERN_PROC_PID | KERN_PROC_SHOW_THREADS,
+      getpid(),
+      sizeof(struct kinfo_proc),
+      0,
   };
   u_int miblen = sizeof(mib) / sizeof(mib[0]);
 
@@ -210,8 +201,7 @@ size_t GetThreadCount() {
   // exclude empty members
   size_t nthreads = 0;
   for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) {
-    if (info[i].p_tid != -1)
-      nthreads++;
+    if (info[i].p_tid != -1) nthreads++;
   }
   return nthreads;
 }
@@ -254,13 +244,9 @@ size_t GetThreadCount() {
 size_t GetThreadCount() {
   int dummy_buffer;
   size_t avail;
-  zx_status_t status = zx_object_get_info(
-      zx_process_self(),
-      ZX_INFO_PROCESS_THREADS,
-      &dummy_buffer,
-      0,
-      nullptr,
-      &avail);
+  zx_status_t status =
+      zx_object_get_info(zx_process_self(), ZX_INFO_PROCESS_THREADS,
+                         &dummy_buffer, 0, nullptr, &avail);
   if (status == ZX_OK) {
     return avail;
   } else {
@@ -280,27 +266,15 @@ size_t GetThreadCount() {
 
 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
 
-void SleepMilliseconds(int n) {
-  ::Sleep(static_cast<DWORD>(n));
-}
+AutoHandle::AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
 
-AutoHandle::AutoHandle()
-    : handle_(INVALID_HANDLE_VALUE) {}
+AutoHandle::AutoHandle(Handle handle) : handle_(handle) {}
 
-AutoHandle::AutoHandle(Handle handle)
-    : handle_(handle) {}
+AutoHandle::~AutoHandle() { Reset(); }
 
-AutoHandle::~AutoHandle() {
-  Reset();
-}
-
-AutoHandle::Handle AutoHandle::Get() const {
-  return handle_;
-}
+AutoHandle::Handle AutoHandle::Get() const { return handle_; }
 
-void AutoHandle::Reset() {
-  Reset(INVALID_HANDLE_VALUE);
-}
+void AutoHandle::Reset() { Reset(INVALID_HANDLE_VALUE); }
 
 void AutoHandle::Reset(HANDLE handle) {
   // Resetting with the same handle we already own is invalid.
@@ -312,7 +286,7 @@ void AutoHandle::Reset(HANDLE handle) {
   } else {
     GTEST_CHECK_(!IsCloseable())
         << "Resetting a valid handle to itself is likely a programmer error "
-            "and thus not allowed.";
+           "and thus not allowed.";
   }
 }
 
@@ -322,23 +296,6 @@ bool AutoHandle::IsCloseable() const {
   return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;
 }
 
-Notification::Notification()
-    : event_(::CreateEvent(nullptr,     // Default security attributes.
-                           TRUE,        // Do not reset automatically.
-                           FALSE,       // Initially unset.
-                           nullptr)) {  // Anonymous event.
-  GTEST_CHECK_(event_.Get() != nullptr);
-}
-
-void Notification::Notify() {
-  GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
-}
-
-void Notification::WaitForNotification() {
-  GTEST_CHECK_(
-      ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
-}
-
 Mutex::Mutex()
     : owner_thread_id_(0),
       type_(kDynamic),
@@ -391,25 +348,25 @@ namespace {
 //    MemoryIsNotDeallocated memory_is_not_deallocated;
 //    critical_section_ = new CRITICAL_SECTION;
 //
-class MemoryIsNotDeallocated
-{
+class MemoryIsNotDeallocated {
  public:
   MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {
     old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
     // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT
     // doesn't report mem leak if there's no matching deallocation.
-    _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
+    (void)_CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);
   }
 
   ~MemoryIsNotDeallocated() {
     // Restore the original _CRTDBG_ALLOC_MEM_DF flag
-    _CrtSetDbgFlag(old_crtdbg_flag_);
+    (void)_CrtSetDbgFlag(old_crtdbg_flag_);
   }
 
  private:
   int old_crtdbg_flag_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);
+  MemoryIsNotDeallocated(const MemoryIsNotDeallocated&) = delete;
+  MemoryIsNotDeallocated& operator=(const MemoryIsNotDeallocated&) = delete;
 };
 #endif  // _MSC_VER
 
@@ -435,15 +392,13 @@ void Mutex::ThreadSafeLazyInit() {
         ::InitializeCriticalSection(critical_section_);
         // Updates the critical_section_init_phase_ to 2 to signal
         // initialization complete.
-        GTEST_CHECK_(::InterlockedCompareExchange(
-                          &critical_section_init_phase_, 2L, 1L) ==
-                      1L);
+        GTEST_CHECK_(::InterlockedCompareExchange(&critical_section_init_phase_,
+                                                  2L, 1L) == 1L);
         break;
       case 1:
         // Somebody else is already initializing the mutex; spin until they
         // are done.
-        while (::InterlockedCompareExchange(&critical_section_init_phase_,
-                                            2L,
+        while (::InterlockedCompareExchange(&critical_section_init_phase_, 2L,
                                             2L) != 2L) {
           // Possibly yields the rest of the thread's time slice to other
           // threads.
@@ -488,9 +443,7 @@ class ThreadWithParamSupport : public ThreadWithParamBase {
  private:
   struct ThreadMainParam {
     ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
-        : runnable_(runnable),
-          thread_can_start_(thread_can_start) {
-    }
+        : runnable_(runnable), thread_can_start_(thread_can_start) {}
     std::unique_ptr<Runnable> runnable_;
     // Does not own.
     Notification* thread_can_start_;
@@ -508,20 +461,18 @@ class ThreadWithParamSupport : public ThreadWithParamBase {
   // Prohibit instantiation.
   ThreadWithParamSupport();
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
+  ThreadWithParamSupport(const ThreadWithParamSupport&) = delete;
+  ThreadWithParamSupport& operator=(const ThreadWithParamSupport&) = delete;
 };
 
 }  // namespace
 
-ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
+ThreadWithParamBase::ThreadWithParamBase(Runnablerunnable,
                                          Notification* thread_can_start)
-      : thread_(ThreadWithParamSupport::CreateThread(runnable,
-                                                     thread_can_start)) {
-}
+    : thread_(
+          ThreadWithParamSupport::CreateThread(runnable, thread_can_start)) {}
 
-ThreadWithParamBase::~ThreadWithParamBase() {
-  Join();
-}
+ThreadWithParamBase::~ThreadWithParamBase() { Join(); }
 
 void ThreadWithParamBase::Join() {
   GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
@@ -548,8 +499,10 @@ class ThreadLocalRegistryImpl {
     ThreadIdToThreadLocals::iterator thread_local_pos =
         thread_to_thread_locals->find(current_thread);
     if (thread_local_pos == thread_to_thread_locals->end()) {
-      thread_local_pos = thread_to_thread_locals->insert(
-          std::make_pair(current_thread, ThreadLocalValues())).first;
+      thread_local_pos =
+          thread_to_thread_locals
+              ->insert(std::make_pair(current_thread, ThreadLocalValues()))
+              .first;
       StartWatcherThreadFor(current_thread);
     }
     ThreadLocalValues& thread_local_values = thread_local_pos->second;
@@ -577,9 +530,8 @@ class ThreadLocalRegistryImpl {
       ThreadIdToThreadLocals* const thread_to_thread_locals =
           GetThreadLocalsMapLocked();
       for (ThreadIdToThreadLocals::iterator it =
-          thread_to_thread_locals->begin();
-          it != thread_to_thread_locals->end();
-          ++it) {
+               thread_to_thread_locals->begin();
+           it != thread_to_thread_locals->end(); ++it) {
         ThreadLocalValues& thread_local_values = it->second;
         ThreadLocalValues::iterator value_pos =
             thread_local_values.find(thread_local_instance);
@@ -609,9 +561,8 @@ class ThreadLocalRegistryImpl {
       if (thread_local_pos != thread_to_thread_locals->end()) {
         ThreadLocalValues& thread_local_values = thread_local_pos->second;
         for (ThreadLocalValues::iterator value_pos =
-            thread_local_values.begin();
-            value_pos != thread_local_values.end();
-            ++value_pos) {
+                 thread_local_values.begin();
+             value_pos != thread_local_values.end(); ++value_pos) {
           value_holders.push_back(value_pos->second);
         }
         thread_to_thread_locals->erase(thread_local_pos);
@@ -637,9 +588,8 @@ class ThreadLocalRegistryImpl {
   static void StartWatcherThreadFor(DWORD thread_id) {
     // The returned handle will be kept in thread_map and closed by
     // watcher_thread in WatcherThreadFunc.
-    HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
-                                 FALSE,
-                                 thread_id);
+    HANDLE thread =
+        ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, thread_id);
     GTEST_CHECK_(thread != nullptr);
     // We need to pass a valid thread ID pointer into CreateThread for it
     // to work correctly under Win98.
@@ -650,7 +600,8 @@ class ThreadLocalRegistryImpl {
         &ThreadLocalRegistryImpl::WatcherThreadFunc,
         reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
         CREATE_SUSPENDED, &watcher_thread_id);
-    GTEST_CHECK_(watcher_thread != nullptr);
+    GTEST_CHECK_(watcher_thread != nullptr)
+        << "CreateThread failed with error " << ::GetLastError() << ".";
     // Give the watcher thread the same priority as ours to avoid being
     // blocked by it.
     ::SetThreadPriority(watcher_thread,
@@ -664,8 +615,7 @@ class ThreadLocalRegistryImpl {
   static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
     const ThreadIdAndHandle* tah =
         reinterpret_cast<const ThreadIdAndHandle*>(param);
-    GTEST_CHECK_(
-        ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
+    GTEST_CHECK_(::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
     OnThreadExit(tah->first);
     ::CloseHandle(tah->second);
     delete tah;
@@ -689,16 +639,17 @@ class ThreadLocalRegistryImpl {
 };
 
 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);  // NOLINT
-Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);  // NOLINT
+Mutex ThreadLocalRegistryImpl::thread_map_mutex_(
+    Mutex::kStaticMutex);  // NOLINT
 
 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
-      const ThreadLocalBase* thread_local_instance) {
+    const ThreadLocalBase* thread_local_instance) {
   return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
       thread_local_instance);
 }
 
 void ThreadLocalRegistry::OnThreadLocalDestroyed(
-      const ThreadLocalBase* thread_local_instance) {
+    const ThreadLocalBase* thread_local_instance) {
   ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
 }
 
@@ -786,7 +737,7 @@ bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
 bool IsAsciiWordChar(char ch) {
   return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
-      ('0' <= ch && ch <= '9') || ch == '_';
+         ('0' <= ch && ch <= '9') || ch == '_';
 }
 
 // Returns true if and only if "\\c" is a supported escape sequence.
@@ -799,17 +750,28 @@ bool IsValidEscape(char c) {
 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
   if (escaped) {  // "\\p" where p is pattern_char.
     switch (pattern_char) {
-      case 'd': return IsAsciiDigit(ch);
-      case 'D': return !IsAsciiDigit(ch);
-      case 'f': return ch == '\f';
-      case 'n': return ch == '\n';
-      case 'r': return ch == '\r';
-      case 's': return IsAsciiWhiteSpace(ch);
-      case 'S': return !IsAsciiWhiteSpace(ch);
-      case 't': return ch == '\t';
-      case 'v': return ch == '\v';
-      case 'w': return IsAsciiWordChar(ch);
-      case 'W': return !IsAsciiWordChar(ch);
+      case 'd':
+        return IsAsciiDigit(ch);
+      case 'D':
+        return !IsAsciiDigit(ch);
+      case 'f':
+        return ch == '\f';
+      case 'n':
+        return ch == '\n';
+      case 'r':
+        return ch == '\r';
+      case 's':
+        return IsAsciiWhiteSpace(ch);
+      case 'S':
+        return !IsAsciiWhiteSpace(ch);
+      case 't':
+        return ch == '\t';
+      case 'v':
+        return ch == '\v';
+      case 'w':
+        return IsAsciiWordChar(ch);
+      case 'W':
+        return !IsAsciiWordChar(ch);
     }
     return IsAsciiPunct(pattern_char) && pattern_char == ch;
   }
@@ -820,7 +782,8 @@ bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
 // Helper function used by ValidateRegex() to format error messages.
 static std::string FormatRegexSyntaxError(const char* regex, int index) {
   return (Message() << "Syntax error at index " << index
-          << " in simple regular expression \"" << regex << "\": ").GetString();
+                    << " in simple regular expression \"" << regex << "\": ")
+      .GetString();
 }
 
 // Generates non-fatal failures and returns false if regex is invalid;
@@ -862,12 +825,12 @@ bool ValidateRegex(const char* regex) {
                       << "'$' can only appear at the end.";
         is_valid = false;
       } else if (IsInSet(ch, "()[]{}|")) {
-        ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
-                      << "'" << ch << "' is unsupported.";
+        ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch
+                      << "' is unsupported.";
         is_valid = false;
       } else if (IsRepeat(ch) && !prev_repeatable) {
-        ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
-                      << "'" << ch << "' can only follow a repeatable token.";
+        ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch
+                      << "' can only follow a repeatable token.";
         is_valid = false;
       }
 
@@ -885,12 +848,10 @@ bool ValidateRegex(const char* regex) {
 // characters to be indexable by size_t, in which case the test will
 // probably time out anyway.  We are fine with this limitation as
 // std::string has it too.
-bool MatchRepetitionAndRegexAtHead(
-    bool escaped, char c, char repeat, const char* regex,
-    const char* str) {
+bool MatchRepetitionAndRegexAtHead(bool escaped, char c, char repeat,
+                                   const char* regex, const char* str) {
   const size_t min_count = (repeat == '+') ? 1 : 0;
-  const size_t max_count = (repeat == '?') ? 1 :
-      static_cast<size_t>(-1) - 1;
+  const size_t max_count = (repeat == '?') ? 1 : static_cast<size_t>(-1) - 1;
   // We cannot call numeric_limits::max() as it conflicts with the
   // max() macro on Windows.
 
@@ -903,8 +864,7 @@ bool MatchRepetitionAndRegexAtHead(
       // greedy match.
       return true;
     }
-    if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
-      return false;
+    if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) return false;
   }
   return false;
 }
@@ -918,25 +878,23 @@ bool MatchRegexAtHead(const char* regex, const char* str) {
 
   // "$" only matches the end of a string.  Note that regex being
   // valid guarantees that there's nothing after "$" in it.
-  if (*regex == '$')
-    return *str == '\0';
+  if (*regex == '$') return *str == '\0';
 
   // Is the first thing in regex an escape sequence?
   const bool escaped = *regex == '\\';
-  if (escaped)
-    ++regex;
+  if (escaped) ++regex;
   if (IsRepeat(regex[1])) {
     // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
     // here's an indirect recursion.  It terminates as the regex gets
     // shorter in each recursion.
-    return MatchRepetitionAndRegexAtHead(
-        escaped, regex[0], regex[1], regex + 2, str);
+    return MatchRepetitionAndRegexAtHead(escaped, regex[0], regex[1], regex + 2,
+                                         str);
   } else {
     // regex isn't empty, isn't "$", and doesn't start with a
     // repetition.  We match the first atom of regex with the first
     // character of str and recurse.
     return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
-        MatchRegexAtHead(regex + 1, str + 1);
+           MatchRegexAtHead(regex + 1, str + 1);
   }
 }
 
@@ -951,13 +909,11 @@ bool MatchRegexAtHead(const char* regex, const char* str) {
 bool MatchRegexAnywhere(const char* regex, const char* str) {
   if (regex == nullptr || str == nullptr) return false;
 
-  if (*regex == '^')
-    return MatchRegexAtHead(regex + 1, str);
+  if (*regex == '^') return MatchRegexAtHead(regex + 1, str);
 
   // A successful match can be anywhere in str.
   do {
-    if (MatchRegexAtHead(regex, str))
-      return true;
+    if (MatchRegexAtHead(regex, str)) return true;
   } while (*str++ != '\0');
   return false;
 }
@@ -1038,8 +994,8 @@ GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
 // FormatFileLocation in order to contrast the two functions.
 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
 // to the file location it produces, unlike FormatFileLocation().
-GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
-    const char* file, int line) {
+GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
+                                                               int line) {
   const std::string file_name(file == nullptr ? kUnknownFile : file);
 
   if (line < 0)
@@ -1050,12 +1006,13 @@ GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
 
 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
     : severity_(severity) {
-  const char* const marker =
-      severity == GTEST_INFO ?    "[  INFO ]" :
-      severity == GTEST_WARNING ? "[WARNING]" :
-      severity == GTEST_ERROR ?   "[ ERROR ]" : "[ FATAL ]";
-  GetStream() << ::std::endl << marker << " "
-              << FormatFileLocation(file, line).c_str() << ": ";
+  const char* const marker = severity == GTEST_INFO      ? "[  INFO ]"
+                             : severity == GTEST_WARNING ? "[WARNING]"
+                             : severity == GTEST_ERROR   ? "[ ERROR ]"
+                                                         : "[ FATAL ]";
+  GetStream() << ::std::endl
+              << marker << " " << FormatFileLocation(file, line).c_str()
+              << ": ";
 }
 
 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
@@ -1078,27 +1035,26 @@ class CapturedStream {
  public:
   // The ctor redirects the stream to a temporary file.
   explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
-# if GTEST_OS_WINDOWS
-    char temp_dir_path[MAX_PATH + 1] = { '\0' };  // NOLINT
-    char temp_file_path[MAX_PATH + 1] = { '\0' };  // NOLINT
+#if GTEST_OS_WINDOWS
+    char temp_dir_path[MAX_PATH + 1] = {'\0'};   // NOLINT
+    char temp_file_path[MAX_PATH + 1] = {'\0'};  // NOLINT
 
     ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
-    const UINT success = ::GetTempFileNameA(temp_dir_path,
-                                            "gtest_redir",
+    const UINT success = ::GetTempFileNameA(temp_dir_path, "gtest_redir",
                                             0,  // Generate unique file name.
                                             temp_file_path);
     GTEST_CHECK_(success != 0)
         << "Unable to create a temporary file in " << temp_dir_path;
     const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
-    GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
-                                    << temp_file_path;
+    GTEST_CHECK_(captured_fd != -1)
+        << "Unable to open temporary file " << temp_file_path;
     filename_ = temp_file_path;
-# else
+#else
     // There's no guarantee that a test has write access to the current
     // directory, so we create the temporary file in a temporary directory.
     std::string name_template;
 
-#  if GTEST_OS_LINUX_ANDROID
+#if GTEST_OS_LINUX_ANDROID
     // Note: Android applications are expected to call the framework's
     // Context.getExternalStorageDirectory() method through JNI to get
     // the location of the world-writable SD Card directory. However,
@@ -1111,7 +1067,7 @@ class CapturedStream {
     // '/sdcard' and other variants cannot be relied on, as they are not
     // guaranteed to be mounted, or may have a delay in mounting.
     name_template = "/data/local/tmp/";
-#  elif GTEST_OS_IOS
+#elif GTEST_OS_IOS
     char user_temp_dir[PATH_MAX + 1];
 
     // Documented alternative to NSTemporaryDirectory() (for obtaining creating
@@ -1132,9 +1088,9 @@ class CapturedStream {
     name_template = user_temp_dir;
     if (name_template.back() != GTEST_PATH_SEP_[0])
       name_template.push_back(GTEST_PATH_SEP_[0]);
-#  else
+#else
     name_template = "/tmp/";
-#  endif
+#endif
     name_template.append("gtest_captured_stream.XXXXXX");
 
     // mkstemp() modifies the string bytes in place, and does not go beyond the
@@ -1150,15 +1106,13 @@ class CapturedStream {
           << " for test; does the test have access to the /tmp directory?";
     }
     filename_ = std::move(name_template);
-# endif  // GTEST_OS_WINDOWS
+#endif  // GTEST_OS_WINDOWS
     fflush(nullptr);
     dup2(captured_fd, fd_);
     close(captured_fd);
   }
 
-  ~CapturedStream() {
-    remove(filename_.c_str());
-  }
+  ~CapturedStream() { remove(filename_.c_str()); }
 
   std::string GetCapturedString() {
     if (uncaptured_fd_ != -1) {
@@ -1185,7 +1139,8 @@ class CapturedStream {
   // Name of the temporary file holding the stderr output.
   ::std::string filename_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
+  CapturedStream(const CapturedStream&) = delete;
+  CapturedStream& operator=(const CapturedStream&) = delete;
 };
 
 GTEST_DISABLE_MSC_DEPRECATED_POP_()
@@ -1213,6 +1168,15 @@ static std::string GetCapturedStream(CapturedStream** captured_stream) {
   return content;
 }
 
+#if defined(_MSC_VER) || defined(__BORLANDC__)
+// MSVC and C++Builder do not provide a definition of STDERR_FILENO.
+const int kStdOutFileno = 1;
+const int kStdErrFileno = 2;
+#else
+const int kStdOutFileno = STDOUT_FILENO;
+const int kStdErrFileno = STDERR_FILENO;
+#endif  // defined(_MSC_VER) || defined(__BORLANDC__)
+
 // Starts capturing stdout.
 void CaptureStdout() {
   CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
@@ -1235,10 +1199,6 @@ std::string GetCapturedStderr() {
 
 #endif  // GTEST_HAS_STREAM_REDIRECTION
 
-
-
-
-
 size_t GetFileSize(FILE* file) {
   fseek(file, 0, SEEK_END);
   return static_cast<size_t>(ftell(file));
@@ -1256,7 +1216,8 @@ std::string ReadEntireFile(FILE* file) {
   // Keeps reading the file until we cannot read further or the
   // pre-determined file size is reached.
   do {
-    bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
+    bytes_last_read =
+        fread(buffer + bytes_read, 1, file_size - bytes_read, file);
     bytes_read += bytes_last_read;
   } while (bytes_last_read > 0 && bytes_read < file_size);
 
@@ -1344,7 +1305,7 @@ bool ParseInt32(const Message& src_text, const char* str, int32_t* value) {
       // LONG_MAX or LONG_MIN when the input overflows.)
       result != long_value
       // The parsed value overflows as an int32_t.
-      ) {
+  ) {
     Message msg;
     msg << "WARNING: " << src_text
         << " is expected to be a 32-bit integer, but actually"
@@ -1388,8 +1349,8 @@ int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) {
   }
 
   int32_t result = default_value;
-  if (!ParseInt32(Message() << "Environment variable " << env_var,
-                  string_value, &result)) {
+  if (!ParseInt32(Message() << "Environment variable " << env_var, string_value,
+                  &result)) {
     printf("The default value %s is used.\n",
            (Message() << default_value).GetString().c_str());
     fflush(stdout);
@@ -1408,7 +1369,7 @@ int32_t Int32FromGTestEnv(const char* flag, int32_t default_value) {
 // not check that the flag is 'output'
 // In essence this checks an env variable called XML_OUTPUT_FILE
 // and if it is set we prepend "xml:" to its value, if it not set we return ""
-std::string OutputFlagAlsoCheckEnvVar(){
+std::string OutputFlagAlsoCheckEnvVar() {
   std::string default_value_for_output_flag = "";
   const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE");
   if (nullptr != xml_output_file_env) {
index 1b68fcb500550f8d0846b158455a126bbc4bfdf1..f3976d230dacfd386e7c9afea0da778bbd613f86 100644 (file)
@@ -27,7 +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.
 
-
 // Google Test - The Google C++ Testing and Mocking Framework
 //
 // This file implements a universal value printer that can print a
@@ -101,7 +100,7 @@ void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
     PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
     *os << " ... ";
     // Rounds up to 2-byte boundary.
-    const size_t resume_pos = (count - kChunkSize + 1)/2*2;
+    const size_t resume_pos = (count - kChunkSize + 1) / 2 * 2;
     PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
   }
   *os << ">";
@@ -136,11 +135,7 @@ void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
 //   - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
 //   - as a hexadecimal escape sequence (e.g. '\x7F'), or
 //   - as a special escape sequence (e.g. '\r', '\n').
-enum CharFormat {
-  kAsIs,
-  kHexEscape,
-  kSpecialEscape
-};
+enum CharFormat { kAsIs, kHexEscape, kSpecialEscape };
 
 // Returns true if c is a printable ASCII character.  We test the
 // value of c directly instead of calling isprint(), which is buggy on
@@ -213,35 +208,21 @@ static CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) {
   }
 }
 
-static const char* GetCharWidthPrefix(char) {
-  return "";
-}
+static const char* GetCharWidthPrefix(char) { return ""; }
 
-static const char* GetCharWidthPrefix(signed char) {
-  return "";
-}
+static const char* GetCharWidthPrefix(signed char) { return ""; }
 
-static const char* GetCharWidthPrefix(unsigned char) {
-  return "";
-}
+static const char* GetCharWidthPrefix(unsigned char) { return ""; }
 
 #ifdef __cpp_char8_t
-static const char* GetCharWidthPrefix(char8_t) {
-  return "u8";
-}
+static const char* GetCharWidthPrefix(char8_t) { return "u8"; }
 #endif
 
-static const char* GetCharWidthPrefix(char16_t) {
-  return "u";
-}
+static const char* GetCharWidthPrefix(char16_t) { return "u"; }
 
-static const char* GetCharWidthPrefix(char32_t) {
-  return "U";
-}
+static const char* GetCharWidthPrefix(char32_t) { return "U"; }
 
-static const char* GetCharWidthPrefix(wchar_t) {
-  return "L";
-}
+static const char* GetCharWidthPrefix(wchar_t) { return "L"; }
 
 // Prints a char c as if it's part of a string literal, escaping it when
 // necessary; returns how c was formatted.
@@ -276,8 +257,7 @@ void PrintCharAndCodeTo(Char c, ostream* os) {
   // To aid user debugging, we also print c's code in decimal, unless
   // it's 0 (in which case c was printed as '\\0', making the code
   // obvious).
-  if (c == 0)
-    return;
+  if (c == 0) return;
   *os << " (" << static_cast<int>(c);
 
   // For more convenience, we print c's code again in hexadecimal,
@@ -304,17 +284,60 @@ void PrintTo(char32_t c, ::std::ostream* os) {
       << static_cast<uint32_t>(c);
 }
 
+// gcc/clang __{u,}int128_t
+#if defined(__SIZEOF_INT128__)
+void PrintTo(__uint128_t v, ::std::ostream* os) {
+  if (v == 0) {
+    *os << "0";
+    return;
+  }
+
+  // Buffer large enough for ceil(log10(2^128))==39 and the null terminator
+  char buf[40];
+  char* p = buf + sizeof(buf);
+
+  // Some configurations have a __uint128_t, but no support for built in
+  // division. Do manual long division instead.
+
+  uint64_t high = static_cast<uint64_t>(v >> 64);
+  uint64_t low = static_cast<uint64_t>(v);
+
+  *--p = 0;
+  while (high != 0 || low != 0) {
+    uint64_t high_mod = high % 10;
+    high = high / 10;
+    // This is the long division algorithm specialized for a divisor of 10 and
+    // only two elements.
+    // Notable values:
+    //   2^64 / 10 == 1844674407370955161
+    //   2^64 % 10 == 6
+    const uint64_t carry = 6 * high_mod + low % 10;
+    low = low / 10 + high_mod * 1844674407370955161 + carry / 10;
+
+    char digit = static_cast<char>(carry % 10);
+    *--p = '0' + digit;
+  }
+  *os << p;
+}
+void PrintTo(__int128_t v, ::std::ostream* os) {
+  __uint128_t uv = static_cast<__uint128_t>(v);
+  if (v < 0) {
+    *os << "-";
+    uv = -uv;
+  }
+  PrintTo(uv, os);
+}
+#endif  // __SIZEOF_INT128__
+
 // Prints the given array of characters to the ostream.  CharType must be either
 // char, char8_t, char16_t, char32_t, or wchar_t.
 // The array starts at begin, the length is len, it may include '\0' characters
 // and may not be NUL-terminated.
 template <typename CharType>
-GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
-GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
-GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
-GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
-static CharFormat PrintCharsAsStringTo(
-    const CharType* begin, size_t len, ostream* os) {
+GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
+    GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
+        GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static CharFormat
+        PrintCharsAsStringTo(const CharType* begin, size_t len, ostream* os) {
   const char* const quote_prefix = GetCharWidthPrefix(*begin);
   *os << quote_prefix << "\"";
   bool is_previous_hex = false;
@@ -340,12 +363,11 @@ static CharFormat PrintCharsAsStringTo(
 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
 // 'begin'.  CharType must be either char or wchar_t.
 template <typename CharType>
-GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
-GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
-GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
-GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
-static void UniversalPrintCharArray(
-    const CharType* begin, size_t len, ostream* os) {
+GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
+    GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
+        GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static void
+        UniversalPrintCharArray(const CharType* begin, size_t len,
+                                ostream* os) {
   // The code
   //   const char kFoo[] = "foo";
   // generates an array of 4, not 3, elements, with the last one being '\0'.
@@ -436,28 +458,28 @@ void PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); }
 namespace {
 
 bool ContainsUnprintableControlCodes(const char* str, size_t length) {
-  const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
+  const unsigned char* s = reinterpret_cast<const unsigned char*>(str);
 
   for (size_t i = 0; i < length; i++) {
     unsigned char ch = *s++;
     if (std::iscntrl(ch)) {
-        switch (ch) {
+      switch (ch) {
         case '\t':
         case '\n':
         case '\r':
           break;
         default:
           return true;
-        }
       }
+    }
   }
   return false;
 }
 
-bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }
+bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t <= 0xbf; }
 
 bool IsValidUTF8(const char* str, size_t length) {
-  const unsigned char *s = reinterpret_cast<const unsigned char *>(str);
+  const unsigned char* s = reinterpret_cast<const unsigned char*>(str);
 
   for (size_t i = 0; i < length;) {
     unsigned char lead = s[i++];
@@ -470,15 +492,13 @@ bool IsValidUTF8(const char* str, size_t length) {
     } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
       ++i;  // 2-byte character
     } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
-               IsUTF8TrailByte(s[i]) &&
-               IsUTF8TrailByte(s[i + 1]) &&
+               IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) &&
                // check for non-shortest form and surrogate
                (lead != 0xe0 || s[i] >= 0xa0) &&
                (lead != 0xed || s[i] < 0xa0)) {
       i += 2;  // 3-byte character
     } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
-               IsUTF8TrailByte(s[i]) &&
-               IsUTF8TrailByte(s[i + 1]) &&
+               IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) &&
                IsUTF8TrailByte(s[i + 2]) &&
                // check for non-shortest form
                (lead != 0xf0 || s[i] >= 0x90) &&
@@ -502,7 +522,7 @@ void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
 
 void PrintStringTo(const ::std::string& s, ostream* os) {
   if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
-    if (GTEST_FLAG(print_utf8)) {
+    if (GTEST_FLAG_GET(print_utf8)) {
       ConditionalPrintAsText(s.data(), s.size(), os);
     }
   }
index a938683ceded2f34697efd8305a67368064d0198..eb7c8d1cf9235390e1081c5d5f9acb886802f220 100644 (file)
@@ -51,13 +51,11 @@ std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
   return os << internal::FormatFileLocation(result.file_name(),
                                             result.line_number())
             << " "
-            << (result.type() == TestPartResult::kSuccess
-                    ? "Success"
-                    : result.type() == TestPartResult::kSkip
-                          ? "Skipped"
-                          : result.type() == TestPartResult::kFatalFailure
-                                ? "Fatal failure"
-                                : "Non-fatal failure")
+            << (result.type() == TestPartResult::kSuccess ? "Success"
+                : result.type() == TestPartResult::kSkip  ? "Skipped"
+                : result.type() == TestPartResult::kFatalFailure
+                    ? "Fatal failure"
+                    : "Non-fatal failure")
             << ":\n"
             << result.message() << std::endl;
 }
@@ -86,8 +84,8 @@ namespace internal {
 
 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
     : has_new_fatal_failure_(false),
-      original_reporter_(GetUnitTestImpl()->
-                         GetTestPartResultReporterForCurrentThread()) {
+      original_reporter_(
+          GetUnitTestImpl()->GetTestPartResultReporterForCurrentThread()) {
   GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
 }
 
@@ -98,8 +96,7 @@ HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
 
 void HasNewFatalFailureHelper::ReportTestPartResult(
     const TestPartResult& result) {
-  if (result.fatally_failed())
-    has_new_fatal_failure_ = true;
+  if (result.fatally_failed()) has_new_fatal_failure_ = true;
   original_reporter_->ReportTestPartResult(result);
 }
 
index c02c3df6599527af878d28f4aa2311a61a65c48a..a2828b83c66457d6082d55b05ac5ae596a9d1efc 100644 (file)
@@ -27,7 +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.
 
-
 #include "gtest/gtest-typed-test.h"
 
 #include "gtest/gtest.h"
@@ -38,8 +37,7 @@ namespace internal {
 // Skips to the first non-space char in str. Returns an empty string if str
 // contains only whitespace characters.
 static const char* SkipSpaces(const char* str) {
-  while (IsSpace(*str))
-    str++;
+  while (IsSpace(*str)) str++;
   return str;
 }
 
@@ -85,8 +83,7 @@ const char* TypedTestSuitePState::VerifyRegisteredTestNames(
   }
 
   for (RegisteredTestIter it = registered_tests_.begin();
-       it != registered_tests_.end();
-       ++it) {
+       it != registered_tests_.end(); ++it) {
     if (tests.count(it->first) == 0) {
       errors << "You forgot to list test " << it->first << ".\n";
     }
index 21c611aff124a87121a8086a66d2bb176064669d..6f31dd22603340a2006d3eb8755df5ea7d414733 100644 (file)
@@ -31,8 +31,6 @@
 // The Google C++ Testing and Mocking Framework (Google Test)
 
 #include "gtest/gtest.h"
-#include "gtest/internal/custom/gtest.h"
-#include "gtest/gtest-spi.h"
 
 #include <ctype.h>
 #include <stdarg.h>
 #include <chrono>  // NOLINT
 #include <cmath>
 #include <cstdint>
+#include <initializer_list>
 #include <iomanip>
+#include <iterator>
 #include <limits>
 #include <list>
 #include <map>
 #include <ostream>  // NOLINT
 #include <sstream>
+#include <unordered_set>
 #include <vector>
 
+#include "gtest/gtest-assertion-result.h"
+#include "gtest/gtest-spi.h"
+#include "gtest/internal/custom/gtest.h"
+
 #if GTEST_OS_LINUX
 
-# include <fcntl.h>  // NOLINT
-# include <limits.h>  // NOLINT
-# include <sched.h>  // NOLINT
+#include <fcntl.h>   // NOLINT
+#include <limits.h>  // NOLINT
+#include <sched.h>   // NOLINT
 // Declares vsnprintf().  This header is not available on Windows.
-# include <strings.h>  // NOLINT
-# include <sys/mman.h>  // NOLINT
-# include <sys/time.h>  // NOLINT
-# include <unistd.h>  // NOLINT
-# include <string>
+#include <strings.h>   // NOLINT
+#include <sys/mman.h>  // NOLINT
+#include <sys/time.h>  // NOLINT
+#include <unistd.h>    // NOLINT
+
+#include <string>
 
 #elif GTEST_OS_ZOS
-# include <sys/time.h>  // NOLINT
+#include <sys/time.h>  // NOLINT
 
 // On z/OS we additionally need strings.h for strcasecmp.
-# include <strings.h>  // NOLINT
+#include <strings.h>   // NOLINT
 
 #elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
 
-# include <windows.h>  // NOLINT
-# undef min
+#include <windows.h>  // NOLINT
+#undef min
 
 #elif GTEST_OS_WINDOWS  // We are on Windows proper.
 
-# include <windows.h>  // NOLINT
-# undef min
+#include <windows.h>  // NOLINT
+#undef min
 
 #ifdef _MSC_VER
-# include <crtdbg.h>  // NOLINT
+#include <crtdbg.h>  // NOLINT
 #endif
 
-# include <io.h>  // NOLINT
-# include <sys/timeb.h>  // NOLINT
-# include <sys/types.h>  // NOLINT
-# include <sys/stat.h>  // NOLINT
+#include <io.h>         // NOLINT
+#include <sys/stat.h>   // NOLINT
+#include <sys/timeb.h>  // NOLINT
+#include <sys/types.h>  // NOLINT
 
-# if GTEST_OS_WINDOWS_MINGW
-#  include <sys/time.h>  // NOLINT
-# endif  // GTEST_OS_WINDOWS_MINGW
+#if GTEST_OS_WINDOWS_MINGW
+#include <sys/time.h>  // NOLINT
+#endif                 // GTEST_OS_WINDOWS_MINGW
 
 #else
 
 // cpplint thinks that the header is already included, so we want to
 // silence it.
-# include <sys/time.h>  // NOLINT
-# include <unistd.h>  // NOLINT
+#include <sys/time.h>  // NOLINT
+#include <unistd.h>    // NOLINT
 
 #endif  // GTEST_OS_LINUX
 
 #if GTEST_HAS_EXCEPTIONS
-# include <stdexcept>
+#include <stdexcept>
 #endif
 
 #if GTEST_CAN_STREAM_RESULTS_
-# include <arpa/inet.h>  // NOLINT
-# include <netdb.h>  // NOLINT
-# include <sys/socket.h>  // NOLINT
-# include <sys/types.h>  // NOLINT
+#include <arpa/inet.h>   // NOLINT
+#include <netdb.h>       // NOLINT
+#include <sys/socket.h>  // NOLINT
+#include <sys/types.h>   // NOLINT
 #endif
 
 #include "src/gtest-internal-inl.h"
 
 #if GTEST_OS_WINDOWS
-# define vsnprintf _vsnprintf
+#define vsnprintf _vsnprintf
 #endif  // GTEST_OS_WINDOWS
 
 #if GTEST_OS_MAC
 #include "absl/debugging/failure_signal_handler.h"
 #include "absl/debugging/stacktrace.h"
 #include "absl/debugging/symbolize.h"
+#include "absl/flags/parse.h"
+#include "absl/flags/usage.h"
 #include "absl/strings/str_cat.h"
+#include "absl/strings/str_replace.h"
 #endif  // GTEST_HAS_ABSL
 
 namespace testing {
@@ -177,7 +186,7 @@ const char kStackTraceMarker[] = "\nStack trace:\n";
 // is specified on the command line.
 bool g_help_flag = false;
 
-// Utilty function to Open File for Writing
+// Utility function to Open File for Writing
 static FILE* OpenFileForWriting(const std::string& output_file) {
   FILE* fileout = nullptr;
   FilePath output_file_path(output_file);
@@ -216,28 +225,33 @@ static bool GetDefaultFailFast() {
   return false;
 }
 
+}  // namespace testing
+
 GTEST_DEFINE_bool_(
-    fail_fast, internal::BoolFromGTestEnv("fail_fast", GetDefaultFailFast()),
+    fail_fast,
+    testing::internal::BoolFromGTestEnv("fail_fast",
+                                        testing::GetDefaultFailFast()),
     "True if and only if a test failure should stop further test execution.");
 
 GTEST_DEFINE_bool_(
     also_run_disabled_tests,
-    internal::BoolFromGTestEnv("also_run_disabled_tests", false),
+    testing::internal::BoolFromGTestEnv("also_run_disabled_tests", false),
     "Run disabled tests too, in addition to the tests normally being run.");
 
 GTEST_DEFINE_bool_(
-    break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false),
+    break_on_failure,
+    testing::internal::BoolFromGTestEnv("break_on_failure", false),
     "True if and only if a failed assertion should be a debugger "
     "break-point.");
 
 GTEST_DEFINE_bool_(catch_exceptions,
-                   internal::BoolFromGTestEnv("catch_exceptions", true),
+                   testing::internal::BoolFromGTestEnv("catch_exceptions",
+                                                       true),
                    "True if and only if " GTEST_NAME_
                    " should catch exceptions and treat them as test failures.");
 
 GTEST_DEFINE_string_(
-    color,
-    internal::StringFromGTestEnv("color", "auto"),
+    color, testing::internal::StringFromGTestEnv("color", "auto"),
     "Whether to use colors in the output.  Valid values: yes, no, "
     "and auto.  'auto' means to use colors if the output is "
     "being sent to a terminal and the TERM environment variable "
@@ -245,7 +259,8 @@ GTEST_DEFINE_string_(
 
 GTEST_DEFINE_string_(
     filter,
-    internal::StringFromGTestEnv("filter", GetDefaultFilter()),
+    testing::internal::StringFromGTestEnv("filter",
+                                          testing::GetDefaultFilter()),
     "A colon-separated list of glob (not regex) patterns "
     "for filtering the tests to run, optionally followed by a "
     "'-' and a : separated list of negative patterns (tests to "
@@ -254,13 +269,14 @@ GTEST_DEFINE_string_(
 
 GTEST_DEFINE_bool_(
     install_failure_signal_handler,
-    internal::BoolFromGTestEnv("install_failure_signal_handler", false),
-    "If true and supported on the current platform, " GTEST_NAME_ " should "
+    testing::internal::BoolFromGTestEnv("install_failure_signal_handler",
+                                        false),
+    "If true and supported on the current platform, " GTEST_NAME_
+    " should "
     "install a signal handler that dumps debugging information when fatal "
     "signals are raised.");
 
-GTEST_DEFINE_bool_(list_tests, false,
-                   "List all tests without running them.");
+GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them.");
 
 // The net priority order after flag processing is thus:
 //   --gtest_output command line flag
@@ -269,8 +285,8 @@ GTEST_DEFINE_bool_(list_tests, false,
 //   ''
 GTEST_DEFINE_string_(
     output,
-    internal::StringFromGTestEnv("output",
-      internal::OutputFlagAlsoCheckEnvVar().c_str()),
+    testing::internal::StringFromGTestEnv(
+        "output", testing::internal::OutputFlagAlsoCheckEnvVar().c_str()),
     "A format (defaults to \"xml\" but can be specified to be \"json\"), "
     "optionally followed by a colon and an output file name or directory. "
     "A directory is indicated by a trailing pathname separator. "
@@ -281,65 +297,79 @@ GTEST_DEFINE_string_(
     "digits.");
 
 GTEST_DEFINE_bool_(
-    brief, internal::BoolFromGTestEnv("brief", false),
+    brief, testing::internal::BoolFromGTestEnv("brief", false),
     "True if only test failures should be displayed in text output.");
 
-GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true),
+GTEST_DEFINE_bool_(print_time,
+                   testing::internal::BoolFromGTestEnv("print_time", true),
                    "True if and only if " GTEST_NAME_
                    " should display elapsed time in text output.");
 
-GTEST_DEFINE_bool_(print_utf8, internal::BoolFromGTestEnv("print_utf8", true),
+GTEST_DEFINE_bool_(print_utf8,
+                   testing::internal::BoolFromGTestEnv("print_utf8", true),
                    "True if and only if " GTEST_NAME_
                    " prints UTF8 characters as text.");
 
 GTEST_DEFINE_int32_(
-    random_seed,
-    internal::Int32FromGTestEnv("random_seed", 0),
+    random_seed, testing::internal::Int32FromGTestEnv("random_seed", 0),
     "Random number seed to use when shuffling test orders.  Must be in range "
     "[1, 99999], or 0 to use a seed based on the current time.");
 
 GTEST_DEFINE_int32_(
-    repeat,
-    internal::Int32FromGTestEnv("repeat", 1),
+    repeat, testing::internal::Int32FromGTestEnv("repeat", 1),
     "How many times to repeat each test.  Specify a negative number "
     "for repeating forever.  Useful for shaking out flaky tests.");
 
+GTEST_DEFINE_bool_(
+    recreate_environments_when_repeating,
+    testing::internal::BoolFromGTestEnv("recreate_environments_when_repeating",
+                                        false),
+    "Controls whether global test environments are recreated for each repeat "
+    "of the tests. If set to false the global test environments are only set "
+    "up once, for the first iteration, and only torn down once, for the last. "
+    "Useful for shaking out flaky tests with stable, expensive test "
+    "environments. If --gtest_repeat is set to a negative number, meaning "
+    "there is no last run, the environments will always be recreated to avoid "
+    "leaks.");
+
 GTEST_DEFINE_bool_(show_internal_stack_frames, false,
                    "True if and only if " GTEST_NAME_
                    " should include internal stack frames when "
                    "printing test failure stack traces.");
 
-GTEST_DEFINE_bool_(shuffle, internal::BoolFromGTestEnv("shuffle", false),
+GTEST_DEFINE_bool_(shuffle,
+                   testing::internal::BoolFromGTestEnv("shuffle", false),
                    "True if and only if " GTEST_NAME_
                    " should randomize tests' order on every run.");
 
 GTEST_DEFINE_int32_(
     stack_trace_depth,
-    internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
+    testing::internal::Int32FromGTestEnv("stack_trace_depth",
+                                         testing::kMaxStackTraceDepth),
     "The maximum number of stack frames to print when an "
     "assertion fails.  The valid range is 0 through 100, inclusive.");
 
 GTEST_DEFINE_string_(
     stream_result_to,
-    internal::StringFromGTestEnv("stream_result_to", ""),
+    testing::internal::StringFromGTestEnv("stream_result_to", ""),
     "This flag specifies the host name and the port number on which to stream "
     "test results. Example: \"localhost:555\". The flag is effective only on "
     "Linux.");
 
 GTEST_DEFINE_bool_(
     throw_on_failure,
-    internal::BoolFromGTestEnv("throw_on_failure", false),
+    testing::internal::BoolFromGTestEnv("throw_on_failure", false),
     "When this flag is specified, a failed assertion will throw an exception "
     "if exceptions are enabled or exit the program with a non-zero code "
     "otherwise. For use with an external test framework.");
 
 #if GTEST_USE_OWN_FLAGFILE_FLAG_
 GTEST_DEFINE_string_(
-    flagfile,
-    internal::StringFromGTestEnv("flagfile", ""),
+    flagfile, testing::internal::StringFromGTestEnv("flagfile", ""),
     "This flag specifies the flagfile to read command-line flags from.");
 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
 
+namespace testing {
 namespace internal {
 
 // Generates a random number from [0, range), using a Linear
@@ -348,10 +378,9 @@ namespace internal {
 uint32_t Random::Generate(uint32_t range) {
   // These constants are the same as are used in glibc's rand(3).
   // Use wider types than necessary to prevent unsigned overflow diagnostics.
-  state_ = static_cast<uint32_t>(1103515245ULL*state_ + 12345U) % kMaxRange;
+  state_ = static_cast<uint32_t>(1103515245ULL * state_ + 12345U) % kMaxRange;
 
-  GTEST_CHECK_(range > 0)
-      << "Cannot generate a number in the range [0, 0).";
+  GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0).";
   GTEST_CHECK_(range <= kMaxRange)
       << "Generation of a number in [0, " << range << ") was requested, "
       << "but this can only generate numbers in [0, " << kMaxRange << ").";
@@ -396,32 +425,26 @@ static bool ShouldRunTestSuite(const TestSuite* test_suite) {
 }
 
 // AssertHelper constructor.
-AssertHelper::AssertHelper(TestPartResult::Type type,
-                           const char* file,
-                           int line,
-                           const char* message)
-    : data_(new AssertHelperData(type, file, line, message)) {
-}
+AssertHelper::AssertHelper(TestPartResult::Type type, const char* file,
+                           int line, const char* message)
+    : data_(new AssertHelperData(type, file, line, message)) {}
 
-AssertHelper::~AssertHelper() {
-  delete data_;
-}
+AssertHelper::~AssertHelper() { delete data_; }
 
 // Message assignment, for assertion streaming support.
 void AssertHelper::operator=(const Message& message) const {
-  UnitTest::GetInstance()->
-    AddTestPartResult(data_->type, data_->file, data_->line,
-                      AppendUserMessage(data_->message, message),
-                      UnitTest::GetInstance()->impl()
-                      ->CurrentOsStackTraceExceptTop(1)
-                      // Skips the stack frame for this function itself.
-                      );  // NOLINT
+  UnitTest::GetInstance()->AddTestPartResult(
+      data_->type, data_->file, data_->line,
+      AppendUserMessage(data_->message, message),
+      UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1)
+      // Skips the stack frame for this function itself.
+  );  // NOLINT
 }
 
 namespace {
 
 // When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P
-// to creates test cases for it, a syntetic test case is
+// to creates test cases for it, a synthetic test case is
 // inserted to report ether an error or a log message.
 //
 // This configuration bit will likely be removed at some point.
@@ -452,7 +475,6 @@ class FailureTest : public Test {
   const bool as_error_;
 };
 
-
 }  // namespace
 
 std::set<std::string>* GetIgnoredParameterizedTestSuites() {
@@ -496,7 +518,8 @@ void InsertSyntheticTestCase(const std::string& name, CodeLocation location,
       "To suppress this error for this test suite, insert the following line "
       "(in a non-header) in the namespace it is defined in:"
       "\n\n"
-      "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + name + ");";
+      "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
+      name + ");";
 
   std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">";
   RegisterTest(  //
@@ -516,19 +539,18 @@ void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
 }
 
 void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) {
-  GetUnitTestImpl()
-      ->type_parameterized_test_registry()
-      .RegisterInstantiation(case_name);
+  GetUnitTestImpl()->type_parameterized_test_registry().RegisterInstantiation(
+      case_name);
 }
 
 void TypeParameterizedTestSuiteRegistry::RegisterTestSuite(
     const char* test_suite_name, CodeLocation code_location) {
   suites_.emplace(std::string(test_suite_name),
-                 TypeParameterizedTestSuiteInfo(code_location));
+                  TypeParameterizedTestSuiteInfo(code_location));
 }
 
 void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
-        const char* test_suite_name) {
+    const char* test_suite_name) {
   auto it = suites_.find(std::string(test_suite_name));
   if (it != suites_.end()) {
     it->second.instantiated = true;
@@ -606,7 +628,8 @@ FilePath GetCurrentExecutableName() {
 
 // Returns the output format, or "" for normal printed output.
 std::string UnitTestOptions::GetOutputFormat() {
-  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
+  std::string s = GTEST_FLAG_GET(output);
+  const char* const gtest_output_flag = s.c_str();
   const char* const colon = strchr(gtest_output_flag, ':');
   return (colon == nullptr)
              ? std::string(gtest_output_flag)
@@ -617,19 +640,19 @@ std::string UnitTestOptions::GetOutputFormat() {
 // Returns the name of the requested output file, or the default if none
 // was explicitly specified.
 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
-  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
+  std::string s = GTEST_FLAG_GET(output);
+  const char* const gtest_output_flag = s.c_str();
 
   std::string format = GetOutputFormat();
-  if (format.empty())
-    format = std::string(kDefaultOutputFormat);
+  if (format.empty()) format = std::string(kDefaultOutputFormat);
 
   const char* const colon = strchr(gtest_output_flag, ':');
   if (colon == nullptr)
     return internal::FilePath::MakeFileName(
-        internal::FilePath(
-            UnitTest::GetInstance()->original_working_dir()),
-        internal::FilePath(kDefaultOutputFile), 0,
-        format.c_str()).string();
+               internal::FilePath(
+                   UnitTest::GetInstance()->original_working_dir()),
+               internal::FilePath(kDefaultOutputFile), 0, format.c_str())
+        .string();
 
   internal::FilePath output_name(colon + 1);
   if (!output_name.IsAbsolutePath())
@@ -637,8 +660,7 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
         internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
         internal::FilePath(colon + 1));
 
-  if (!output_name.IsDirectory())
-    return output_name.string();
+  if (!output_name.IsDirectory()) return output_name.string();
 
   internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
       output_name, internal::GetCurrentExecutableName(),
@@ -699,59 +721,119 @@ static bool PatternMatchesString(const std::string& name_str,
   return true;
 }
 
-bool UnitTestOptions::MatchesFilter(const std::string& name_str,
-                                    const char* filter) {
-  // The filter is a list of patterns separated by colons (:).
-  const char* pattern = filter;
-  while (true) {
-    // Find the bounds of this pattern.
-    const char* const next_sep = strchr(pattern, ':');
-    const char* const pattern_end =
-        next_sep != nullptr ? next_sep : pattern + strlen(pattern);
-
-    // Check if this pattern matches name_str.
-    if (PatternMatchesString(name_str, pattern, pattern_end)) {
-      return true;
-    }
+namespace {
+
+bool IsGlobPattern(const std::string& pattern) {
+  return std::any_of(pattern.begin(), pattern.end(),
+                     [](const char c) { return c == '?' || c == '*'; });
+}
+
+class UnitTestFilter {
+ public:
+  UnitTestFilter() = default;
+
+  // Constructs a filter from a string of patterns separated by `:`.
+  explicit UnitTestFilter(const std::string& filter) {
+    // By design "" filter matches "" string.
+    std::vector<std::string> all_patterns;
+    SplitString(filter, ':', &all_patterns);
+    const auto exact_match_patterns_begin = std::partition(
+        all_patterns.begin(), all_patterns.end(), &IsGlobPattern);
+
+    glob_patterns_.reserve(static_cast<size_t>(
+        std::distance(all_patterns.begin(), exact_match_patterns_begin)));
+    std::move(all_patterns.begin(), exact_match_patterns_begin,
+              std::inserter(glob_patterns_, glob_patterns_.begin()));
+    std::move(
+        exact_match_patterns_begin, all_patterns.end(),
+        std::inserter(exact_match_patterns_, exact_match_patterns_.begin()));
+  }
+
+  // Returns true if and only if name matches at least one of the patterns in
+  // the filter.
+  bool MatchesName(const std::string& name) const {
+    return exact_match_patterns_.count(name) > 0 ||
+           std::any_of(glob_patterns_.begin(), glob_patterns_.end(),
+                       [&name](const std::string& pattern) {
+                         return PatternMatchesString(
+                             name, pattern.c_str(),
+                             pattern.c_str() + pattern.size());
+                       });
+  }
+
+ private:
+  std::vector<std::string> glob_patterns_;
+  std::unordered_set<std::string> exact_match_patterns_;
+};
 
-    // Give up on this pattern. However, if we found a pattern separator (:),
-    // advance to the next pattern (skipping over the separator) and restart.
-    if (next_sep == nullptr) {
-      return false;
+class PositiveAndNegativeUnitTestFilter {
+ public:
+  // Constructs a positive and a negative filter from a string. The string
+  // contains a positive filter optionally followed by a '-' character and a
+  // negative filter. In case only a negative filter is provided the positive
+  // filter will be assumed "*".
+  // A filter is a list of patterns separated by ':'.
+  explicit PositiveAndNegativeUnitTestFilter(const std::string& filter) {
+    std::vector<std::string> positive_and_negative_filters;
+
+    // NOTE: `SplitString` always returns a non-empty container.
+    SplitString(filter, '-', &positive_and_negative_filters);
+    const auto& positive_filter = positive_and_negative_filters.front();
+
+    if (positive_and_negative_filters.size() > 1) {
+      positive_filter_ = UnitTestFilter(
+          positive_filter.empty() ? kUniversalFilter : positive_filter);
+
+      // TODO(b/214626361): Fail on multiple '-' characters
+      // For the moment to preserve old behavior we concatenate the rest of the
+      // string parts with `-` as separator to generate the negative filter.
+      auto negative_filter_string = positive_and_negative_filters[1];
+      for (std::size_t i = 2; i < positive_and_negative_filters.size(); i++)
+        negative_filter_string =
+            negative_filter_string + '-' + positive_and_negative_filters[i];
+      negative_filter_ = UnitTestFilter(negative_filter_string);
+    } else {
+      // In case we don't have a negative filter and positive filter is ""
+      // we do not use kUniversalFilter by design as opposed to when we have a
+      // negative filter.
+      positive_filter_ = UnitTestFilter(positive_filter);
     }
-    pattern = next_sep + 1;
   }
-  return true;
+
+  // Returns true if and only if test name (this is generated by appending test
+  // suit name and test name via a '.' character) matches the positive filter
+  // and does not match the negative filter.
+  bool MatchesTest(const std::string& test_suite_name,
+                   const std::string& test_name) const {
+    return MatchesName(test_suite_name + "." + test_name);
+  }
+
+  // Returns true if and only if name matches the positive filter and does not
+  // match the negative filter.
+  bool MatchesName(const std::string& name) const {
+    return positive_filter_.MatchesName(name) &&
+           !negative_filter_.MatchesName(name);
+  }
+
+ private:
+  UnitTestFilter positive_filter_;
+  UnitTestFilter negative_filter_;
+};
+}  // namespace
+
+bool UnitTestOptions::MatchesFilter(const std::string& name_str,
+                                    const char* filter) {
+  return UnitTestFilter(filter).MatchesName(name_str);
 }
 
 // Returns true if and only if the user-specified filter matches the test
 // suite name and the test name.
 bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,
                                         const std::string& test_name) {
-  const std::string& full_name = test_suite_name + "." + test_name.c_str();
-
   // Split --gtest_filter at '-', if there is one, to separate into
   // positive filter and negative filter portions
-  const char* const p = GTEST_FLAG(filter).c_str();
-  const char* const dash = strchr(p, '-');
-  std::string positive;
-  std::string negative;
-  if (dash == nullptr) {
-    positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
-    negative = "";
-  } else {
-    positive = std::string(p, dash);   // Everything up to the dash
-    negative = std::string(dash + 1);  // Everything after the dash
-    if (positive.empty()) {
-      // Treat '-test1' as the same as '*-test1'
-      positive = kUniversalFilter;
-    }
-  }
-
-  // A filter is a colon-separated list of patterns.  It matches a
-  // test if any pattern in it matches the test.
-  return (MatchesFilter(full_name, positive.c_str()) &&
-          !MatchesFilter(full_name, negative.c_str()));
+  return PositiveAndNegativeUnitTestFilter(GTEST_FLAG_GET(filter))
+      .MatchesTest(test_suite_name, test_name);
 }
 
 #if GTEST_HAS_SEH
@@ -771,7 +853,7 @@ int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
 
   bool should_handle = true;
 
-  if (!GTEST_FLAG(catch_exceptions))
+  if (!GTEST_FLAG_GET(catch_exceptions))
     should_handle = false;
   else if (exception_code == EXCEPTION_BREAKPOINT)
     should_handle = false;
@@ -789,8 +871,7 @@ int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
 // results. Intercepts only failures from the current thread.
 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
     TestPartResultArray* result)
-    : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
-      result_(result) {
+    : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) {
   Init();
 }
 
@@ -799,8 +880,7 @@ ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
 // results.
 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
     InterceptMode intercept_mode, TestPartResultArray* result)
-    : intercept_mode_(intercept_mode),
-      result_(result) {
+    : intercept_mode_(intercept_mode), result_(result) {
   Init();
 }
 
@@ -844,9 +924,7 @@ namespace internal {
 // from user test code.  GetTestTypeId() is guaranteed to always
 // return the same value, as it always calls GetTypeId<>() from the
 // gtest.cc, which is within the Google Test framework.
-TypeId GetTestTypeId() {
-  return GetTypeId<Test>();
-}
+TypeId GetTestTypeId() { return GetTypeId<Test>(); }
 
 // The value of GetTestTypeId() as seen from within the Google Test
 // library.  This is solely for testing GetTestTypeId().
@@ -861,9 +939,9 @@ static AssertionResult HasOneFailure(const char* /* results_expr */,
                                      const TestPartResultArray& results,
                                      TestPartResult::Type type,
                                      const std::string& substr) {
-  const std::string expected(type == TestPartResult::kFatalFailure ?
-                        "1 fatal failure" :
-                        "1 non-fatal failure");
+  const std::string expected(type == TestPartResult::kFatalFailure
+                                 ? "1 fatal failure"
+                                 : "1 non-fatal failure");
   Message msg;
   if (results.size() != 1) {
     msg << "Expected: " << expected << "\n"
@@ -882,10 +960,10 @@ static AssertionResult HasOneFailure(const char* /* results_expr */,
   }
 
   if (strstr(r.message(), substr.c_str()) == nullptr) {
-    return AssertionFailure() << "Expected: " << expected << " containing \""
-                              << substr << "\"\n"
-                              << "  Actual:\n"
-                              << r;
+    return AssertionFailure()
+           << "Expected: " << expected << " containing \"" << substr << "\"\n"
+           << "  Actual:\n"
+           << r;
   }
 
   return AssertionSuccess();
@@ -908,7 +986,8 @@ SingleFailureChecker::~SingleFailureChecker() {
 }
 
 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
-    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
+    UnitTestImpl* unit_test)
+    : unit_test_(unit_test) {}
 
 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
     const TestPartResult& result) {
@@ -917,7 +996,8 @@ void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
 }
 
 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
-    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
+    UnitTestImpl* unit_test)
+    : unit_test_(unit_test) {}
 
 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
     const TestPartResult& result) {
@@ -1024,11 +1104,10 @@ int UnitTestImpl::test_to_run_count() const {
 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
   return os_stack_trace_getter()->CurrentStackTrace(
-      static_cast<int>(GTEST_FLAG(stack_trace_depth)),
-      skip_count + 1
+      static_cast<int>(GTEST_FLAG_GET(stack_trace_depth)), skip_count + 1
       // Skips the user-specified number of frames plus this function
       // itself.
-      );  // NOLINT
+  );  // NOLINT
 }
 
 // A helper class for measuring elapsed times.
@@ -1072,8 +1151,7 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) {
   const int unicode_length =
       MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
   WCHAR* unicode = new WCHAR[unicode_length + 1];
-  MultiByteToWideChar(CP_ACP, 0, ansi, length,
-                      unicode, unicode_length);
+  MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length);
   unicode[unicode_length] = 0;
   return unicode;
 }
@@ -1082,7 +1160,7 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) {
 // memory using new. The caller is responsible for deleting the return
 // value using delete[]. Returns the ANSI string, or NULL if the
 // input is NULL.
-const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
+const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
   if (!utf16_str) return nullptr;
   const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
                                               0, nullptr, nullptr);
@@ -1101,7 +1179,7 @@ const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
 // Unlike strcmp(), this function can handle NULL argument(s).  A NULL
 // C string is considered different to any non-NULL C string,
 // including the empty string.
-bool String::CStringEquals(const char * lhs, const char * rhs) {
+bool String::CStringEquals(const char* lhs, const char* rhs) {
   if (lhs == nullptr) return rhs == nullptr;
 
   if (rhs == nullptr) return false;
@@ -1115,11 +1193,10 @@ bool String::CStringEquals(const char * lhs, const char * rhs) {
 // encoding, and streams the result to the given Message object.
 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
                                      Message* msg) {
-  for (size_t i = 0; i != length; ) {  // NOLINT
+  for (size_t i = 0; i != length;) {  // NOLINT
     if (wstr[i] != L'\0') {
       *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
-      while (i != length && wstr[i] != L'\0')
-        i++;
+      while (i != length && wstr[i] != L'\0') i++;
     } else {
       *msg << '\0';
       i++;
@@ -1161,17 +1238,17 @@ Message::Message() : ss_(new ::std::stringstream) {
 
 // These two overloads allow streaming a wide C string to a Message
 // using the UTF-8 encoding.
-Message& Message::operator <<(const wchar_t* wide_c_str) {
+Message& Message::operator<<(const wchar_t* wide_c_str) {
   return *this << internal::String::ShowWideCString(wide_c_str);
 }
-Message& Message::operator <<(wchar_t* wide_c_str) {
+Message& Message::operator<<(wchar_t* wide_c_str) {
   return *this << internal::String::ShowWideCString(wide_c_str);
 }
 
 #if GTEST_HAS_STD_WSTRING
 // Converts the given wide string to a narrow string using the UTF-8
 // encoding, and streams the result to this Message object.
-Message& Message::operator <<(const ::std::wstring& wstr) {
+Message& Message::operator<<(const ::std::wstring& wstr) {
   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
   return *this;
 }
@@ -1183,44 +1260,6 @@ std::string Message::GetString() const {
   return internal::StringStreamToString(ss_.get());
 }
 
-// AssertionResult constructors.
-// Used in EXPECT_TRUE/FALSE(assertion_result).
-AssertionResult::AssertionResult(const AssertionResult& other)
-    : success_(other.success_),
-      message_(other.message_.get() != nullptr
-                   ? new ::std::string(*other.message_)
-                   : static_cast< ::std::string*>(nullptr)) {}
-
-// Swaps two AssertionResults.
-void AssertionResult::swap(AssertionResult& other) {
-  using std::swap;
-  swap(success_, other.success_);
-  swap(message_, other.message_);
-}
-
-// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
-AssertionResult AssertionResult::operator!() const {
-  AssertionResult negation(!success_);
-  if (message_.get() != nullptr) negation << *message_;
-  return negation;
-}
-
-// Makes a successful assertion result.
-AssertionResult AssertionSuccess() {
-  return AssertionResult(true);
-}
-
-// Makes a failed assertion result.
-AssertionResult AssertionFailure() {
-  return AssertionResult(false);
-}
-
-// Makes a failed assertion result with the given failure message.
-// Deprecated; use AssertionFailure() << message.
-AssertionResult AssertionFailure(const Message& message) {
-  return AssertionFailure() << message;
-}
-
 namespace internal {
 
 namespace edit_distance {
@@ -1512,8 +1551,7 @@ std::vector<std::string> SplitEscapedString(const std::string& str) {
 AssertionResult EqFailure(const char* lhs_expression,
                           const char* rhs_expression,
                           const std::string& lhs_value,
-                          const std::string& rhs_value,
-                          bool ignoring_case) {
+                          const std::string& rhs_value, bool ignoring_case) {
   Message msg;
   msg << "Expected equality of these values:";
   msg << "\n  " << lhs_expression;
@@ -1530,10 +1568,8 @@ AssertionResult EqFailure(const char* lhs_expression,
   }
 
   if (!lhs_value.empty() && !rhs_value.empty()) {
-    const std::vector<std::string> lhs_lines =
-        SplitEscapedString(lhs_value);
-    const std::vector<std::string> rhs_lines =
-        SplitEscapedString(rhs_value);
+    const std::vector<std::string> lhs_lines = SplitEscapedString(lhs_value);
+    const std::vector<std::string> rhs_lines = SplitEscapedString(rhs_value);
     if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
       msg << "\nWith diff:\n"
           << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
@@ -1545,27 +1581,21 @@ AssertionResult EqFailure(const char* lhs_expression,
 
 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
 std::string GetBoolAssertionFailureMessage(
-    const AssertionResult& assertion_result,
-    const char* expression_text,
-    const char* actual_predicate_value,
-    const char* expected_predicate_value) {
+    const AssertionResult& assertion_result, const char* expression_text,
+    const char* actual_predicate_value, const char* expected_predicate_value) {
   const char* actual_message = assertion_result.message();
   Message msg;
   msg << "Value of: " << expression_text
       << "\n  Actual: " << actual_predicate_value;
-  if (actual_message[0] != '\0')
-    msg << " (" << actual_message << ")";
+  if (actual_message[0] != '\0') msg << " (" << actual_message << ")";
   msg << "\nExpected: " << expected_predicate_value;
   return msg.GetString();
 }
 
 // Helper function for implementing ASSERT_NEAR.
-AssertionResult DoubleNearPredFormat(const char* expr1,
-                                     const char* expr2,
-                                     const char* abs_error_expr,
-                                     double val1,
-                                     double val2,
-                                     double abs_error) {
+AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2,
+                                     const char* abs_error_expr, double val1,
+                                     double val2, double abs_error) {
   const double diff = fabs(val1 - val2);
   if (diff <= abs_error) return AssertionSuccess();
 
@@ -1595,20 +1625,17 @@ AssertionResult DoubleNearPredFormat(const char* expr1,
               "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
   }
   return AssertionFailure()
-      << "The difference between " << expr1 << " and " << expr2
-      << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
-      << expr1 << " evaluates to " << val1 << ",\n"
-      << expr2 << " evaluates to " << val2 << ", and\n"
-      << abs_error_expr << " evaluates to " << abs_error << ".";
+         << "The difference between " << expr1 << " and " << expr2 << " is "
+         << diff << ", which exceeds " << abs_error_expr << ", where\n"
+         << expr1 << " evaluates to " << val1 << ",\n"
+         << expr2 << " evaluates to " << val2 << ", and\n"
+         << abs_error_expr << " evaluates to " << abs_error << ".";
 }
 
-
 // Helper template for implementing FloatLE() and DoubleLE().
 template <typename RawType>
-AssertionResult FloatingPointLE(const char* expr1,
-                                const char* expr2,
-                                RawType val1,
-                                RawType val2) {
+AssertionResult FloatingPointLE(const char* expr1, const char* expr2,
+                                RawType val1, RawType val2) {
   // Returns success if val1 is less than val2,
   if (val1 < val2) {
     return AssertionSuccess();
@@ -1633,24 +1660,24 @@ AssertionResult FloatingPointLE(const char* expr1,
           << val2;
 
   return AssertionFailure()
-      << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
-      << "  Actual: " << StringStreamToString(&val1_ss) << " vs "
-      << StringStreamToString(&val2_ss);
+         << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
+         << "  Actual: " << StringStreamToString(&val1_ss) << " vs "
+         << StringStreamToString(&val2_ss);
 }
 
 }  // namespace internal
 
 // Asserts that val1 is less than, or almost equal to, val2.  Fails
 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
-AssertionResult FloatLE(const char* expr1, const char* expr2,
-                        float val1, float val2) {
+AssertionResult FloatLE(const char* expr1, const char* expr2, float val1,
+                        float val2) {
   return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
 }
 
 // Asserts that val1 is less than, or almost equal to, val2.  Fails
 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
-AssertionResult DoubleLE(const char* expr1, const char* expr2,
-                         double val1, double val2) {
+AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1,
+                         double val2) {
   return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
 }
 
@@ -1658,62 +1685,51 @@ namespace internal {
 
 // The helper function for {ASSERT|EXPECT}_STREQ.
 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
-                               const char* rhs_expression,
-                               const char* lhs,
+                               const char* rhs_expression, const char* lhs,
                                const char* rhs) {
   if (String::CStringEquals(lhs, rhs)) {
     return AssertionSuccess();
   }
 
-  return EqFailure(lhs_expression,
-                   rhs_expression,
-                   PrintToString(lhs),
-                   PrintToString(rhs),
-                   false);
+  return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
+                   PrintToString(rhs), false);
 }
 
 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
 AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
-                                   const char* rhs_expression,
-                                   const char* lhs,
+                                   const char* rhs_expression, const char* lhs,
                                    const char* rhs) {
   if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
     return AssertionSuccess();
   }
 
-  return EqFailure(lhs_expression,
-                   rhs_expression,
-                   PrintToString(lhs),
-                   PrintToString(rhs),
-                   true);
+  return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
+                   PrintToString(rhs), true);
 }
 
 // The helper function for {ASSERT|EXPECT}_STRNE.
 AssertionResult CmpHelperSTRNE(const char* s1_expression,
-                               const char* s2_expression,
-                               const char* s1,
+                               const char* s2_expression, const char* s1,
                                const char* s2) {
   if (!String::CStringEquals(s1, s2)) {
     return AssertionSuccess();
   } else {
-    return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
-                              << s2_expression << "), actual: \""
-                              << s1 << "\" vs \"" << s2 << "\"";
+    return AssertionFailure()
+           << "Expected: (" << s1_expression << ") != (" << s2_expression
+           << "), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
   }
 }
 
 // The helper function for {ASSERT|EXPECT}_STRCASENE.
 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
-                                   const char* s2_expression,
-                                   const char* s1,
+                                   const char* s2_expression, const char* s1,
                                    const char* s2) {
   if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
     return AssertionSuccess();
   } else {
     return AssertionFailure()
-        << "Expected: (" << s1_expression << ") != ("
-        << s2_expression << ") (ignoring case), actual: \""
-        << s1 << "\" vs \"" << s2 << "\"";
+           << "Expected: (" << s1_expression << ") != (" << s2_expression
+           << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
   }
 }
 
@@ -1741,8 +1757,7 @@ bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
 
 // StringType here can be either ::std::string or ::std::wstring.
 template <typename StringType>
-bool IsSubstringPred(const StringType& needle,
-                     const StringType& haystack) {
+bool IsSubstringPred(const StringType& needle, const StringType& haystack) {
   return haystack.find(needle) != StringType::npos;
 }
 
@@ -1751,21 +1766,22 @@ bool IsSubstringPred(const StringType& needle,
 // StringType here can be const char*, const wchar_t*, ::std::string,
 // or ::std::wstring.
 template <typename StringType>
-AssertionResult IsSubstringImpl(
-    bool expected_to_be_substring,
-    const char* needle_expr, const char* haystack_expr,
-    const StringType& needle, const StringType& haystack) {
+AssertionResult IsSubstringImpl(bool expected_to_be_substring,
+                                const char* needle_expr,
+                                const char* haystack_expr,
+                                const StringType& needle,
+                                const StringType& haystack) {
   if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
     return AssertionSuccess();
 
   const bool is_wide_string = sizeof(needle[0]) > 1;
   const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
   return AssertionFailure()
-      << "Value of: " << needle_expr << "\n"
-      << "  Actual: " << begin_string_quote << needle << "\"\n"
-      << "Expected: " << (expected_to_be_substring ? "" : "not ")
-      << "a substring of " << haystack_expr << "\n"
-      << "Which is: " << begin_string_quote << haystack << "\"";
+         << "Value of: " << needle_expr << "\n"
+         << "  Actual: " << begin_string_quote << needle << "\"\n"
+         << "Expected: " << (expected_to_be_substring ? "" : "not ")
+         << "a substring of " << haystack_expr << "\n"
+         << "Which is: " << begin_string_quote << haystack << "\"";
 }
 
 }  // namespace
@@ -1774,52 +1790,52 @@ AssertionResult IsSubstringImpl(
 // substring of haystack (NULL is considered a substring of itself
 // only), and return an appropriate error message when they fail.
 
-AssertionResult IsSubstring(
-    const char* needle_expr, const char* haystack_expr,
-    const char* needle, const char* haystack) {
+AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
+                            const char* needle, const char* haystack) {
   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
 }
 
-AssertionResult IsSubstring(
-    const char* needle_expr, const char* haystack_expr,
-    const wchar_t* needle, const wchar_t* haystack) {
+AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
+                            const wchar_t* needle, const wchar_t* haystack) {
   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
 }
 
-AssertionResult IsNotSubstring(
-    const char* needle_expr, const char* haystack_expr,
-    const char* needle, const char* haystack) {
+AssertionResult IsNotSubstring(const char* needle_expr,
+                               const char* haystack_expr, const char* needle,
+                               const char* haystack) {
   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
 }
 
-AssertionResult IsNotSubstring(
-    const char* needle_expr, const char* haystack_expr,
-    const wchar_t* needle, const wchar_t* haystack) {
+AssertionResult IsNotSubstring(const char* needle_expr,
+                               const char* haystack_expr, const wchar_t* needle,
+                               const wchar_t* haystack) {
   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
 }
 
-AssertionResult IsSubstring(
-    const char* needle_expr, const char* haystack_expr,
-    const ::std::string& needle, const ::std::string& haystack) {
+AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
+                            const ::std::string& needle,
+                            const ::std::string& haystack) {
   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
 }
 
-AssertionResult IsNotSubstring(
-    const char* needle_expr, const char* haystack_expr,
-    const ::std::string& needle, const ::std::string& haystack) {
+AssertionResult IsNotSubstring(const char* needle_expr,
+                               const char* haystack_expr,
+                               const ::std::string& needle,
+                               const ::std::string& haystack) {
   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
 }
 
 #if GTEST_HAS_STD_WSTRING
-AssertionResult IsSubstring(
-    const char* needle_expr, const char* haystack_expr,
-    const ::std::wstring& needle, const ::std::wstring& haystack) {
+AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
+                            const ::std::wstring& needle,
+                            const ::std::wstring& haystack) {
   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
 }
 
-AssertionResult IsNotSubstring(
-    const char* needle_expr, const char* haystack_expr,
-    const ::std::wstring& needle, const ::std::wstring& haystack) {
+AssertionResult IsNotSubstring(const char* needle_expr,
+                               const char* haystack_expr,
+                               const ::std::wstring& needle,
+                               const ::std::wstring& haystack) {
   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
 }
 #endif  // GTEST_HAS_STD_WSTRING
@@ -1831,43 +1847,42 @@ namespace internal {
 namespace {
 
 // Helper function for IsHRESULT{SuccessFailure} predicates
-AssertionResult HRESULTFailureHelper(const char* expr,
-                                     const char* expected,
+AssertionResult HRESULTFailureHelper(const char* expr, const char* expected,
                                      long hr) {  // NOLINT
-# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
+#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE
 
   // Windows CE doesn't support FormatMessage.
   const char error_text[] = "";
 
-# else
+#else
 
   // Looks up the human-readable system message for the HRESULT code
   // and since we're not passing any params to FormatMessage, we don't
   // want inserts expanded.
-  const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
-                       FORMAT_MESSAGE_IGNORE_INSERTS;
+  const DWORD kFlags =
+      FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
   const DWORD kBufSize = 4096;
   // Gets the system's human readable message string for this HRESULT.
-  char error_text[kBufSize] = { '\0' };
+  char error_text[kBufSize] = {'\0'};
   DWORD message_length = ::FormatMessageA(kFlags,
-                                          0,   // no source, we're asking system
+                                          0,  // no source, we're asking system
                                           static_cast<DWORD>(hr),  // the error
-                                          0,   // no line width restrictions
+                                          0,  // no line width restrictions
                                           error_text,  // output buffer
                                           kBufSize,    // buf size
                                           nullptr);  // no arguments for inserts
   // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
   for (; message_length && IsSpace(error_text[message_length - 1]);
-          --message_length) {
+       --message_length) {
     error_text[message_length - 1] = '\0';
   }
 
-# endif  // GTEST_OS_WINDOWS_MOBILE
+#endif  // GTEST_OS_WINDOWS_MOBILE
 
   const std::string error_hex("0x" + String::FormatHexInt(hr));
   return ::testing::AssertionFailure()
-      << "Expected: " << expr << " " << expected << ".\n"
-      << "  Actual: " << error_hex << " " << error_text << "\n";
+         << "Expected: " << expr << " " << expected << ".\n"
+         << "  Actual: " << error_hex << " " << error_text << "\n";
 }
 
 }  // namespace
@@ -1901,16 +1916,18 @@ AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
 //  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
 
 // The maximum code-point a one-byte UTF-8 sequence can represent.
-constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) <<  7) - 1;
+constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) << 7) - 1;
 
 // The maximum code-point a two-byte UTF-8 sequence can represent.
 constexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1;
 
 // The maximum code-point a three-byte UTF-8 sequence can represent.
-constexpr uint32_t kMaxCodePoint3 = (static_cast<uint32_t>(1) << (4 + 2*6)) - 1;
+constexpr uint32_t kMaxCodePoint3 =
+    (static_cast<uint32_t>(1) << (4 + 2 * 6)) - 1;
 
 // The maximum code-point a four-byte UTF-8 sequence can represent.
-constexpr uint32_t kMaxCodePoint4 = (static_cast<uint32_t>(1) << (3 + 3*6)) - 1;
+constexpr uint32_t kMaxCodePoint4 =
+    (static_cast<uint32_t>(1) << (3 + 3 * 6)) - 1;
 
 // Chops off the n lowest bits from a bit pattern.  Returns the n
 // lowest bits.  As a side effect, the original bit pattern will be
@@ -1935,7 +1952,7 @@ std::string CodePointToUtf8(uint32_t code_point) {
   char str[5];  // Big enough for the largest valid code point.
   if (code_point <= kMaxCodePoint1) {
     str[1] = '\0';
-    str[0] = static_cast<char>(code_point);                          // 0xxxxxxx
+    str[0] = static_cast<char>(code_point);  // 0xxxxxxx
   } else if (code_point <= kMaxCodePoint2) {
     str[2] = '\0';
     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
@@ -1963,8 +1980,8 @@ std::string CodePointToUtf8(uint32_t code_point) {
 // and thus should be combined into a single Unicode code point
 // using CreateCodePointFromUtf16SurrogatePair.
 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
-  return sizeof(wchar_t) == 2 &&
-      (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
+  return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 &&
+         (second & 0xFC00) == 0xDC00;
 }
 
 // Creates a Unicode code point from UTF16 surrogate pair.
@@ -1995,8 +2012,7 @@ inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first,
 // and contains invalid UTF-16 surrogate pairs, values in those pairs
 // will be encoded as individual Unicode characters from Basic Normal Plane.
 std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
-  if (num_chars == -1)
-    num_chars = static_cast<int>(wcslen(str));
+  if (num_chars == -1) num_chars = static_cast<int>(wcslen(str));
 
   ::std::stringstream stream;
   for (int i = 0; i < num_chars; ++i) {
@@ -2005,8 +2021,8 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
     if (str[i] == L'\0') {
       break;
     } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
-      unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
-                                                                 str[i + 1]);
+      unicode_code_point =
+          CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]);
       i++;
     } else {
       unicode_code_point = static_cast<uint32_t>(str[i]);
@@ -2019,7 +2035,7 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
 
 // Converts a wide C string to an std::string using the UTF-8 encoding.
 // NULL will be converted to "(null)".
-std::string String::ShowWideCString(const wchar_t * wide_c_str) {
+std::string String::ShowWideCString(const wchar_t* wide_c_str) {
   if (wide_c_str == nullptr) return "(null)";
 
   return internal::WideStringToUtf8(wide_c_str, -1);
@@ -2031,7 +2047,7 @@ std::string String::ShowWideCString(const wchar_t * wide_c_str) {
 // Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
 // C string is considered different to any non-NULL C string,
 // including the empty string.
-bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
+bool String::WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) {
   if (lhs == nullptr) return rhs == nullptr;
 
   if (rhs == nullptr) return false;
@@ -2041,33 +2057,27 @@ bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
 
 // Helper function for *_STREQ on wide strings.
 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
-                               const char* rhs_expression,
-                               const wchar_t* lhs,
+                               const char* rhs_expression, const wchar_t* lhs,
                                const wchar_t* rhs) {
   if (String::WideCStringEquals(lhs, rhs)) {
     return AssertionSuccess();
   }
 
-  return EqFailure(lhs_expression,
-                   rhs_expression,
-                   PrintToString(lhs),
-                   PrintToString(rhs),
-                   false);
+  return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),
+                   PrintToString(rhs), false);
 }
 
 // Helper function for *_STRNE on wide strings.
 AssertionResult CmpHelperSTRNE(const char* s1_expression,
-                               const char* s2_expression,
-                               const wchar_t* s1,
+                               const char* s2_expression, const wchar_t* s1,
                                const wchar_t* s2) {
   if (!String::WideCStringEquals(s1, s2)) {
     return AssertionSuccess();
   }
 
-  return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
-                            << s2_expression << "), actual: "
-                            << PrintToString(s1)
-                            << " vs " << PrintToString(s2);
+  return AssertionFailure()
+         << "Expected: (" << s1_expression << ") != (" << s2_expression
+         << "), actual: " << PrintToString(s1) << " vs " << PrintToString(s2);
 }
 
 // Compares two C strings, ignoring case.  Returns true if and only if they have
@@ -2076,7 +2086,7 @@ AssertionResult CmpHelperSTRNE(const char* s1_expression,
 // Unlike strcasecmp(), this function can handle NULL argument(s).  A
 // NULL C string is considered different to any non-NULL C string,
 // including the empty string.
-bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
+bool String::CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
   if (lhs == nullptr) return rhs == nullptr;
   if (rhs == nullptr) return false;
   return posix::StrCaseCmp(lhs, rhs) == 0;
@@ -2118,8 +2128,8 @@ bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
 
 // Returns true if and only if str ends with the given suffix, ignoring case.
 // Any string is considered to end with an empty suffix.
-bool String::EndsWithCaseInsensitive(
-    const std::string& str, const std::string& suffix) {
+bool String::EndsWithCaseInsensitive(const std::string& str,
+                                     const std::string& suffix) {
   const size_t str_len = str.length();
   const size_t suffix_len = suffix.length();
   return (str_len >= suffix_len) &&
@@ -2202,15 +2212,13 @@ TestResult::TestResult()
     : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}
 
 // D'tor.
-TestResult::~TestResult() {
-}
+TestResult::~TestResult() {}
 
 // Returns the i-th test part result among all the results. i can
 // range from 0 to total_part_count() - 1. If i is not in that range,
 // aborts the program.
 const TestPartResult& TestResult::GetTestPartResult(int i) const {
-  if (i < 0 || i >= total_part_count())
-    internal::posix::Abort();
+  if (i < 0 || i >= total_part_count()) internal::posix::Abort();
   return test_part_results_.at(static_cast<size_t>(i));
 }
 
@@ -2218,15 +2226,12 @@ const TestPartResult& TestResult::GetTestPartResult(int i) const {
 // test_property_count() - 1. If i is not in that range, aborts the
 // program.
 const TestProperty& TestResult::GetTestProperty(int i) const {
-  if (i < 0 || i >= test_property_count())
-    internal::posix::Abort();
+  if (i < 0 || i >= test_property_count()) internal::posix::Abort();
   return test_properties_.at(static_cast<size_t>(i));
 }
 
 // Clears the test part results.
-void TestResult::ClearTestPartResults() {
-  test_part_results_.clear();
-}
+void TestResult::ClearTestPartResults() { test_part_results_.clear(); }
 
 // Adds a test part result to the list.
 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
@@ -2255,15 +2260,8 @@ void TestResult::RecordProperty(const std::string& xml_element,
 // The list of reserved attributes used in the <testsuites> element of XML
 // output.
 static const char* const kReservedTestSuitesAttributes[] = {
-  "disabled",
-  "errors",
-  "failures",
-  "name",
-  "random_seed",
-  "tests",
-  "time",
-  "timestamp"
-};
+    "disabled",    "errors", "failures", "name",
+    "random_seed", "tests",  "time",     "timestamp"};
 
 // The list of reserved attributes used in the <testsuite> element of XML
 // output.
@@ -2273,8 +2271,8 @@ static const char* const kReservedTestSuiteAttributes[] = {
 
 // The list of reserved attributes used in the <testcase> element of XML output.
 static const char* const kReservedTestCaseAttributes[] = {
-    "classname",   "name", "status", "time",  "type_param",
-    "value_param", "file", "line"};
+    "classname",  "name",        "status", "time",
+    "type_param", "value_param", "file",   "line"};
 
 // Use a slightly different set for allowed output to ensure existing tests can
 // still RecordProperty("result") or "RecordProperty(timestamp")
@@ -2336,7 +2334,7 @@ static bool ValidateTestPropertyName(
     const std::string& property_name,
     const std::vector<std::string>& reserved_names) {
   if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
-          reserved_names.end()) {
+      reserved_names.end()) {
     ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
                   << " (" << FormatWordList(reserved_names)
                   << " are reserved by " << GTEST_NAME_ << ")";
@@ -2374,8 +2372,7 @@ bool TestResult::Skipped() const {
 // Returns true if and only if the test failed.
 bool TestResult::Failed() const {
   for (int i = 0; i < total_part_count(); ++i) {
-    if (GetTestPartResult(i).failed())
-      return true;
+    if (GetTestPartResult(i).failed()) return true;
   }
   return false;
 }
@@ -2416,27 +2413,22 @@ int TestResult::test_property_count() const {
 // Creates a Test object.
 
 // The c'tor saves the states of all flags.
-Test::Test()
-    : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
-}
+Test::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {}
 
 // The d'tor restores the states of all flags.  The actual work is
 // done by the d'tor of the gtest_flag_saver_ field, and thus not
 // visible here.
-Test::~Test() {
-}
+Test::~Test() {}
 
 // Sets up the test fixture.
 //
 // A sub-class may override this.
-void Test::SetUp() {
-}
+void Test::SetUp() {}
 
 // Tears down the test fixture.
 //
 // A sub-class may override this.
-void Test::TearDown() {
-}
+void Test::TearDown() {}
 
 // Allows user supplied key value pairs to be recorded for later output.
 void Test::RecordProperty(const std::string& key, const std::string& value) {
@@ -2541,8 +2533,8 @@ bool Test::HasSameFixtureClass() {
 static std::string* FormatSehExceptionMessage(DWORD exception_code,
                                               const char* location) {
   Message message;
-  message << "SEH exception with code 0x" << std::setbase(16) <<
-    exception_code << std::setbase(10) << " thrown in " << location << ".";
+  message << "SEH exception with code 0x" << std::setbase(16) << exception_code
+          << std::setbase(10) << " thrown in " << location << ".";
 
   return new std::string(message.GetString());
 }
@@ -2585,8 +2577,8 @@ GoogleTestFailureException::GoogleTestFailureException(
 // exceptions in the same function.  Therefore, we provide a separate
 // wrapper function for handling SEH exceptions.)
 template <class T, typename Result>
-Result HandleSehExceptionsInMethodIfSupported(
-    T* object, Result (T::*method)(), const char* location) {
+Result HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
+                                              const char* location) {
 #if GTEST_HAS_SEH
   __try {
     return (object->*method)();
@@ -2595,8 +2587,8 @@ Result HandleSehExceptionsInMethodIfSupported(
     // We create the exception message on the heap because VC++ prohibits
     // creation of objects with destructors on stack in functions using __try
     // (see error C2712).
-    std::string* exception_message = FormatSehExceptionMessage(
-        GetExceptionCode(), location);
+    std::string* exception_message =
+        FormatSehExceptionMessage(GetExceptionCode(), location);
     internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
                                              *exception_message);
     delete exception_message;
@@ -2612,8 +2604,8 @@ Result HandleSehExceptionsInMethodIfSupported(
 // exceptions, if they are supported; returns the 0-value for type
 // Result in case of an SEH exception.
 template <class T, typename Result>
-Result HandleExceptionsInMethodIfSupported(
-    T* object, Result (T::*method)(), const char* location) {
+Result HandleExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
+                                           const char* location) {
   // NOTE: The user code can affect the way in which Google Test handles
   // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
   // RUN_ALL_TESTS() starts. It is technically possible to check the flag
@@ -2623,7 +2615,7 @@ Result HandleExceptionsInMethodIfSupported(
   // try {
   //   // Perform the test method.
   // } catch (...) {
-  //   if (GTEST_FLAG(catch_exceptions))
+  //   if (GTEST_FLAG_GET(catch_exceptions))
   //     // Report the exception as failure.
   //   else
   //     throw;  // Re-throws the original exception.
@@ -2679,16 +2671,16 @@ void Test::Run() {
   // GTEST_SKIP().
   if (!HasFatalFailure() && !IsSkipped()) {
     impl->os_stack_trace_getter()->UponLeavingGTest();
-    internal::HandleExceptionsInMethodIfSupported(
-        this, &Test::TestBody, "the test body");
+    internal::HandleExceptionsInMethodIfSupported(this, &Test::TestBody,
+                                                  "the test body");
   }
 
   // However, we want to clean up as much as possible.  Hence we will
   // always call TearDown(), even if SetUp() or the test body has
   // failed.
   impl->os_stack_trace_getter()->UponLeavingGTest();
-  internal::HandleExceptionsInMethodIfSupported(
-      this, &Test::TearDown, "TearDown()");
+  internal::HandleExceptionsInMethodIfSupported(this, &Test::TearDown,
+                                                "TearDown()");
 }
 
 // Returns true if and only if the current test has a fatal failure.
@@ -2698,8 +2690,9 @@ bool Test::HasFatalFailure() {
 
 // Returns true if and only if the current test has a non-fatal failure.
 bool Test::HasNonfatalFailure() {
-  return internal::GetUnitTestImpl()->current_test_result()->
-      HasNonfatalFailure();
+  return internal::GetUnitTestImpl()
+      ->current_test_result()
+      ->HasNonfatalFailure();
 }
 
 // Returns true if and only if the current test was skipped.
@@ -2799,11 +2792,10 @@ class TestNameIs {
   // Constructor.
   //
   // TestNameIs has NO default constructor.
-  explicit TestNameIs(const char* name)
-      : name_(name) {}
+  explicit TestNameIs(const char* name) : name_(name) {}
 
   // Returns true if and only if the test name of test_info matches name_.
-  bool operator()(const TestInfo * test_info) const {
+  bool operator()(const TestInfo* test_info) const {
     return test_info && test_info->name() == name_;
   }
 
@@ -2831,20 +2823,20 @@ void UnitTestImpl::RegisterParameterizedTests() {
 // Creates the test object, runs it, records its result, and then
 // deletes it.
 void TestInfo::Run() {
-  if (!should_run_) return;
+  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
+  if (!should_run_) {
+    if (is_disabled_ && matches_filter_) repeater->OnTestDisabled(*this);
+    return;
+  }
 
   // Tells UnitTest where to store test result.
   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
   impl->set_current_test_info(this);
 
-  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
-
   // Notifies the unit test event listeners that a test is about to start.
   repeater->OnTestStart(*this);
-
   result_.set_start_timestamp(internal::GetTimeInMillis());
   internal::Timer timer;
-
   impl->os_stack_trace_getter()->UponLeavingGTest();
 
   // Creates the test object.
@@ -3009,11 +3001,18 @@ void TestSuite::Run() {
   internal::HandleExceptionsInMethodIfSupported(
       this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
 
+  const bool skip_all = ad_hoc_test_result().Failed();
+
   start_timestamp_ = internal::GetTimeInMillis();
   internal::Timer timer;
   for (int i = 0; i < total_test_count(); i++) {
-    GetMutableTestInfo(i)->Run();
-    if (GTEST_FLAG(fail_fast) && GetMutableTestInfo(i)->result()->Failed()) {
+    if (skip_all) {
+      GetMutableTestInfo(i)->Skip();
+    } else {
+      GetMutableTestInfo(i)->Run();
+    }
+    if (GTEST_FLAG_GET(fail_fast) &&
+        GetMutableTestInfo(i)->result()->Failed()) {
       for (int j = i + 1; j < total_test_count(); j++) {
         GetMutableTestInfo(j)->Skip();
       }
@@ -3089,11 +3088,10 @@ void TestSuite::UnshuffleTests() {
 //
 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
 // FormatCountableNoun(5, "book", "books") returns "5 books".
-static std::string FormatCountableNoun(int count,
-                                       const char * singular_form,
-                                       const char * plural_form) {
+static std::string FormatCountableNoun(int count, const char* singular_form,
+                                       const char* plural_form) {
   return internal::StreamableToString(count) + " " +
-      (count == 1 ? singular_form : plural_form);
+         (count == 1 ? singular_form : plural_form);
 }
 
 // Formats the count of tests.
@@ -3110,7 +3108,7 @@ static std::string FormatTestSuiteCount(int test_suite_count) {
 // representation.  Both kNonFatalFailure and kFatalFailure are translated
 // to "Failure", as the user usually doesn't care about the difference
 // between the two when viewing the test result.
-static const char * TestPartResultTypeToString(TestPartResult::Type type) {
+static const char* TestPartResultTypeToString(TestPartResult::Type type) {
   switch (type) {
     case TestPartResult::kSkip:
       return "Skipped\n";
@@ -3137,17 +3135,18 @@ enum class GTestColor { kDefault, kRed, kGreen, kYellow };
 // Prints a TestPartResult to an std::string.
 static std::string PrintTestPartResultToString(
     const TestPartResult& test_part_result) {
-  return (Message()
-          << internal::FormatFileLocation(test_part_result.file_name(),
-                                          test_part_result.line_number())
-          << " " << TestPartResultTypeToString(test_part_result.type())
-          << test_part_result.message()).GetString();
+  return (Message() << internal::FormatFileLocation(
+                           test_part_result.file_name(),
+                           test_part_result.line_number())
+                    << " "
+                    << TestPartResultTypeToString(test_part_result.type())
+                    << test_part_result.message())
+      .GetString();
 }
 
 // Prints a TestPartResult.
 static void PrintTestPartResult(const TestPartResult& test_part_result) {
-  const std::string& result =
-      PrintTestPartResultToString(test_part_result);
+  const std::string& result = PrintTestPartResultToString(test_part_result);
   printf("%s\n", result.c_str());
   fflush(stdout);
   // If the test program runs in Visual Studio or a debugger, the
@@ -3164,8 +3163,8 @@ static void PrintTestPartResult(const TestPartResult& test_part_result) {
 }
 
 // class PrettyUnitTestResultPrinter
-#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
-    !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
+#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
+    !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
 
 // Returns the character attribute for the given color.
 static WORD GetColorAttribute(GTestColor color) {
@@ -3176,7 +3175,8 @@ static WORD GetColorAttribute(GTestColor color) {
       return FOREGROUND_GREEN;
     case GTestColor::kYellow:
       return FOREGROUND_RED | FOREGROUND_GREEN;
-    default:           return 0;
+    default:
+      return 0;
   }
 }
 
@@ -3232,7 +3232,8 @@ static const char* GetAnsiColorCode(GTestColor color) {
 
 // Returns true if and only if Google Test should use colors in the output.
 bool ShouldUseColor(bool stdout_is_tty) {
-  const char* const gtest_color = GTEST_FLAG(color).c_str();
+  std::string c = GTEST_FLAG_GET(color);
+  const char* const gtest_color = c.c_str();
 
   if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
@@ -3259,9 +3260,9 @@ bool ShouldUseColor(bool stdout_is_tty) {
   }
 
   return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
-      String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
-      String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
-      String::CStringEquals(gtest_color, "1");
+         String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
+         String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
+         String::CStringEquals(gtest_color, "1");
   // We take "yes", "true", "t", and "1" as meaning "yes".  If the
   // value is neither one of these nor "auto", we treat it as "no" to
   // be conservative.
@@ -3273,18 +3274,13 @@ bool ShouldUseColor(bool stdout_is_tty) {
 // that would be colored when printed, as can be done on Linux.
 
 GTEST_ATTRIBUTE_PRINTF_(2, 3)
-static void ColoredPrintf(GTestColor color, const char *fmt, ...) {
+static void ColoredPrintf(GTestColor color, const charfmt, ...) {
   va_list args;
   va_start(args, fmt);
 
-#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
-    GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM)
-  const bool use_color = AlwaysFalse();
-#else
   static const bool in_color_mode =
       ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
   const bool use_color = in_color_mode && (color != GTestColor::kDefault);
-#endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
 
   if (!use_color) {
     vprintf(fmt, args);
@@ -3292,8 +3288,8 @@ static void ColoredPrintf(GTestColor color, const char *fmt, ...) {
     return;
   }
 
-#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
-    !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
+#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
+    !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW
   const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
 
   // Gets the current text color.
@@ -3364,6 +3360,7 @@ class PrettyUnitTestResultPrinter : public TestEventListener {
 #endif  // OnTestCaseStart
 
   void OnTestStart(const TestInfo& test_info) override;
+  void OnTestDisabled(const TestInfo& test_info) override;
 
   void OnTestPartResult(const TestPartResult& result) override;
   void OnTestEnd(const TestInfo& test_info) override;
@@ -3384,13 +3381,14 @@ class PrettyUnitTestResultPrinter : public TestEventListener {
   static void PrintSkippedTests(const UnitTest& unit_test);
 };
 
-  // Fired before each iteration of tests starts.
+// Fired before each iteration of tests starts.
 void PrettyUnitTestResultPrinter::OnTestIterationStart(
     const UnitTest& unit_test, int iteration) {
-  if (GTEST_FLAG(repeat) != 1)
+  if (GTEST_FLAG_GET(repeat) != 1)
     printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
 
-  const char* const filter = GTEST_FLAG(filter).c_str();
+  std::string f = GTEST_FLAG_GET(filter);
+  const char* const filter = f.c_str();
 
   // Prints the filter if it's not *.  This reminds the user that some
   // tests may be skipped.
@@ -3406,7 +3404,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationStart(
                   internal::posix::GetEnv(kTestTotalShards));
   }
 
-  if (GTEST_FLAG(shuffle)) {
+  if (GTEST_FLAG_GET(shuffle)) {
     ColoredPrintf(GTestColor::kYellow,
                   "Note: Randomizing tests' orders with a seed of %d .\n",
                   unit_test.random_seed());
@@ -3462,6 +3460,13 @@ void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
   fflush(stdout);
 }
 
+void PrettyUnitTestResultPrinter::OnTestDisabled(const TestInfo& test_info) {
+  ColoredPrintf(GTestColor::kYellow, "[ DISABLED ] ");
+  PrintTestName(test_info.test_suite_name(), test_info.name());
+  printf("\n");
+  fflush(stdout);
+}
+
 // Called after an assertion failure.
 void PrettyUnitTestResultPrinter::OnTestPartResult(
     const TestPartResult& result) {
@@ -3486,12 +3491,12 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
     ColoredPrintf(GTestColor::kRed, "[  FAILED  ] ");
   }
   PrintTestName(test_info.test_suite_name(), test_info.name());
-  if (test_info.result()->Failed())
-    PrintFullTestCommentIfPresent(test_info);
+  if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info);
 
-  if (GTEST_FLAG(print_time)) {
-    printf(" (%s ms)\n", internal::StreamableToString(
-           test_info.result()->elapsed_time()).c_str());
+  if (GTEST_FLAG_GET(print_time)) {
+    printf(" (%s ms)\n",
+           internal::StreamableToString(test_info.result()->elapsed_time())
+               .c_str());
   } else {
     printf("\n");
   }
@@ -3500,7 +3505,7 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
 
 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
-  if (!GTEST_FLAG(print_time)) return;
+  if (!GTEST_FLAG_GET(print_time)) return;
 
   const std::string counts =
       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
@@ -3511,7 +3516,7 @@ void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
 }
 #else
 void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) {
-  if (!GTEST_FLAG(print_time)) return;
+  if (!GTEST_FLAG_GET(print_time)) return;
 
   const std::string counts =
       FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
@@ -3607,7 +3612,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
   printf("%s from %s ran.",
          FormatTestCount(unit_test.test_to_run_count()).c_str(),
          FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
-  if (GTEST_FLAG(print_time)) {
+  if (GTEST_FLAG_GET(print_time)) {
     printf(" (%s ms total)",
            internal::StreamableToString(unit_test.elapsed_time()).c_str());
   }
@@ -3628,7 +3633,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
   }
 
   int num_disabled = unit_test.reportable_disabled_test_count();
-  if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
+  if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) {
     if (unit_test.Passed()) {
       printf("\n");  // Add a spacer if no FAILURE banner is displayed.
     }
@@ -3664,6 +3669,7 @@ class BriefUnitTestResultPrinter : public TestEventListener {
 #endif  // OnTestCaseStart
 
   void OnTestStart(const TestInfo& /*test_info*/) override {}
+  void OnTestDisabled(const TestInfo& /*test_info*/) override {}
 
   void OnTestPartResult(const TestPartResult& result) override;
   void OnTestEnd(const TestInfo& test_info) override;
@@ -3700,7 +3706,7 @@ void BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
     PrintTestName(test_info.test_suite_name(), test_info.name());
     PrintFullTestCommentIfPresent(test_info);
 
-    if (GTEST_FLAG(print_time)) {
+    if (GTEST_FLAG_GET(print_time)) {
       printf(" (%s ms)\n",
              internal::StreamableToString(test_info.result()->elapsed_time())
                  .c_str());
@@ -3717,7 +3723,7 @@ void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
   printf("%s from %s ran.",
          FormatTestCount(unit_test.test_to_run_count()).c_str(),
          FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
-  if (GTEST_FLAG(print_time)) {
+  if (GTEST_FLAG_GET(print_time)) {
     printf(" (%s ms total)",
            internal::StreamableToString(unit_test.elapsed_time()).c_str());
   }
@@ -3732,7 +3738,7 @@ void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
   }
 
   int num_disabled = unit_test.reportable_disabled_test_count();
-  if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
+  if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) {
     if (unit_test.Passed()) {
       printf("\n");  // Add a spacer if no FAILURE banner is displayed.
     }
@@ -3752,7 +3758,7 @@ class TestEventRepeater : public TestEventListener {
  public:
   TestEventRepeater() : forwarding_enabled_(true) {}
   ~TestEventRepeater() override;
-  void Append(TestEventListener *listener);
+  void Append(TestEventListenerlistener);
   TestEventListener* Release(TestEventListener* listener);
 
   // Controls whether events will be forwarded to listeners_. Set to false
@@ -3770,6 +3776,7 @@ class TestEventRepeater : public TestEventListener {
 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
   void OnTestSuiteStart(const TestSuite& parameter) override;
   void OnTestStart(const TestInfo& test_info) override;
+  void OnTestDisabled(const TestInfo& test_info) override;
   void OnTestPartResult(const TestPartResult& result) override;
   void OnTestEnd(const TestInfo& test_info) override;
 //  Legacy API is deprecated but still available
@@ -3789,18 +3796,19 @@ class TestEventRepeater : public TestEventListener {
   // The list of listeners that receive events.
   std::vector<TestEventListener*> listeners_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
+  TestEventRepeater(const TestEventRepeater&) = delete;
+  TestEventRepeater& operator=(const TestEventRepeater&) = delete;
 };
 
 TestEventRepeater::~TestEventRepeater() {
   ForEach(listeners_, Delete<TestEventListener>);
 }
 
-void TestEventRepeater::Append(TestEventListener *listener) {
+void TestEventRepeater::Append(TestEventListenerlistener) {
   listeners_.push_back(listener);
 }
 
-TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
+TestEventListener* TestEventRepeater::Release(TestEventListenerlistener) {
   for (size_t i = 0; i < listeners_.size(); ++i) {
     if (listeners_[i] == listener) {
       listeners_.erase(listeners_.begin() + static_cast<int>(i));
@@ -3813,14 +3821,14 @@ TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
 
 // Since most methods are very similar, use macros to reduce boilerplate.
 // This defines a member that forwards the call to all listeners.
-#define GTEST_REPEATER_METHOD_(Name, Type) \
-void TestEventRepeater::Name(const Type& parameter) { \
-  if (forwarding_enabled_) { \
-    for (size_t i = 0; i < listeners_.size(); i++) { \
-      listeners_[i]->Name(parameter); \
-    } \
-  } \
-}
+#define GTEST_REPEATER_METHOD_(Name, Type)              \
+  void TestEventRepeater::Name(const Type& parameter) { \
+    if (forwarding_enabled_) {                          \
+      for (size_t i = 0; i < listeners_.size(); i++) {  \
+        listeners_[i]->Name(parameter);                 \
+      }                                                 \
+    }                                                   \
+  }
 // This defines a member that forwards the call to all listeners in reverse
 // order.
 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type)      \
@@ -3840,6 +3848,7 @@ GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)
 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
 GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)
 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
+GTEST_REPEATER_METHOD_(OnTestDisabled, TestInfo)
 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
@@ -3890,12 +3899,13 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener {
  private:
   // Is c a whitespace character that is normalized to a space character
   // when it appears in an XML attribute value?
-  static bool IsNormalizableWhitespace(char c) {
-    return c == 0x9 || c == 0xA || c == 0xD;
+  static bool IsNormalizableWhitespace(unsigned char c) {
+    return c == '\t' || c == '\n' || c == '\r';
   }
 
   // May c appear in a well-formed XML document?
-  static bool IsValidXmlCharacter(char c) {
+  // https://www.w3.org/TR/REC-xml/#charsets
+  static bool IsValidXmlCharacter(unsigned char c) {
     return IsNormalizableWhitespace(c) || c >= 0x20;
   }
 
@@ -3965,7 +3975,8 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener {
   // The output file.
   const std::string output_file_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
+  XmlUnitTestResultPrinter(const XmlUnitTestResultPrinter&) = delete;
+  XmlUnitTestResultPrinter& operator=(const XmlUnitTestResultPrinter&) = delete;
 };
 
 // Creates a new XmlUnitTestResultPrinter.
@@ -4005,8 +4016,8 @@ void XmlUnitTestResultPrinter::ListTestsMatchingFilter(
 // module will consist of ordinary English text.
 // If this module is ever modified to produce version 1.1 XML output,
 // most invalid characters can be retained using character references.
-std::string XmlUnitTestResultPrinter::EscapeXml(
-    const std::string& str, bool is_attribute) {
+std::string XmlUnitTestResultPrinter::EscapeXml(const std::string& str,
+                                                bool is_attribute) {
   Message m;
 
   for (size_t i = 0; i < str.size(); ++i) {
@@ -4034,8 +4045,9 @@ std::string XmlUnitTestResultPrinter::EscapeXml(
           m << '"';
         break;
       default:
-        if (IsValidXmlCharacter(ch)) {
-          if (is_attribute && IsNormalizableWhitespace(ch))
+        if (IsValidXmlCharacter(static_cast<unsigned char>(ch))) {
+          if (is_attribute &&
+              IsNormalizableWhitespace(static_cast<unsigned char>(ch)))
             m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
               << ";";
           else
@@ -4056,7 +4068,7 @@ std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
   std::string output;
   output.reserve(str.size());
   for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
-    if (IsValidXmlCharacter(*it))
+    if (IsValidXmlCharacter(static_cast<unsigned char>(*it)))
       output.push_back(*it);
 
   return output;
@@ -4064,7 +4076,6 @@ std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
 
 // The following routines generate an XML representation of a UnitTest
 // object.
-// GOOGLETEST_CM0009 DO NOT DELETE
 //
 // This is how Google Test concepts map to the DTD:
 //
@@ -4113,12 +4124,12 @@ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
     return "";
   // YYYY-MM-DDThh:mm:ss.sss
   return StreamableToString(time_struct.tm_year + 1900) + "-" +
-      String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
-      String::FormatIntWidth2(time_struct.tm_mday) + "T" +
-      String::FormatIntWidth2(time_struct.tm_hour) + ":" +
-      String::FormatIntWidth2(time_struct.tm_min) + ":" +
-      String::FormatIntWidth2(time_struct.tm_sec) + "." +
-      String::FormatIntWidthN(static_cast<int>(ms % 1000), 3);
+         String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
+         String::FormatIntWidth2(time_struct.tm_mday) + "T" +
+         String::FormatIntWidth2(time_struct.tm_hour) + ":" +
+         String::FormatIntWidth2(time_struct.tm_min) + ":" +
+         String::FormatIntWidth2(time_struct.tm_sec) + "." +
+         String::FormatIntWidthN(static_cast<int>(ms % 1000), 3);
 }
 
 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
@@ -4129,8 +4140,8 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
   for (;;) {
     const char* const next_segment = strstr(segment, "]]>");
     if (next_segment != nullptr) {
-      stream->write(
-          segment, static_cast<std::streamsize>(next_segment - segment));
+      stream->write(segment,
+                    static_cast<std::streamsize>(next_segment - segment));
       *stream << "]]>]]&gt;<![CDATA[";
       segment = next_segment + strlen("]]>");
     } else {
@@ -4142,15 +4153,13 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
 }
 
 void XmlUnitTestResultPrinter::OutputXmlAttribute(
-    std::ostream* stream,
-    const std::string& element_name,
-    const std::string& name,
-    const std::string& value) {
+    std::ostream* stream, const std::string& element_name,
+    const std::string& name, const std::string& value) {
   const std::vector<std::string>& allowed_names =
       GetReservedOutputAttributesForElement(element_name);
 
   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
-                   allowed_names.end())
+               allowed_names.end())
       << "Attribute " << name << " is not allowed for element <" << element_name
       << ">.";
 
@@ -4216,10 +4225,11 @@ void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
     OutputXmlAttribute(stream, kTestsuite, "type_param",
                        test_info.type_param());
   }
-  if (GTEST_FLAG(list_tests)) {
-    OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
-    OutputXmlAttribute(stream, kTestsuite, "line",
-                       StreamableToString(test_info.line()));
+
+  OutputXmlAttribute(stream, kTestsuite, "file", test_info.file());
+  OutputXmlAttribute(stream, kTestsuite, "line",
+                     StreamableToString(test_info.line()));
+  if (GTEST_FLAG_GET(list_tests)) {
     *stream << " />\n";
     return;
   }
@@ -4254,8 +4264,7 @@ void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
           internal::FormatCompilerIndependentFileLocation(part.file_name(),
                                                           part.line_number());
       const std::string summary = location + "\n" + part.summary();
-      *stream << "      <failure message=\""
-              << EscapeXmlAttribute(summary)
+      *stream << "      <failure message=\"" << EscapeXmlAttribute(summary)
               << "\" type=\"\">";
       const std::string detail = location + "\n" + part.message();
       OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
@@ -4295,7 +4304,7 @@ void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
   OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name());
   OutputXmlAttribute(stream, kTestsuite, "tests",
                      StreamableToString(test_suite.reportable_test_count()));
-  if (!GTEST_FLAG(list_tests)) {
+  if (!GTEST_FLAG_GET(list_tests)) {
     OutputXmlAttribute(stream, kTestsuite, "failures",
                        StreamableToString(test_suite.failed_test_count()));
     OutputXmlAttribute(
@@ -4343,7 +4352,7 @@ void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
       stream, kTestsuites, "timestamp",
       FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
 
-  if (GTEST_FLAG(shuffle)) {
+  if (GTEST_FLAG_GET(shuffle)) {
     OutputXmlAttribute(stream, kTestsuites, "random_seed",
                        StreamableToString(unit_test.random_seed()));
   }
@@ -4396,7 +4405,7 @@ std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
   for (int i = 0; i < result.test_property_count(); ++i) {
     const TestProperty& property = result.GetTestProperty(i);
     attributes << " " << property.key() << "="
-        << "\"" << EscapeXmlAttribute(property.value()) << "\"";
+               << "\"" << EscapeXmlAttribute(property.value()) << "\"";
   }
   return attributes.GetString();
 }
@@ -4410,15 +4419,15 @@ void XmlUnitTestResultPrinter::OutputXmlTestProperties(
     return;
   }
 
-  *stream << "<" << kProperties << ">\n";
+  *stream << "      <" << kProperties << ">\n";
   for (int i = 0; i < result.test_property_count(); ++i) {
     const TestProperty& property = result.GetTestProperty(i);
-    *stream << "<" << kProperty;
+    *stream << "        <" << kProperty;
     *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
     *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
     *stream << "/>\n";
   }
-  *stream << "</" << kProperties << ">\n";
+  *stream << "      </" << kProperties << ">\n";
 }
 
 // End XmlUnitTestResultPrinter
@@ -4442,16 +4451,12 @@ class JsonUnitTestResultPrinter : public EmptyTestEventListener {
   //// streams the attribute as JSON.
   static void OutputJsonKey(std::ostream* stream,
                             const std::string& element_name,
-                            const std::string& name,
-                            const std::string& value,
-                            const std::string& indent,
-                            bool comma = true);
+                            const std::string& name, const std::string& value,
+                            const std::string& indent, bool comma = true);
   static void OutputJsonKey(std::ostream* stream,
                             const std::string& element_name,
-                            const std::string& name,
-                            int value,
-                            const std::string& indent,
-                            bool comma = true);
+                            const std::string& name, int value,
+                            const std::string& indent, bool comma = true);
 
   // Streams a test suite JSON stanza containing the given test result.
   //
@@ -4484,7 +4489,9 @@ class JsonUnitTestResultPrinter : public EmptyTestEventListener {
   // The output file.
   const std::string output_file_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);
+  JsonUnitTestResultPrinter(const JsonUnitTestResultPrinter&) = delete;
+  JsonUnitTestResultPrinter& operator=(const JsonUnitTestResultPrinter&) =
+      delete;
 };
 
 // Creates a new JsonUnitTestResultPrinter.
@@ -4496,7 +4503,7 @@ JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)
 }
 
 void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
-                                                  int /*iteration*/) {
+                                                   int /*iteration*/) {
   FILE* jsonout = OpenFileForWriting(output_file_);
   std::stringstream stream;
   PrintJsonUnitTest(&stream, unit_test);
@@ -4562,55 +4569,48 @@ static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {
     return "";
   // YYYY-MM-DDThh:mm:ss
   return StreamableToString(time_struct.tm_year + 1900) + "-" +
-      String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
-      String::FormatIntWidth2(time_struct.tm_mday) + "T" +
-      String::FormatIntWidth2(time_struct.tm_hour) + ":" +
-      String::FormatIntWidth2(time_struct.tm_min) + ":" +
-      String::FormatIntWidth2(time_struct.tm_sec) + "Z";
+         String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
+         String::FormatIntWidth2(time_struct.tm_mday) + "T" +
+         String::FormatIntWidth2(time_struct.tm_hour) + ":" +
+         String::FormatIntWidth2(time_struct.tm_min) + ":" +
+         String::FormatIntWidth2(time_struct.tm_sec) + "Z";
 }
 
 static inline std::string Indent(size_t width) {
   return std::string(width, ' ');
 }
 
-void JsonUnitTestResultPrinter::OutputJsonKey(
-    std::ostream* stream,
-    const std::string& element_name,
-    const std::string& name,
-    const std::string& value,
-    const std::string& indent,
-    bool comma) {
+void JsonUnitTestResultPrinter::OutputJsonKey(std::ostream* stream,
+                                              const std::string& element_name,
+                                              const std::string& name,
+                                              const std::string& value,
+                                              const std::string& indent,
+                                              bool comma) {
   const std::vector<std::string>& allowed_names =
       GetReservedOutputAttributesForElement(element_name);
 
   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
-                   allowed_names.end())
+               allowed_names.end())
       << "Key \"" << name << "\" is not allowed for value \"" << element_name
       << "\".";
 
   *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\"";
-  if (comma)
-    *stream << ",\n";
+  if (comma) *stream << ",\n";
 }
 
 void JsonUnitTestResultPrinter::OutputJsonKey(
-    std::ostream* stream,
-    const std::string& element_name,
-    const std::string& name,
-    int value,
-    const std::string& indent,
-    bool comma) {
+    std::ostream* stream, const std::string& element_name,
+    const std::string& name, int value, const std::string& indent, bool comma) {
   const std::vector<std::string>& allowed_names =
       GetReservedOutputAttributesForElement(element_name);
 
   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
-                   allowed_names.end())
+               allowed_names.end())
       << "Key \"" << name << "\" is not allowed for value \"" << element_name
       << "\".";
 
   *stream << indent << "\"" << name << "\": " << StreamableToString(value);
-  if (comma)
-    *stream << ",\n";
+  if (comma) *stream << ",\n";
 }
 
 // Streams a test suite JSON stanza containing the given test result.
@@ -4620,7 +4620,7 @@ void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(
   *stream << Indent(4) << "{\n";
   OutputJsonKey(stream, "testsuite", "name", "NonTestSuiteFailure", Indent(6));
   OutputJsonKey(stream, "testsuite", "tests", 1, Indent(6));
-  if (!GTEST_FLAG(list_tests)) {
+  if (!GTEST_FLAG_GET(list_tests)) {
     OutputJsonKey(stream, "testsuite", "failures", 1, Indent(6));
     OutputJsonKey(stream, "testsuite", "disabled", 0, Indent(6));
     OutputJsonKey(stream, "testsuite", "skipped", 0, Indent(6));
@@ -4674,11 +4674,14 @@ void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
     OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(),
                   kIndent);
   }
-  if (GTEST_FLAG(list_tests)) {
-    OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
-    OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
+
+  OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent);
+  OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false);
+  if (GTEST_FLAG_GET(list_tests)) {
     *stream << "\n" << Indent(8) << "}";
     return;
+  } else {
+    *stream << ",\n";
   }
 
   OutputJsonKey(stream, kTestsuite, "status",
@@ -4710,7 +4713,9 @@ void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
     if (part.failed()) {
       *stream << ",\n";
       if (++failures == 1) {
-        *stream << kIndent << "\"" << "failures" << "\": [\n";
+        *stream << kIndent << "\""
+                << "failures"
+                << "\": [\n";
       }
       const std::string location =
           internal::FormatCompilerIndependentFileLocation(part.file_name(),
@@ -4723,8 +4728,7 @@ void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
     }
   }
 
-  if (failures > 0)
-    *stream << "\n" << kIndent << "]";
+  if (failures > 0) *stream << "\n" << kIndent << "]";
   *stream << "\n" << Indent(8) << "}";
 }
 
@@ -4738,7 +4742,7 @@ void JsonUnitTestResultPrinter::PrintJsonTestSuite(
   OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent);
   OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(),
                 kIndent);
-  if (!GTEST_FLAG(list_tests)) {
+  if (!GTEST_FLAG_GET(list_tests)) {
     OutputJsonKey(stream, kTestsuite, "failures",
                   test_suite.failed_test_count(), kIndent);
     OutputJsonKey(stream, kTestsuite, "disabled",
@@ -4785,7 +4789,7 @@ void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
   OutputJsonKey(stream, kTestsuites, "disabled",
                 unit_test.reportable_disabled_test_count(), kIndent);
   OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent);
-  if (GTEST_FLAG(shuffle)) {
+  if (GTEST_FLAG_GET(shuffle)) {
     OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(),
                   kIndent);
   }
@@ -4820,7 +4824,9 @@ void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
     OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
   }
 
-  *stream << "\n" << kIndent << "]\n" << "}\n";
+  *stream << "\n"
+          << kIndent << "]\n"
+          << "}\n";
 }
 
 void JsonUnitTestResultPrinter::PrintJsonTestList(
@@ -4855,7 +4861,8 @@ std::string JsonUnitTestResultPrinter::TestPropertiesAsJson(
   Message attributes;
   for (int i = 0; i < result.test_property_count(); ++i) {
     const TestProperty& property = result.GetTestProperty(i);
-    attributes << ",\n" << indent << "\"" << property.key() << "\": "
+    attributes << ",\n"
+               << indent << "\"" << property.key() << "\": "
                << "\"" << EscapeJson(property.value()) << "\"";
   }
   return attributes.GetString();
@@ -4895,14 +4902,14 @@ void StreamingListener::SocketWriter::MakeConnection() {
 
   addrinfo hints;
   memset(&hints, 0, sizeof(hints));
-  hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.
+  hints.ai_family = AF_UNSPEC;  // To allow both IPv4 and IPv6 addresses.
   hints.ai_socktype = SOCK_STREAM;
   addrinfo* servinfo = nullptr;
 
   // Use the getaddrinfo() to get a linked list of IP addresses for
   // the given host name.
-  const int error_num = getaddrinfo(
-      host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
+  const int error_num =
+      getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
   if (error_num != 0) {
     GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
                         << gai_strerror(error_num);
@@ -4911,8 +4918,8 @@ void StreamingListener::SocketWriter::MakeConnection() {
   // Loop through all the results and connect to the first we can.
   for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;
        cur_addr = cur_addr->ai_next) {
-    sockfd_ = socket(
-        cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
+    sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype,
+                     cur_addr->ai_protocol);
     if (sockfd_ != -1) {
       // Connect the client socket to the server socket.
       if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
@@ -4962,7 +4969,7 @@ std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
 
   for (int i = 0; i < raw_stack_size; ++i) {
     if (raw_stack[i] == caller_frame &&
-        !GTEST_FLAG(show_internal_stack_frames)) {
+        !GTEST_FLAG_GET(show_internal_stack_frames)) {
       // Add a marker to the trace and stop adding frames.
       absl::StrAppend(&result, kElidedFramesMarker, "\n");
       break;
@@ -4981,7 +4988,7 @@ std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
 
   return result;
 
-#else  // !GTEST_HAS_ABSL
+#else   // !GTEST_HAS_ABSL
   static_cast<void>(max_depth);
   static_cast<void>(skip_count);
   return "";
@@ -5005,14 +5012,14 @@ void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
 class ScopedPrematureExitFile {
  public:
   explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
-      : premature_exit_filepath_(premature_exit_filepath ?
-                                 premature_exit_filepath : "") {
+      : premature_exit_filepath_(
+            premature_exit_filepath ? premature_exit_filepath : "") {
     // If a path to the premature-exit file is specified...
     if (!premature_exit_filepath_.empty()) {
       // create the file with a single "0" character in it.  I/O
       // errors are ignored as there's nothing better we can do and we
       // don't want to fail the test because of this.
-      FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
+      FILE* pfile = posix::FOpen(premature_exit_filepath_.c_str(), "w");
       fwrite("0", 1, 1, pfile);
       fclose(pfile);
     }
@@ -5034,7 +5041,8 @@ class ScopedPrematureExitFile {
  private:
   const std::string premature_exit_filepath_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
+  ScopedPrematureExitFile(const ScopedPrematureExitFile&) = delete;
+  ScopedPrematureExitFile& operator=(const ScopedPrematureExitFile&) = delete;
 };
 
 }  // namespace internal
@@ -5208,7 +5216,7 @@ int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
 // Gets the time of the test program start, in ms from the start of the
 // UNIX epoch.
 internal::TimeInMillis UnitTest::start_timestamp() const {
-    return impl()->start_timestamp();
+  return impl()->start_timestamp();
 }
 
 // Gets the elapsed time, in milliseconds.
@@ -5251,9 +5259,7 @@ TestSuite* UnitTest::GetMutableTestSuite(int i) {
 
 // Returns the list of event listeners that can be used to track events
 // inside Google Test.
-TestEventListeners& UnitTest::listeners() {
-  return *impl()->listeners();
-}
+TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); }
 
 // Registers and returns a global test environment.  When a test
 // program is run, all global test environments will be set-up in the
@@ -5278,12 +5284,11 @@ Environment* UnitTest::AddEnvironment(Environment* env) {
 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
 // this to report their results.  The user code should use the
 // assertion macros instead of calling this directly.
-void UnitTest::AddTestPartResult(
-    TestPartResult::Type result_type,
-    const char* file_name,
-    int line_number,
-    const std::string& message,
-    const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
+void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
+                                 const char* file_name, int line_number,
+                                 const std::string& message,
+                                 const std::string& os_stack_trace)
+    GTEST_LOCK_EXCLUDED_(mutex_) {
   Message msg;
   msg << message;
 
@@ -5293,8 +5298,9 @@ void UnitTest::AddTestPartResult(
 
     for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {
       const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
-      msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
-          << " " << trace.message;
+      msg << "\n"
+          << internal::FormatFileLocation(trace.file, trace.line) << " "
+          << trace.message;
     }
   }
 
@@ -5304,8 +5310,8 @@ void UnitTest::AddTestPartResult(
 
   const TestPartResult result = TestPartResult(
       result_type, file_name, line_number, msg.GetString().c_str());
-  impl_->GetTestPartResultReporterForCurrentThread()->
-      ReportTestPartResult(result);
+  impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
+      result);
 
   if (result_type != TestPartResult::kSuccess &&
       result_type != TestPartResult::kSkip) {
@@ -5314,7 +5320,7 @@ void UnitTest::AddTestPartResult(
     // in the code (perhaps in order to use Google Test assertions
     // with another testing framework) and specify the former on the
     // command line for debugging.
-    if (GTEST_FLAG(break_on_failure)) {
+    if (GTEST_FLAG_GET(break_on_failure)) {
 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
       // Using DebugBreak on Windows allows gtest to still break into a debugger
       // when a failure happens and both the --gtest_break_on_failure and
@@ -5331,7 +5337,7 @@ void UnitTest::AddTestPartResult(
       // portability: some debuggers don't correctly trap abort().
       *static_cast<volatile int*>(nullptr) = 1;
 #endif  // GTEST_OS_WINDOWS
-    } else if (GTEST_FLAG(throw_on_failure)) {
+    } else if (GTEST_FLAG_GET(throw_on_failure)) {
 #if GTEST_HAS_EXCEPTIONS
       throw internal::GoogleTestFailureException(result);
 #else
@@ -5360,7 +5366,7 @@ void UnitTest::RecordProperty(const std::string& key,
 // from the main thread.
 int UnitTest::Run() {
   const bool in_death_test_child_process =
-      internal::GTEST_FLAG(internal_run_death_test).length() > 0;
+      GTEST_FLAG_GET(internal_run_death_test).length() > 0;
 
   // Google Test implements this protocol for catching that a test
   // program exits before returning control to Google Test:
@@ -5390,7 +5396,7 @@ int UnitTest::Run() {
 
   // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
   // used for the duration of the program.
-  impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
+  impl()->set_catch_exceptions(GTEST_FLAG_GET(catch_exceptions));
 
 #if GTEST_OS_WINDOWS
   // Either the user wants Google Test to catch exceptions thrown by the
@@ -5398,26 +5404,26 @@ int UnitTest::Run() {
   // process. In either case the user does not want to see pop-up dialogs
   // about crashes - they are expected.
   if (impl()->catch_exceptions() || in_death_test_child_process) {
-# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
+#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
     // SetErrorMode doesn't exist on CE.
     SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
                  SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
-# endif  // !GTEST_OS_WINDOWS_MOBILE
+#endif  // !GTEST_OS_WINDOWS_MOBILE
 
-# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
+#if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
     // Death test children can be terminated with _abort().  On Windows,
     // _abort() can show a dialog with a warning message.  This forces the
     // abort message to go to stderr instead.
     _set_error_mode(_OUT_TO_STDERR);
-# endif
+#endif
 
-# if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
+#if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE
     // In the debug version, Visual Studio pops up a separate dialog
     // offering a choice to debug the aborted program. We need to suppress
     // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
     // executed. Google Test will notify the user of any unexpected
     // failure via stderr.
-    if (!GTEST_FLAG(break_on_failure))
+    if (!GTEST_FLAG_GET(break_on_failure))
       _set_abort_behavior(
           0x0,                                    // Clear the following flags:
           _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
@@ -5431,14 +5437,15 @@ int UnitTest::Run() {
                               _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
       (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
     }
-# endif
+#endif
   }
 #endif  // GTEST_OS_WINDOWS
 
   return internal::HandleExceptionsInMethodIfSupported(
-      impl(),
-      &internal::UnitTestImpl::RunAllTests,
-      "auxiliary test code (environments or event listeners)") ? 0 : 1;
+             impl(), &internal::UnitTestImpl::RunAllTests,
+             "auxiliary test code (environments or event listeners)")
+             ? 0
+             : 1;
 }
 
 // Returns the working directory when the first TEST() or TEST_F() was
@@ -5483,14 +5490,10 @@ UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {
 }
 
 // Creates an empty UnitTest.
-UnitTest::UnitTest() {
-  impl_ = new internal::UnitTestImpl(this);
-}
+UnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); }
 
 // Destructor of UnitTest.
-UnitTest::~UnitTest() {
-  delete impl_;
-}
+UnitTest::~UnitTest() { delete impl_; }
 
 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
 // Google Test trace stack.
@@ -5501,8 +5504,7 @@ void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
 }
 
 // Pops a trace from the per-thread Google Test trace stack.
-void UnitTest::PopGTestTrace()
-    GTEST_LOCK_EXCLUDED_(mutex_) {
+void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) {
   internal::MutexLock lock(&mutex_);
   impl_->gtest_trace_stack().pop_back();
 }
@@ -5599,12 +5601,12 @@ void UnitTestImpl::ConfigureXmlOutput() {
 // Initializes event listeners for streaming test results in string form.
 // Must not be called before InitGoogleTest.
 void UnitTestImpl::ConfigureStreamingOutput() {
-  const std::string& target = GTEST_FLAG(stream_result_to);
+  const std::string& target = GTEST_FLAG_GET(stream_result_to);
   if (!target.empty()) {
     const size_t pos = target.find(':');
     if (pos != std::string::npos) {
-      listeners()->Append(new StreamingListener(target.substr(0, pos),
-                                                target.substr(pos+1)));
+      listeners()->Append(
+          new StreamingListener(target.substr(0, pos), target.substr(pos + 1)));
     } else {
       GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target
                           << "\" ignored.";
@@ -5642,7 +5644,7 @@ void UnitTestImpl::PostFlagParsingInit() {
     // to shut down the default XML output before invoking RUN_ALL_TESTS.
     ConfigureXmlOutput();
 
-    if (GTEST_FLAG(brief)) {
+    if (GTEST_FLAG_GET(brief)) {
       listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter);
     }
 
@@ -5652,7 +5654,7 @@ void UnitTestImpl::PostFlagParsingInit() {
 #endif  // GTEST_CAN_STREAM_RESULTS_
 
 #if GTEST_HAS_ABSL
-    if (GTEST_FLAG(install_failure_signal_handler)) {
+    if (GTEST_FLAG_GET(install_failure_signal_handler)) {
       absl::FailureSignalHandlerOptions options;
       absl::InstallFailureSignalHandler(options);
     }
@@ -5710,9 +5712,9 @@ TestSuite* UnitTestImpl::GetTestSuite(
   auto* const new_test_suite =
       new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);
 
+  const UnitTestFilter death_test_suite_filter(kDeathTestSuiteFilter);
   // Is this a death test suite?
-  if (internal::UnitTestOptions::MatchesFilter(test_suite_name,
-                                               kDeathTestSuiteFilter)) {
+  if (death_test_suite_filter.MatchesName(test_suite_name)) {
     // Yes.  Inserts the test suite after the last death test suite
     // defined so far.  This only works when the test suites haven't
     // been shuffled.  Otherwise we may end up running a death test
@@ -5749,8 +5751,7 @@ bool UnitTestImpl::RunAllTests() {
   const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();
 
   // Do not run any test if the --help flag was specified.
-  if (g_help_flag)
-    return true;
+  if (g_help_flag) return true;
 
   // Repeats the call to the post-flag parsing initialization in case the
   // user didn't call InitGoogleTest.
@@ -5768,11 +5769,11 @@ bool UnitTestImpl::RunAllTests() {
 #if GTEST_HAS_DEATH_TEST
   in_subprocess_for_death_test =
       (internal_run_death_test_flag_.get() != nullptr);
-# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
+#if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
   if (in_subprocess_for_death_test) {
     GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
   }
-# endif  // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
+#endif  // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
 #endif  // GTEST_HAS_DEATH_TEST
 
   const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
@@ -5780,19 +5781,18 @@ bool UnitTestImpl::RunAllTests() {
 
   // Compares the full test names with the filter to decide which
   // tests to run.
-  const bool has_tests_to_run = FilterTests(should_shard
-                                              ? HONOR_SHARDING_PROTOCOL
-                                              : IGNORE_SHARDING_PROTOCOL) > 0;
+  const bool has_tests_to_run =
+      FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL
+                               : IGNORE_SHARDING_PROTOCOL) > 0;
 
   // Lists the tests and exits if the --gtest_list_tests flag was specified.
-  if (GTEST_FLAG(list_tests)) {
+  if (GTEST_FLAG_GET(list_tests)) {
     // This must be called *after* FilterTests() has been called.
     ListTestsMatchingFilter();
     return true;
   }
 
-  random_seed_ = GTEST_FLAG(shuffle) ?
-      GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
+  random_seed_ = GetRandomSeedFromFlag(GTEST_FLAG_GET(random_seed));
 
   // True if and only if at least one test has failed.
   bool failed = false;
@@ -5804,9 +5804,21 @@ bool UnitTestImpl::RunAllTests() {
 
   // How many times to repeat the tests?  We don't want to repeat them
   // when we are inside the subprocess of a death test.
-  const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
+  const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG_GET(repeat);
+
   // Repeats forever if the repeat count is negative.
   const bool gtest_repeat_forever = repeat < 0;
+
+  // Should test environments be set up and torn down for each repeat, or only
+  // set up on the first and torn down on the last iteration? If there is no
+  // "last" iteration because the tests will repeat forever, always recreate the
+  // environments to avoid leaks in case one of the environments is using
+  // resources that are external to this process. Without this check there would
+  // be no way to clean up those external resources automatically.
+  const bool recreate_environments_when_repeating =
+      GTEST_FLAG_GET(recreate_environments_when_repeating) ||
+      gtest_repeat_forever;
+
   for (int i = 0; gtest_repeat_forever || i != repeat; i++) {
     // We want to preserve failures generated by ad-hoc test
     // assertions executed before RUN_ALL_TESTS().
@@ -5815,7 +5827,7 @@ bool UnitTestImpl::RunAllTests() {
     Timer timer;
 
     // Shuffles test suites and tests if requested.
-    if (has_tests_to_run && GTEST_FLAG(shuffle)) {
+    if (has_tests_to_run && GTEST_FLAG_GET(shuffle)) {
       random()->Reseed(static_cast<uint32_t>(random_seed_));
       // This should be done before calling OnTestIterationStart(),
       // such that a test event listener can see the actual test order
@@ -5828,10 +5840,13 @@ bool UnitTestImpl::RunAllTests() {
 
     // Runs each test suite if there is at least one test to run.
     if (has_tests_to_run) {
-      // Sets up all environments beforehand.
-      repeater->OnEnvironmentsSetUpStart(*parent_);
-      ForEach(environments_, SetUpEnvironment);
-      repeater->OnEnvironmentsSetUpEnd(*parent_);
+      // Sets up all environments beforehand. If test environments aren't
+      // recreated for each iteration, only do so on the first iteration.
+      if (i == 0 || recreate_environments_when_repeating) {
+        repeater->OnEnvironmentsSetUpStart(*parent_);
+        ForEach(environments_, SetUpEnvironment);
+        repeater->OnEnvironmentsSetUpEnd(*parent_);
+      }
 
       // Runs the tests only if there was no fatal failure or skip triggered
       // during global set-up.
@@ -5853,7 +5868,7 @@ bool UnitTestImpl::RunAllTests() {
         for (int test_index = 0; test_index < total_test_suite_count();
              test_index++) {
           GetMutableSuiteCase(test_index)->Run();
-          if (GTEST_FLAG(fail_fast) &&
+          if (GTEST_FLAG_GET(fail_fast) &&
               GetMutableSuiteCase(test_index)->Failed()) {
             for (int j = test_index + 1; j < total_test_suite_count(); j++) {
               GetMutableSuiteCase(j)->Skip();
@@ -5871,11 +5886,15 @@ bool UnitTestImpl::RunAllTests() {
         }
       }
 
-      // Tears down all environments in reverse order afterwards.
-      repeater->OnEnvironmentsTearDownStart(*parent_);
-      std::for_each(environments_.rbegin(), environments_.rend(),
-                    TearDownEnvironment);
-      repeater->OnEnvironmentsTearDownEnd(*parent_);
+      // Tears down all environments in reverse order afterwards. If test
+      // environments aren't recreated for each iteration, only do so on the
+      // last iteration.
+      if (i == repeat - 1 || recreate_environments_when_repeating) {
+        repeater->OnEnvironmentsTearDownStart(*parent_);
+        std::for_each(environments_.rbegin(), environments_.rend(),
+                      TearDownEnvironment);
+        repeater->OnEnvironmentsTearDownEnd(*parent_);
+      }
     }
 
     elapsed_time_ = timer.Elapsed();
@@ -5896,7 +5915,7 @@ bool UnitTestImpl::RunAllTests() {
     // (it's always safe to unshuffle the tests).
     UnshuffleTests();
 
-    if (GTEST_FLAG(shuffle)) {
+    if (GTEST_FLAG_GET(shuffle)) {
       // Picks a new random seed for each iteration.
       random_seed_ = GetNextRandomSeed(random_seed_);
     }
@@ -5947,8 +5966,7 @@ void WriteToShardStatusFileIfNeeded() {
 // an error and exits. If in_subprocess_for_death_test, sharding is
 // disabled because it must only be applied to the original test
 // process. Otherwise, we could filter out death tests we intended to execute.
-bool ShouldShard(const char* total_shards_env,
-                 const char* shard_index_env,
+bool ShouldShard(const char* total_shards_env, const char* shard_index_env,
                  bool in_subprocess_for_death_test) {
   if (in_subprocess_for_death_test) {
     return false;
@@ -5960,27 +5978,27 @@ bool ShouldShard(const char* total_shards_env,
   if (total_shards == -1 && shard_index == -1) {
     return false;
   } else if (total_shards == -1 && shard_index != -1) {
-    const Message msg = Message()
-      << "Invalid environment variables: you have "
-      << kTestShardIndex << " = " << shard_index
-      << ", but have left " << kTestTotalShards << " unset.\n";
+    const Message msg = Message() << "Invalid environment variables: you have "
+                                  << kTestShardIndex << " = " << shard_index
+                                  << ", but have left " << kTestTotalShards
+                                  << " unset.\n";
     ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
     fflush(stdout);
     exit(EXIT_FAILURE);
   } else if (total_shards != -1 && shard_index == -1) {
     const Message msg = Message()
-      << "Invalid environment variables: you have "
-      << kTestTotalShards << " = " << total_shards
-      << ", but have left " << kTestShardIndex << " unset.\n";
+                        << "Invalid environment variables: you have "
+                        << kTestTotalShards << " = " << total_shards
+                        << ", but have left " << kTestShardIndex << " unset.\n";
     ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
     fflush(stdout);
     exit(EXIT_FAILURE);
   } else if (shard_index < 0 || shard_index >= total_shards) {
-    const Message msg = Message()
-      << "Invalid environment variables: we require 0 <= "
-      << kTestShardIndex << " < " << kTestTotalShards
-      << ", but you have " << kTestShardIndex << "=" << shard_index
-      << ", " << kTestTotalShards << "=" << total_shards << ".\n";
+    const Message msg =
+        Message() << "Invalid environment variables: we require 0 <= "
+                  << kTestShardIndex << " < " << kTestTotalShards
+                  << ", but you have " << kTestShardIndex << "=" << shard_index
+                  << ", " << kTestTotalShards << "=" << total_shards << ".\n";
     ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
     fflush(stdout);
     exit(EXIT_FAILURE);
@@ -6022,11 +6040,16 @@ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
 // https://github.com/google/googletest/blob/master/googletest/docs/advanced.md
 // . Returns the number of tests that should run.
 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
-  const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
-      Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
-  const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
-      Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
-
+  const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL
+                                   ? Int32FromEnvOrDie(kTestTotalShards, -1)
+                                   : -1;
+  const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL
+                                  ? Int32FromEnvOrDie(kTestShardIndex, -1)
+                                  : -1;
+
+  const PositiveAndNegativeUnitTestFilter gtest_flag_filter(
+      GTEST_FLAG_GET(filter));
+  const UnitTestFilter disable_test_filter(kDisableTestFilter);
   // num_runnable_tests are the number of tests that will
   // run across all shards (i.e., match filter and are not disabled).
   // num_selected_tests are the number of tests to be run on
@@ -6042,18 +6065,17 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
       const std::string test_name(test_info->name());
       // A test is disabled if test suite name or test name matches
       // kDisableTestFilter.
-      const bool is_disabled = internal::UnitTestOptions::MatchesFilter(
-                                   test_suite_name, kDisableTestFilter) ||
-                               internal::UnitTestOptions::MatchesFilter(
-                                   test_name, kDisableTestFilter);
+      const bool is_disabled =
+          disable_test_filter.MatchesName(test_suite_name) ||
+          disable_test_filter.MatchesName(test_name);
       test_info->is_disabled_ = is_disabled;
 
-      const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(
-          test_suite_name, test_name);
+      const bool matches_filter =
+          gtest_flag_filter.MatchesTest(test_suite_name, test_name);
       test_info->matches_filter_ = matches_filter;
 
       const bool is_runnable =
-          (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
+          (GTEST_FLAG_GET(also_run_disabled_tests) || !is_disabled) &&
           matches_filter;
 
       const bool is_in_another_shard =
@@ -6222,8 +6244,8 @@ void UnitTestImpl::UnshuffleTests() {
 // For example, if Foo() calls Bar(), which in turn calls
 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
-std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
-                                            int skip_count) {
+GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_ std::string
+GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, int skip_count) {
   // We pass skip_count + 1 to skip this wrapper function in addition
   // to what the user really wants to skip.
   return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
@@ -6233,7 +6255,7 @@ std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
 // suppress unreachable code warnings.
 namespace {
 class ClassUniqueToAlwaysTrue {};
-}
+}  // namespace
 
 bool IsTrue(bool condition) { return condition; }
 
@@ -6241,8 +6263,7 @@ bool AlwaysTrue() {
 #if GTEST_HAS_EXCEPTIONS
   // This condition is always false so AlwaysTrue() never actually throws,
   // but it makes the compiler think that it may throw.
-  if (IsTrue(false))
-    throw ClassUniqueToAlwaysTrue();
+  if (IsTrue(false)) throw ClassUniqueToAlwaysTrue();
 #endif  // GTEST_HAS_EXCEPTIONS
   return true;
 }
@@ -6264,13 +6285,14 @@ bool SkipPrefix(const char* prefix, const char** pstr) {
 // part can be omitted.
 //
 // Returns the value of the flag, or NULL if the parsing failed.
-static const char* ParseFlagValue(const char* str, const char* flag,
+static const char* ParseFlagValue(const char* str, const char* flag_name,
                                   bool def_optional) {
   // str and flag must not be NULL.
-  if (str == nullptr || flag == nullptr) return nullptr;
+  if (str == nullptr || flag_name == nullptr) return nullptr;
 
   // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
-  const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
+  const std::string flag_str =
+      std::string("--") + GTEST_FLAG_PREFIX_ + flag_name;
   const size_t flag_len = flag_str.length();
   if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;
 
@@ -6301,9 +6323,9 @@ static const char* ParseFlagValue(const char* str, const char* flag,
 //
 // On success, stores the value of the flag in *value, and returns
 // true.  On failure, returns false without changing *value.
-static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
+static bool ParseFlag(const char* str, const char* flag_name, bool* value) {
   // Gets the value of the flag as a string.
-  const char* const value_str = ParseFlagValue(str, flag, true);
+  const char* const value_str = ParseFlagValue(str, flag_name, true);
 
   // Aborts if the parsing failed.
   if (value_str == nullptr) return false;
@@ -6317,16 +6339,16 @@ static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
 //
 // On success, stores the value of the flag in *value, and returns
 // true.  On failure, returns false without changing *value.
-bool ParseInt32Flag(const char* str, const char* flag, int32_t* value) {
+bool ParseFlag(const char* str, const char* flag_name, int32_t* value) {
   // Gets the value of the flag as a string.
-  const char* const value_str = ParseFlagValue(str, flag, false);
+  const char* const value_str = ParseFlagValue(str, flag_name, false);
 
   // Aborts if the parsing failed.
   if (value_str == nullptr) return false;
 
   // Sets *value to the value of the flag.
-  return ParseInt32(Message() << "The value of flag --" << flag,
-                    value_str, value);
+  return ParseInt32(Message() << "The value of flag --" << flag_name, value_str,
+                    value);
 }
 
 // Parses a string for a string flag, in the form of "--flag=value".
@@ -6334,9 +6356,9 @@ bool ParseInt32Flag(const char* str, const char* flag, int32_t* value) {
 // On success, stores the value of the flag in *value, and returns
 // true.  On failure, returns false without changing *value.
 template <typename String>
-static bool ParseStringFlag(const char* str, const char* flag, String* value) {
+static bool ParseFlag(const char* str, const char* flag_name, String* value) {
   // Gets the value of the flag as a string.
-  const char* const value_str = ParseFlagValue(str, flag, false);
+  const char* const value_str = ParseFlagValue(str, flag_name, false);
 
   // Aborts if the parsing failed.
   if (value_str == nullptr) return false;
@@ -6353,8 +6375,7 @@ static bool ParseStringFlag(const char* str, const char* flag, String* value) {
 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
 // internal flags and do not trigger the help message.
 static bool HasGoogleTestFlagPrefix(const char* str) {
-  return (SkipPrefix("--", &str) ||
-          SkipPrefix("-", &str) ||
+  return (SkipPrefix("--", &str) || SkipPrefix("-", &str) ||
           SkipPrefix("/", &str)) &&
          !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
          (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
@@ -6437,6 +6458,10 @@ static const char kColorEncodedHelpMessage[] =
     "random_seed=@Y[NUMBER]@D\n"
     "      Random number seed to use for shuffling test orders (between 1 and\n"
     "      99999, or 0 to use a seed based on the current time).\n"
+    "  @G--" GTEST_FLAG_PREFIX_
+    "recreate_environments_when_repeating@D\n"
+    "      Sets up and tears down the global test environment on each repeat\n"
+    "      of the test.\n"
     "\n"
     "Test Output:\n"
     "  @G--" GTEST_FLAG_PREFIX_
@@ -6454,18 +6479,18 @@ static const char kColorEncodedHelpMessage[] =
     "      Generate a JSON or XML report in the given directory or with the "
     "given\n"
     "      file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
-# if GTEST_CAN_STREAM_RESULTS_
+#if GTEST_CAN_STREAM_RESULTS_
     "  @G--" GTEST_FLAG_PREFIX_
     "stream_result_to=@YHOST@G:@YPORT@D\n"
     "      Stream test results to the given server.\n"
-# endif  // GTEST_CAN_STREAM_RESULTS_
+#endif  // GTEST_CAN_STREAM_RESULTS_
     "\n"
     "Assertion Behavior:\n"
-# if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
+#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
     "  @G--" GTEST_FLAG_PREFIX_
     "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
     "      Set the default death test style.\n"
-# endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
+#endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
     "  @G--" GTEST_FLAG_PREFIX_
     "break_on_failure@D\n"
     "      Turn assertion failures into debugger break-points.\n"
@@ -6497,41 +6522,44 @@ static const char kColorEncodedHelpMessage[] =
     "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
 
 static bool ParseGoogleTestFlag(const char* const arg) {
-  return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
-                       &GTEST_FLAG(also_run_disabled_tests)) ||
-         ParseBoolFlag(arg, kBreakOnFailureFlag,
-                       &GTEST_FLAG(break_on_failure)) ||
-         ParseBoolFlag(arg, kCatchExceptionsFlag,
-                       &GTEST_FLAG(catch_exceptions)) ||
-         ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
-         ParseStringFlag(arg, kDeathTestStyleFlag,
-                         &GTEST_FLAG(death_test_style)) ||
-         ParseBoolFlag(arg, kDeathTestUseFork,
-                       &GTEST_FLAG(death_test_use_fork)) ||
-         ParseBoolFlag(arg, kFailFast, &GTEST_FLAG(fail_fast)) ||
-         ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
-         ParseStringFlag(arg, kInternalRunDeathTestFlag,
-                         &GTEST_FLAG(internal_run_death_test)) ||
-         ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
-         ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
-         ParseBoolFlag(arg, kBriefFlag, &GTEST_FLAG(brief)) ||
-         ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
-         ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
-         ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
-         ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
-         ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
-         ParseInt32Flag(arg, kStackTraceDepthFlag,
-                        &GTEST_FLAG(stack_trace_depth)) ||
-         ParseStringFlag(arg, kStreamResultToFlag,
-                         &GTEST_FLAG(stream_result_to)) ||
-         ParseBoolFlag(arg, kThrowOnFailureFlag, &GTEST_FLAG(throw_on_failure));
+#define GTEST_INTERNAL_PARSE_FLAG(flag_name)  \
+  do {                                        \
+    auto value = GTEST_FLAG_GET(flag_name);   \
+    if (ParseFlag(arg, #flag_name, &value)) { \
+      GTEST_FLAG_SET(flag_name, value);       \
+      return true;                            \
+    }                                         \
+  } while (false)
+
+  GTEST_INTERNAL_PARSE_FLAG(also_run_disabled_tests);
+  GTEST_INTERNAL_PARSE_FLAG(break_on_failure);
+  GTEST_INTERNAL_PARSE_FLAG(catch_exceptions);
+  GTEST_INTERNAL_PARSE_FLAG(color);
+  GTEST_INTERNAL_PARSE_FLAG(death_test_style);
+  GTEST_INTERNAL_PARSE_FLAG(death_test_use_fork);
+  GTEST_INTERNAL_PARSE_FLAG(fail_fast);
+  GTEST_INTERNAL_PARSE_FLAG(filter);
+  GTEST_INTERNAL_PARSE_FLAG(internal_run_death_test);
+  GTEST_INTERNAL_PARSE_FLAG(list_tests);
+  GTEST_INTERNAL_PARSE_FLAG(output);
+  GTEST_INTERNAL_PARSE_FLAG(brief);
+  GTEST_INTERNAL_PARSE_FLAG(print_time);
+  GTEST_INTERNAL_PARSE_FLAG(print_utf8);
+  GTEST_INTERNAL_PARSE_FLAG(random_seed);
+  GTEST_INTERNAL_PARSE_FLAG(repeat);
+  GTEST_INTERNAL_PARSE_FLAG(recreate_environments_when_repeating);
+  GTEST_INTERNAL_PARSE_FLAG(shuffle);
+  GTEST_INTERNAL_PARSE_FLAG(stack_trace_depth);
+  GTEST_INTERNAL_PARSE_FLAG(stream_result_to);
+  GTEST_INTERNAL_PARSE_FLAG(throw_on_failure);
+  return false;
 }
 
 #if GTEST_USE_OWN_FLAGFILE_FLAG_
 static void LoadFlagsFromFile(const std::string& path) {
   FILE* flagfile = posix::FOpen(path.c_str(), "r");
   if (!flagfile) {
-    GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile)
+    GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG_GET(flagfile)
                       << "\"";
   }
   std::string contents(ReadEntireFile(flagfile));
@@ -6539,10 +6567,8 @@ static void LoadFlagsFromFile(const std::string& path) {
   std::vector<std::string> lines;
   SplitString(contents, '\n', &lines);
   for (size_t i = 0; i < lines.size(); ++i) {
-    if (lines[i].empty())
-      continue;
-    if (!ParseGoogleTestFlag(lines[i].c_str()))
-      g_help_flag = true;
+    if (lines[i].empty()) continue;
+    if (!ParseGoogleTestFlag(lines[i].c_str())) g_help_flag = true;
   }
 }
 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
@@ -6552,25 +6578,23 @@ static void LoadFlagsFromFile(const std::string& path) {
 // instantiated to either char or wchar_t.
 template <typename CharType>
 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
+  std::string flagfile_value;
   for (int i = 1; i < *argc; i++) {
     const std::string arg_string = StreamableToString(argv[i]);
     const char* const arg = arg_string.c_str();
 
-    using internal::ParseBoolFlag;
-    using internal::ParseInt32Flag;
-    using internal::ParseStringFlag;
+    using internal::ParseFlag;
 
     bool remove_flag = false;
     if (ParseGoogleTestFlag(arg)) {
       remove_flag = true;
 #if GTEST_USE_OWN_FLAGFILE_FLAG_
-    } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {
-      LoadFlagsFromFile(GTEST_FLAG(flagfile));
+    } else if (ParseFlag(arg, "flagfile", &flagfile_value)) {
+      GTEST_FLAG_SET(flagfile, flagfile_value);
+      LoadFlagsFromFile(flagfile_value);
       remove_flag = true;
 #endif  // GTEST_USE_OWN_FLAGFILE_FLAG_
-    } else if (arg_string == "--help" || arg_string == "-h" ||
-               arg_string == "-?" || arg_string == "/?" ||
-               HasGoogleTestFlagPrefix(arg)) {
+    } else if (arg_string == "--help" || HasGoogleTestFlagPrefix(arg)) {
       // Both help flag and unrecognized Google Test flags (excluding
       // internal ones) trigger help display.
       g_help_flag = true;
@@ -6605,7 +6629,27 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
 // Parses the command line for Google Test flags, without initializing
 // other parts of Google Test.
 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
+#if GTEST_HAS_ABSL
+  if (*argc > 0) {
+    // absl::ParseCommandLine() requires *argc > 0.
+    auto positional_args = absl::flags_internal::ParseCommandLineImpl(
+        *argc, argv, absl::flags_internal::ArgvListAction::kRemoveParsedArgs,
+        absl::flags_internal::UsageFlagsAction::kHandleUsage,
+        absl::flags_internal::OnUndefinedFlag::kReportUndefined);
+    // Any command-line positional arguments not part of any command-line flag
+    // (or arguments to a flag) are copied back out to argv, with the program
+    // invocation name at position 0, and argc is resized. This includes
+    // positional arguments after the flag-terminating delimiter '--'.
+    // See https://abseil.io/docs/cpp/guides/flags.
+    std::copy(positional_args.begin(), positional_args.end(), argv);
+    if (static_cast<int>(positional_args.size()) < *argc) {
+      argv[positional_args.size()] = nullptr;
+      *argc = static_cast<int>(positional_args.size());
+    }
+  }
+#else
   ParseGoogleTestFlagsOnlyImpl(argc, argv);
+#endif
 
   // Fix the value of *_NSGetArgc() on macOS, but if and only if
   // *_NSGetArgv() == argv
@@ -6640,6 +6684,12 @@ void InitGoogleTestImpl(int* argc, CharType** argv) {
 
 #if GTEST_HAS_ABSL
   absl::InitializeSymbolizer(g_argvs[0].c_str());
+
+  // When using the Abseil Flags library, set the program usage message to the
+  // help message, but remove the color-encoding from the message first.
+  absl::SetProgramUsageMessage(absl::StrReplaceAll(
+      kColorEncodedHelpMessage,
+      {{"@D", ""}, {"@R", ""}, {"@G", ""}, {"@Y", ""}, {"@@", "@"}}));
 #endif  // GTEST_HAS_ABSL
 
   ParseGoogleTestFlagsOnly(argc, argv);
@@ -6660,7 +6710,7 @@ void InitGoogleTestImpl(int* argc, CharType** argv) {
 void InitGoogleTest(int* argc, char** argv) {
 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
-#else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
+#else   // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
   internal::InitGoogleTestImpl(argc, argv);
 #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
 }
@@ -6670,7 +6720,7 @@ void InitGoogleTest(int* argc, char** argv) {
 void InitGoogleTest(int* argc, wchar_t** argv) {
 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
-#else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
+#else   // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
   internal::InitGoogleTestImpl(argc, argv);
 #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
 }
@@ -6686,42 +6736,42 @@ void InitGoogleTest() {
 
 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
   GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);
-#else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
+#else   // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
   internal::InitGoogleTestImpl(&argc, argv);
 #endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
 }
 
+#if !defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
+// Return value of first environment variable that is set and contains
+// a non-empty string. If there are none, return the "fallback" string.
+// Since we like the temporary directory to have a directory separator suffix,
+// add it if not provided in the environment variable value.
+static std::string GetTempDirFromEnv(
+    std::initializer_list<const char*> environment_variables,
+    const char* fallback, char separator) {
+  for (const char* variable_name : environment_variables) {
+    const char* value = internal::posix::GetEnv(variable_name);
+    if (value != nullptr && value[0] != '\0') {
+      if (value[strlen(value) - 1] != separator) {
+        return std::string(value).append(1, separator);
+      }
+      return value;
+    }
+  }
+  return fallback;
+}
+#endif
+
 std::string TempDir() {
 #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
   return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
-#elif GTEST_OS_WINDOWS_MOBILE
-  return "\\temp\\";
-#elif GTEST_OS_WINDOWS
-  const char* temp_dir = internal::posix::GetEnv("TEMP");
-  if (temp_dir == nullptr || 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_WINDOWS || GTEST_OS_WINDOWS_MOBILE
+  return GetTempDirFromEnv({"TEST_TMPDIR", "TEMP"}, "\\temp\\", '\\');
 #elif GTEST_OS_LINUX_ANDROID
-  const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR");
-  if (temp_dir == nullptr || temp_dir[0] == '\0') {
-    return "/data/local/tmp/";
-  } else {
-    return temp_dir;
-  }
-#elif GTEST_OS_LINUX
-  const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR");
-  if (temp_dir == nullptr || temp_dir[0] == '\0') {
-    return "/tmp/";
-  } else {
-    return temp_dir;
-  }
+  return GetTempDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/data/local/tmp/", '/');
 #else
-  return "/tmp/";
-#endif  // GTEST_OS_WINDOWS_MOBILE
+  return GetTempDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/tmp/", '/');
+#endif
 }
 
 // Class ScopedTrace
@@ -6738,8 +6788,7 @@ void ScopedTrace::PushTrace(const char* file, int line, std::string message) {
 }
 
 // Pops the info pushed by the c'tor.
-ScopedTrace::~ScopedTrace()
-    GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
+ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
   UnitTest::GetInstance()->PopGTestTrace();
 }
 
index 46b27c3d7d5654668906bff5f5ba1a266881f77b..44976375c997bc157fae8137f0ee6b02136112c7 100644 (file)
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 #include <cstdio>
+
 #include "gtest/gtest.h"
 
 #if GTEST_OS_ESP8266 || GTEST_OS_ESP32
 #if GTEST_OS_ESP8266
 extern "C" {
 #endif
-void setup() {
-  testing::InitGoogleTest();
-}
+void setup() { testing::InitGoogleTest(); }
 
 void loop() { RUN_ALL_TESTS(); }
 
index b06a00a106fdd3f3a1ecf506c59ed3648764ab2d..7754c1303fc00eb606f3ddf9c3eb607f7d608a14 100644 (file)
@@ -30,7 +30,6 @@
 #
 # Bazel BUILD for The Google C++ Testing Framework (Google Test)
 
-load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test")
 load("@rules_python//python:defs.bzl", "py_library", "py_test")
 
 licenses(["notice"])
@@ -95,6 +94,7 @@ cc_test(
         "googletest/test",
     ],
     linkopts = select({
+        "//:qnx": [],
         "//:windows": [],
         "//conditions:default": ["-pthread"],
     }),
@@ -174,6 +174,10 @@ py_test(
     name = "gtest_help_test",
     size = "small",
     srcs = ["gtest_help_test.py"],
+    args = select({
+        "//:has_absl": ["--has_absl_flags"],
+        "//conditions:default": [],
+    }),
     data = [":gtest_help_test_"],
     deps = [":gtest_test_utils"],
 )
index a5dfbc693b43a1b19e3847dcbcab886d2f4d28e6..4eafba3e6bb46dfe5f3b07ce1be7b68325430105 100755 (executable)
@@ -39,7 +39,7 @@ Google Test) with different environments and command line flags.
 """
 
 import os
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 # Constants.
 
index f84957a2d03b56260c8e2c0ae8f5a27beb6f6378..324294f33ec7a2b8ad8cbcc608e6aa2dea252d58 100644 (file)
@@ -27,7 +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.
 
-
 // Unit test for Google Test's break-on-failure mode.
 //
 // A user can ask Google Test to seg-fault when an assertion fails, using
 #include "gtest/gtest.h"
 
 #if GTEST_OS_WINDOWS
-# include <windows.h>
-# include <stdlib.h>
+#include <stdlib.h>
+#include <windows.h>
 #endif
 
 namespace {
 
 // A test that's expected to fail.
-TEST(Foo, Bar) {
-  EXPECT_EQ(2, 3);
-}
+TEST(Foo, Bar) { EXPECT_EQ(2, 3); }
 
 #if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE
 // On Windows Mobile global exception handlers are not supported.
-LONG WINAPI ExitWithExceptionCode(
-    struct _EXCEPTION_POINTERS* exception_pointers) {
+LONG WINAPI
+ExitWithExceptionCode(struct _EXCEPTION_POINTERS* exception_pointers) {
   exit(exception_pointers->ExceptionRecord->ExceptionCode);
 }
 #endif
 
 }  // namespace
 
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
 #if GTEST_OS_WINDOWS
   // Suppresses display of the Windows error dialog upon encountering
   // a general protection fault (segment violation).
   SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
 
-# if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE
+#if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE
 
   // The default unhandled exception filter does not always exit
   // with the exception code as exit code - for example it exits with
@@ -78,7 +75,7 @@ int main(int argc, char **argv) {
   // exceptions.
   SetUnhandledExceptionFilter(ExitWithExceptionCode);
 
-# endif
+#endif
 #endif  // GTEST_OS_WINDOWS
   testing::InitGoogleTest(&argc, argv);
 
index 94a5b33f2305092593755c3ab86aa5f6c329e2a0..d38d91a62a43cb1a0bce169c4b747dbbf042d6d6 100755 (executable)
@@ -35,7 +35,7 @@ googletest-catch-exceptions-ex-test_ (programs written with
 Google Test) and verifies their output.
 """
 
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 # Constants.
 FLAG_PREFIX = '--gtest_'
@@ -147,19 +147,19 @@ class CatchCxxExceptionsTest(gtest_test_utils.TestCase):
     self.assertTrue(
         'CxxExceptionInConstructorTest::TearDownTestSuite() '
         'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
-    self.assertTrue(
+    self.assertFalse(
         'CxxExceptionInSetUpTestSuiteTest constructor '
         'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
-    self.assertTrue(
+    self.assertFalse(
         'CxxExceptionInSetUpTestSuiteTest destructor '
         'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
-    self.assertTrue(
+    self.assertFalse(
         'CxxExceptionInSetUpTestSuiteTest::SetUp() '
         'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
-    self.assertTrue(
+    self.assertFalse(
         'CxxExceptionInSetUpTestSuiteTest::TearDown() '
         'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
-    self.assertTrue(
+    self.assertFalse(
         'CxxExceptionInSetUpTestSuiteTest test body '
         'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)
 
index 8c127d40b11d4d72a3faae80bafbb746d1aa4128..3c8f4f4b790cf063897c9b9cd1b11806dedd8167 100644 (file)
 // exceptions, and the output is verified by
 // googletest-catch-exceptions-test.py.
 
-#include <stdio.h>  // NOLINT
+#include <stdio.h>   // NOLINT
 #include <stdlib.h>  // For exit().
 
 #include "gtest/gtest.h"
 
 #if GTEST_HAS_SEH
-# include <windows.h>
+#include <windows.h>
 #endif
 
 #if GTEST_HAS_EXCEPTIONS
-# include <exception>  // For set_terminate().
-# include <stdexcept>
+#include <exception>  // For set_terminate().
+#include <stdexcept>
 #endif
 
 using testing::Test;
@@ -93,9 +93,7 @@ class SehExceptionInTearDownTest : public Test {
 
 TEST_F(SehExceptionInTearDownTest, ThrowsExceptionInTearDown) {}
 
-TEST(SehExceptionTest, ThrowsSehException) {
-  RaiseException(42, 0, 0, NULL);
-}
+TEST(SehExceptionTest, ThrowsSehException) { RaiseException(42, 0, 0, NULL); }
 
 #endif  // GTEST_HAS_SEH
 
@@ -269,9 +267,7 @@ TEST_F(CxxExceptionInTestBodyTest, ThrowsStdCxxException) {
   throw std::runtime_error("Standard C++ exception");
 }
 
-TEST(CxxExceptionTest, ThrowsNonStdCxxException) {
-  throw "C-string";
-}
+TEST(CxxExceptionTest, ThrowsNonStdCxxException) { throw "C-string"; }
 
 // This terminate handler aborts the program using exit() rather than abort().
 // This avoids showing pop-ups on Windows systems and core dumps on Unix-like
index f3b7c9990bcf44a65036c253e7a01845af9c3717..c22752db82a3e70318bb75beae9e7cb14b2f5807 100755 (executable)
@@ -32,7 +32,7 @@
 """Verifies that Google Test correctly determines whether to use colors."""
 
 import os
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 IS_WINDOWS = os.name == 'nt'
 
index 220a3a00548fdb1e935a3da16df563a50e179a8a..55657b7262b6ba8fd65b76cfe9d8b707304e64a8 100644 (file)
@@ -27,7 +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.
 
-
 // A helper program for testing how Google Test determines whether to use
 // colors in the output.  It prints "YES" and returns 1 if Google Test
 // decides to use colors, and prints "NO" and returns 0 otherwise.
@@ -43,8 +42,7 @@ using testing::internal::ShouldUseColor;
 // created before main() is entered, and thus that ShouldUseColor()
 // works the same way as in a real Google-Test-based test.  We don't actual
 // run the TEST itself.
-TEST(GTestColorTest, Dummy) {
-}
+TEST(GTestColorTest, Dummy) {}
 
 int main(int argc, char** argv) {
   testing::InitGoogleTest(&argc, argv);
index c0b3d1f21d04d3de77803836704cb7f47d2adfe9..4737ff9bfb6b7f8563eb0c23ca564e02b4d0fd45 100644 (file)
@@ -31,7 +31,6 @@
 // Tests for death tests.
 
 #include "gtest/gtest-death-test.h"
-
 #include "gtest/gtest.h"
 #include "gtest/internal/gtest-filepath.h"
 
@@ -40,25 +39,25 @@ using testing::internal::AlwaysTrue;
 
 #if GTEST_HAS_DEATH_TEST
 
-# if GTEST_OS_WINDOWS
-#  include <fcntl.h>           // For O_BINARY
-#  include <direct.h>          // For chdir().
-#  include <io.h>
-# else
-#  include <unistd.h>
-#  include <sys/wait.h>        // For waitpid.
-# endif  // GTEST_OS_WINDOWS
+#if GTEST_OS_WINDOWS
+#include <direct.h>  // For chdir().
+#include <fcntl.h>   // For O_BINARY
+#include <io.h>
+#else
+#include <sys/wait.h>  // For waitpid.
+#include <unistd.h>
+#endif  // GTEST_OS_WINDOWS
 
-# include <limits.h>
-# include <signal.h>
-# include <stdio.h>
+#include <limits.h>
+#include <signal.h>
+#include <stdio.h>
 
-# if GTEST_OS_LINUX
-#  include <sys/time.h>
-# endif  // GTEST_OS_LINUX
+#if GTEST_OS_LINUX
+#include <sys/time.h>
+#endif  // GTEST_OS_LINUX
 
-# include "gtest/gtest-spi.h"
-# include "src/gtest-internal-inl.h"
+#include "gtest/gtest-spi.h"
+#include "src/gtest-internal-inl.h"
 
 namespace posix = ::testing::internal::posix;
 
@@ -90,6 +89,7 @@ class ReplaceDeathTestFactory {
     unit_test_impl_->death_test_factory_.release();
     unit_test_impl_->death_test_factory_.reset(old_factory_);
   }
+
  private:
   // Prevents copying ReplaceDeathTestFactory objects.
   ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
@@ -116,8 +116,7 @@ void DieWithMessage(const ::std::string& message) {
   // Some compilers can recognize that _exit() never returns and issue the
   // 'unreachable code' warning for code following this function, unless
   // fooled by a fake condition.
-  if (AlwaysTrue())
-    _exit(1);
+  if (AlwaysTrue()) _exit(1);
 }
 
 void DieInside(const ::std::string& function) {
@@ -137,8 +136,7 @@ class TestForDeathTest : public testing::Test {
 
   // A method of the test fixture that may die.
   void MemberFunction() {
-    if (should_die_)
-      DieInside("MemberFunction");
+    if (should_die_) DieInside("MemberFunction");
   }
 
   // True if and only if MemberFunction() should die.
@@ -153,8 +151,7 @@ class MayDie {
 
   // A member function that may die.
   void MemberFunction() const {
-    if (should_die_)
-      DieInside("MayDie::MemberFunction");
+    if (should_die_) DieInside("MayDie::MemberFunction");
   }
 
  private:
@@ -173,8 +170,7 @@ int NonVoidFunction() {
 
 // A unary function that may die.
 void DieIf(bool should_die) {
-  if (should_die)
-    DieInside("DieIf");
+  if (should_die) DieInside("DieIf");
 }
 
 // A binary function that may die.
@@ -195,16 +191,16 @@ void DeathTestSubroutine() {
 int DieInDebugElse12(int* sideeffect) {
   if (sideeffect) *sideeffect = 12;
 
-# ifndef NDEBUG
+#ifndef NDEBUG
 
   DieInside("DieInDebugElse12");
 
-# endif  // NDEBUG
+#endif  // NDEBUG
 
   return 12;
 }
 
-# if GTEST_OS_WINDOWS
+#if GTEST_OS_WINDOWS
 
 // Death in dbg due to Windows CRT assertion failure, not opt.
 int DieInCRTDebugElse12(int* sideeffect) {
@@ -224,7 +220,7 @@ int DieInCRTDebugElse12(int* sideeffect) {
 
 #endif  // GTEST_OS_WINDOWS
 
-# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
+#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
 
 // Tests the ExitedWithCode predicate.
 TEST(ExitStatusPredicateTest, ExitedWithCode) {
@@ -237,7 +233,7 @@ TEST(ExitStatusPredicateTest, ExitedWithCode) {
   EXPECT_FALSE(testing::ExitedWithCode(1)(0));
 }
 
-# else
+#else
 
 // Returns the exit status of a process that calls _exit(2) with a
 // given exit code.  This is a helper function for the
@@ -270,14 +266,14 @@ static int KilledExitStatus(int signum) {
 
 // Tests the ExitedWithCode predicate.
 TEST(ExitStatusPredicateTest, ExitedWithCode) {
-  const int status0  = NormalExitStatus(0);
-  const int status1  = NormalExitStatus(1);
+  const int status0 = NormalExitStatus(0);
+  const int status1 = NormalExitStatus(1);
   const int status42 = NormalExitStatus(42);
   const testing::ExitedWithCode pred0(0);
   const testing::ExitedWithCode pred1(1);
   const testing::ExitedWithCode pred42(42);
-  EXPECT_PRED1(pred0,  status0);
-  EXPECT_PRED1(pred1,  status1);
+  EXPECT_PRED1(pred0, status0);
+  EXPECT_PRED1(pred1, status1);
   EXPECT_PRED1(pred42, status42);
   EXPECT_FALSE(pred0(status1));
   EXPECT_FALSE(pred42(status0));
@@ -296,7 +292,7 @@ TEST(ExitStatusPredicateTest, KilledBySignal) {
   EXPECT_FALSE(pred_kill(status_segv));
 }
 
-# endif  // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
+#endif  // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
 
 // The following code intentionally tests a suboptimal syntax.
 #ifdef __GNUC__
@@ -320,8 +316,7 @@ TEST_F(TestForDeathTest, SingleStatement) {
     // doesn't expand into an "if" statement without an "else"
     ;
 
-  if (AlwaysFalse())
-    ASSERT_DEATH(return, "") << "did not die";
+  if (AlwaysFalse()) ASSERT_DEATH(return, "") << "did not die";
 
   if (AlwaysFalse())
     ;
@@ -332,7 +327,7 @@ TEST_F(TestForDeathTest, SingleStatement) {
 #pragma GCC diagnostic pop
 #endif
 
-# if GTEST_USES_PCRE
+#if GTEST_USES_PCRE
 
 void DieWithEmbeddedNul() {
   fprintf(stderr, "Hello%cmy null world.\n", '\0');
@@ -347,7 +342,7 @@ TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
   ASSERT_DEATH(DieWithEmbeddedNul(), "my null world");
 }
 
-# endif  // GTEST_USES_PCRE
+#endif  // GTEST_USES_PCRE
 
 // Tests that death test macros expand to code which interacts well with switch
 // statements.
@@ -357,12 +352,12 @@ TEST_F(TestForDeathTest, SwitchStatement) {
   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
 
   switch (0)
-    default:
-      ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
+  default:
+    ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
 
   switch (0)
-    case 0:
-      EXPECT_DEATH(_exit(1), "") << "exit in switch case";
+  case 0:
+    EXPECT_DEATH(_exit(1), "") << "exit in switch case";
 
   GTEST_DISABLE_MSC_WARNINGS_POP_()
 }
@@ -370,14 +365,14 @@ TEST_F(TestForDeathTest, SwitchStatement) {
 // Tests that a static member function can be used in a "fast" style
 // death test.
 TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) {
-  testing::GTEST_FLAG(death_test_style) = "fast";
+  GTEST_FLAG_SET(death_test_style, "fast");
   ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
 }
 
 // Tests that a method of the test fixture can be used in a "fast"
 // style death test.
 TEST_F(TestForDeathTest, MemberFunctionFastStyle) {
-  testing::GTEST_FLAG(death_test_style) = "fast";
+  GTEST_FLAG_SET(death_test_style, "fast");
   should_die_ = true;
   EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
 }
@@ -387,7 +382,7 @@ void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); }
 // Tests that death tests work even if the current directory has been
 // changed.
 TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
-  testing::GTEST_FLAG(death_test_style) = "fast";
+  GTEST_FLAG_SET(death_test_style, "fast");
 
   ChangeToRootDir();
   EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
@@ -396,8 +391,9 @@ TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
   ASSERT_DEATH(_exit(1), "");
 }
 
-# if GTEST_OS_LINUX
-void SigprofAction(int, siginfo_t*, void*) { /* no op */ }
+#if GTEST_OS_LINUX
+void SigprofAction(int, siginfo_t*, void*) { /* no op */
+}
 
 // Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
 void SetSigprofActionAndTimer() {
@@ -432,7 +428,7 @@ void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) {
 
 // Tests that death tests work when SIGPROF handler and timer are set.
 TEST_F(TestForDeathTest, FastSigprofActionSet) {
-  testing::GTEST_FLAG(death_test_style) = "fast";
+  GTEST_FLAG_SET(death_test_style, "fast");
   SetSigprofActionAndTimer();
   EXPECT_DEATH(_exit(1), "");
   struct sigaction old_signal_action;
@@ -441,37 +437,37 @@ TEST_F(TestForDeathTest, FastSigprofActionSet) {
 }
 
 TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) {
-  testing::GTEST_FLAG(death_test_style) = "threadsafe";
+  GTEST_FLAG_SET(death_test_style, "threadsafe");
   SetSigprofActionAndTimer();
   EXPECT_DEATH(_exit(1), "");
   struct sigaction old_signal_action;
   DisableSigprofActionAndTimer(&old_signal_action);
   EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
 }
-# endif  // GTEST_OS_LINUX
+#endif  // GTEST_OS_LINUX
 
 // Repeats a representative sample of death tests in the "threadsafe" style:
 
 TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
-  testing::GTEST_FLAG(death_test_style) = "threadsafe";
+  GTEST_FLAG_SET(death_test_style, "threadsafe");
   ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
 }
 
 TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
-  testing::GTEST_FLAG(death_test_style) = "threadsafe";
+  GTEST_FLAG_SET(death_test_style, "threadsafe");
   should_die_ = true;
   EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
 }
 
 TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {
-  testing::GTEST_FLAG(death_test_style) = "threadsafe";
+  GTEST_FLAG_SET(death_test_style, "threadsafe");
 
   for (int i = 0; i < 3; ++i)
     EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i;
 }
 
 TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {
-  testing::GTEST_FLAG(death_test_style) = "threadsafe";
+  GTEST_FLAG_SET(death_test_style, "threadsafe");
 
   ChangeToRootDir();
   EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
@@ -481,23 +477,21 @@ TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {
 }
 
 TEST_F(TestForDeathTest, MixedStyles) {
-  testing::GTEST_FLAG(death_test_style) = "threadsafe";
+  GTEST_FLAG_SET(death_test_style, "threadsafe");
   EXPECT_DEATH(_exit(1), "");
-  testing::GTEST_FLAG(death_test_style) = "fast";
+  GTEST_FLAG_SET(death_test_style, "fast");
   EXPECT_DEATH(_exit(1), "");
 }
 
-# if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
+#if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
 
 bool pthread_flag;
 
-void SetPthreadFlag() {
-  pthread_flag = true;
-}
+void SetPthreadFlag() { pthread_flag = true; }
 
 TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
-  if (!testing::GTEST_FLAG(death_test_use_fork)) {
-    testing::GTEST_FLAG(death_test_style) = "threadsafe";
+  if (!GTEST_FLAG_GET(death_test_use_fork)) {
+    GTEST_FLAG_SET(death_test_style, "threadsafe");
     pthread_flag = false;
     ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, nullptr, nullptr));
     ASSERT_DEATH(_exit(1), "");
@@ -505,7 +499,7 @@ TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
   }
 }
 
-# endif  // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
+#endif  // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
 
 // Tests that a method of another class can be used in a death test.
 TEST_F(TestForDeathTest, MethodOfAnotherClass) {
@@ -527,7 +521,7 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
   const testing::internal::RE regex(regex_c_str);
   EXPECT_DEATH(GlobalFunction(), regex);
 
-# if !GTEST_USES_PCRE
+#if !GTEST_USES_PCRE
 
   const ::std::string regex_std_str(regex_c_str);
   EXPECT_DEATH(GlobalFunction(), regex_std_str);
@@ -536,7 +530,7 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
   // lifetime extension of the pointer is not sufficient.
   EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str());
 
-# endif  // !GTEST_USES_PCRE
+#endif  // !GTEST_USES_PCRE
 }
 
 // Tests that a non-void function can be used in a death test.
@@ -551,9 +545,7 @@ TEST_F(TestForDeathTest, FunctionWithParameter) {
 }
 
 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
-TEST_F(TestForDeathTest, OutsideFixture) {
-  DeathTestSubroutine();
-}
+TEST_F(TestForDeathTest, OutsideFixture) { DeathTestSubroutine(); }
 
 // Tests that death tests can be done inside a loop.
 TEST_F(TestForDeathTest, InsideLoop) {
@@ -564,25 +556,28 @@ TEST_F(TestForDeathTest, InsideLoop) {
 
 // Tests that a compound statement can be used in a death test.
 TEST_F(TestForDeathTest, CompoundStatement) {
-  EXPECT_DEATH({  // NOLINT
-    const int x = 2;
-    const int y = x + 1;
-    DieIfLessThan(x, y);
-  },
-  "DieIfLessThan");
+  EXPECT_DEATH(
+      {  // NOLINT
+        const int x = 2;
+        const int y = x + 1;
+        DieIfLessThan(x, y);
+      },
+      "DieIfLessThan");
 }
 
 // Tests that code that doesn't die causes a death test to fail.
 TEST_F(TestForDeathTest, DoesNotDie) {
-  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"),
-                          "failed to die");
+  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"), "failed to die");
 }
 
 // Tests that a death test fails when the error message isn't expected.
 TEST_F(TestForDeathTest, ErrorMessageMismatch) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message.";
-  }, "died but not with expected error");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_DEATH(DieIf(true), "DieIfLessThan")
+            << "End of death test message.";
+      },
+      "died but not with expected error");
 }
 
 // On exit, *aborted will be true if and only if the EXPECT_DEATH()
@@ -596,19 +591,20 @@ void ExpectDeathTestHelper(bool* aborted) {
 // Tests that EXPECT_DEATH doesn't abort the test on failure.
 TEST_F(TestForDeathTest, EXPECT_DEATH) {
   bool aborted = true;
-  EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted),
-                          "failed to die");
+  EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), "failed to die");
   EXPECT_FALSE(aborted);
 }
 
 // Tests that ASSERT_DEATH does abort the test on failure.
 TEST_F(TestForDeathTest, ASSERT_DEATH) {
   static bool aborted;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    aborted = true;
-    ASSERT_DEATH(DieIf(false), "DieIf");  // This assertion should fail.
-    aborted = false;
-  }, "failed to die");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        aborted = true;
+        ASSERT_DEATH(DieIf(false), "DieIf");  // This assertion should fail.
+        aborted = false;
+      },
+      "failed to die");
   EXPECT_TRUE(aborted);
 }
 
@@ -653,52 +649,36 @@ TEST_F(TestForDeathTest, TestExpectDebugDeath) {
   EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex)
       << "Must accept a streamed message";
 
-# ifdef NDEBUG
+#ifdef NDEBUG
 
   // Checks that the assignment occurs in opt mode (sideeffect).
   EXPECT_EQ(12, sideeffect);
 
-# else
+#else
 
   // Checks that the assignment does not occur in dbg mode (no sideeffect).
   EXPECT_EQ(0, sideeffect);
 
-# endif
+#endif
 }
 
-# if GTEST_OS_WINDOWS
+#if GTEST_OS_WINDOWS
 
-// Tests that EXPECT_DEBUG_DEATH works as expected when in debug mode
-// the Windows CRT crashes the process with an assertion failure.
+// https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/crtsetreportmode
+// In debug mode, the calls to _CrtSetReportMode and _CrtSetReportFile enable
+// the dumping of assertions to stderr. Tests that EXPECT_DEATH works as
+// expected when in CRT debug mode (compiled with /MTd or /MDd, which defines
+// _DEBUG) the Windows CRT crashes the process with an assertion failure.
 // 1. Asserts on death.
 // 2. Has no side effect (doesn't pop up a window or wait for user input).
-//
-// And in opt mode, it:
-// 1.  Has side effects but does not assert.
+#ifdef _DEBUG
 TEST_F(TestForDeathTest, CRTDebugDeath) {
-  int sideeffect = 0;
-
-  // Put the regex in a local variable to make sure we don't get an "unused"
-  // warning in opt mode.
-  const char* regex = "dup.* : Assertion failed";
-
-  EXPECT_DEBUG_DEATH(DieInCRTDebugElse12(&sideeffect), regex)
+  EXPECT_DEATH(DieInCRTDebugElse12(nullptr), "dup.* : Assertion failed")
       << "Must accept a streamed message";
-
-# ifdef NDEBUG
-
-  // Checks that the assignment occurs in opt mode (sideeffect).
-  EXPECT_EQ(12, sideeffect);
-
-# else
-
-  // Checks that the assignment does not occur in dbg mode (no sideeffect).
-  EXPECT_EQ(0, sideeffect);
-
-# endif
 }
+#endif  // _DEBUG
 
-# endif  // GTEST_OS_WINDOWS
+#endif  // GTEST_OS_WINDOWS
 
 // Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a
 // message to it, and in debug mode it:
@@ -713,20 +693,20 @@ TEST_F(TestForDeathTest, TestAssertDebugDeath) {
   ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
       << "Must accept a streamed message";
 
-# ifdef NDEBUG
+#ifdef NDEBUG
 
   // Checks that the assignment occurs in opt mode (sideeffect).
   EXPECT_EQ(12, sideeffect);
 
-# else
+#else
 
   // Checks that the assignment does not occur in dbg mode (no sideeffect).
   EXPECT_EQ(0, sideeffect);
 
-# endif
+#endif
 }
 
-# ifndef NDEBUG
+#ifndef NDEBUG
 
 void ExpectDebugDeathHelper(bool* aborted) {
   *aborted = true;
@@ -734,18 +714,21 @@ void ExpectDebugDeathHelper(bool* aborted) {
   *aborted = false;
 }
 
-#  if GTEST_OS_WINDOWS
+#if GTEST_OS_WINDOWS
 TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
-  printf("This test should be considered failing if it shows "
-         "any pop-up dialogs.\n");
+  printf(
+      "This test should be considered failing if it shows "
+      "any pop-up dialogs.\n");
   fflush(stdout);
 
-  EXPECT_DEATH({
-    testing::GTEST_FLAG(catch_exceptions) = false;
-    abort();
-  }, "");
+  EXPECT_DEATH(
+      {
+        GTEST_FLAG_SET(catch_exceptions, false);
+        abort();
+      },
+      "");
 }
-#  endif  // GTEST_OS_WINDOWS
+#endif  // GTEST_OS_WINDOWS
 
 // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
 // the function.
@@ -836,83 +819,86 @@ TEST_F(TestForDeathTest, AssertDebugDeathAborts10) {
   EXPECT_TRUE(aborted);
 }
 
-# endif  // _NDEBUG
+#endif  // _NDEBUG
 
 // Tests the *_EXIT family of macros, using a variety of predicates.
 static void TestExitMacros() {
-  EXPECT_EXIT(_exit(1),  testing::ExitedWithCode(1),  "");
+  EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
   ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
 
-# if GTEST_OS_WINDOWS
+#if GTEST_OS_WINDOWS
 
   // Of all signals effects on the process exit code, only those of SIGABRT
   // are documented on Windows.
   // See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c.
   EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar";
 
-# elif !GTEST_OS_FUCHSIA
+#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";
 
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
-      << "This failure is expected, too.";
-  }, "This failure is expected, too.");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
+            << "This failure is expected, too.";
+      },
+      "This failure is expected, too.");
 
-# endif  // GTEST_OS_WINDOWS
+#endif  // GTEST_OS_WINDOWS
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
-      << "This failure is expected.";
-  }, "This failure is expected.");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
+            << "This failure is expected.";
+      },
+      "This failure is expected.");
 }
 
-TEST_F(TestForDeathTest, ExitMacros) {
-  TestExitMacros();
-}
+TEST_F(TestForDeathTest, ExitMacros) { TestExitMacros(); }
 
 TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
-  testing::GTEST_FLAG(death_test_use_fork) = true;
+  GTEST_FLAG_SET(death_test_use_fork, true);
   TestExitMacros();
 }
 
 TEST_F(TestForDeathTest, InvalidStyle) {
-  testing::GTEST_FLAG(death_test_style) = "rococo";
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
-  }, "This failure is expected.");
+  GTEST_FLAG_SET(death_test_style, "rococo");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
+      },
+      "This failure is expected.");
 }
 
 TEST_F(TestForDeathTest, DeathTestFailedOutput) {
-  testing::GTEST_FLAG(death_test_style) = "fast";
+  GTEST_FLAG_SET(death_test_style, "fast");
   EXPECT_NONFATAL_FAILURE(
-      EXPECT_DEATH(DieWithMessage("death\n"),
-                   "expected message"),
+      EXPECT_DEATH(DieWithMessage("death\n"), "expected message"),
       "Actual msg:\n"
       "[  DEATH   ] death\n");
 }
 
 TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
-  testing::GTEST_FLAG(death_test_style) = "fast";
-  EXPECT_NONFATAL_FAILURE(
-      EXPECT_DEATH({
-          fprintf(stderr, "returning\n");
-          fflush(stderr);
-          return;
-        }, ""),
-      "    Result: illegal return in test statement.\n"
-      " Error msg:\n"
-      "[  DEATH   ] returning\n");
+  GTEST_FLAG_SET(death_test_style, "fast");
+  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(
+                              {
+                                fprintf(stderr, "returning\n");
+                                fflush(stderr);
+                                return;
+                              },
+                              ""),
+                          "    Result: illegal return in test statement.\n"
+                          " Error msg:\n"
+                          "[  DEATH   ] returning\n");
 }
 
 TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
-  testing::GTEST_FLAG(death_test_style) = "fast";
+  GTEST_FLAG_SET(death_test_style, "fast");
   EXPECT_NONFATAL_FAILURE(
       EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
-                  testing::ExitedWithCode(3),
-                  "expected message"),
+                  testing::ExitedWithCode(3), "expected message"),
       "    Result: died but not with expected exit code:\n"
       "            Exited with exit status 1\n"
       "Actual msg:\n"
@@ -920,7 +906,7 @@ TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
 }
 
 TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) {
-  testing::GTEST_FLAG(death_test_style) = "fast";
+  GTEST_FLAG_SET(death_test_style, "fast");
   EXPECT_NONFATAL_FAILURE(
       EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
                    "line 1\nxyz\nline 3\n"),
@@ -931,7 +917,7 @@ TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) {
 }
 
 TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) {
-  testing::GTEST_FLAG(death_test_style) = "fast";
+  GTEST_FLAG_SET(death_test_style, "fast");
   EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
                "line 1\nline 2\nline 3\n");
 }
@@ -945,8 +931,8 @@ class MockDeathTestFactory : public DeathTestFactory {
               int line, DeathTest** test) override;
 
   // Sets the parameters for subsequent calls to Create.
-  void SetParameters(bool create, DeathTest::TestRole role,
-                     int status, bool passed);
+  void SetParameters(bool create, DeathTest::TestRole role, int status,
+                     bool passed);
 
   // Accessors.
   int AssumeRoleCalls() const { return assume_role_calls_; }
@@ -988,17 +974,15 @@ class MockDeathTestFactory : public DeathTestFactory {
   bool test_deleted_;
 };
 
-
 // A DeathTest implementation useful in testing.  It returns values set
 // at its creation from its various inherited DeathTest methods, and
 // reports calls to those methods to its parent MockDeathTestFactory
 // object.
 class MockDeathTest : public DeathTest {
  public:
-  MockDeathTest(MockDeathTestFactory *parent,
-                TestRole role, int status, bool passed) :
-      parent_(parent), role_(role), status_(status), passed_(passed) {
-  }
+  MockDeathTest(MockDeathTestFactory* parent, TestRole role, int status,
+                bool passed)
+      : parent_(parent), role_(role), status_(status), passed_(passed) {}
   ~MockDeathTest() override { parent_->test_deleted_ = true; }
   TestRole AssumeRole() override {
     ++parent_->assume_role_calls_;
@@ -1023,7 +1007,6 @@ class MockDeathTest : public DeathTest {
   const bool passed_;
 };
 
-
 // MockDeathTestFactory constructor.
 MockDeathTestFactory::MockDeathTestFactory()
     : create_(true),
@@ -1033,13 +1016,10 @@ MockDeathTestFactory::MockDeathTestFactory()
       assume_role_calls_(0),
       wait_calls_(0),
       passed_args_(),
-      abort_args_() {
-}
-
+      abort_args_() {}
 
 // Sets the parameters for subsequent calls to Create.
-void MockDeathTestFactory::SetParameters(bool create,
-                                         DeathTest::TestRole role,
+void MockDeathTestFactory::SetParameters(bool create, DeathTest::TestRole role,
                                          int status, bool passed) {
   create_ = create;
   role_ = role;
@@ -1052,7 +1032,6 @@ void MockDeathTestFactory::SetParameters(bool create,
   abort_args_.clear();
 }
 
-
 // Sets test to NULL (if create_ is false) or to the address of a new
 // MockDeathTest object with parameters taken from the last call
 // to SetParameters (if create_ is true).  Always returns true.
@@ -1092,10 +1071,12 @@ class MacroLogicDeathTest : public testing::Test {
   // test cannot be run directly from a test routine that uses a
   // MockDeathTest, or the remainder of the routine will not be executed.
   static void RunReturningDeathTest(bool* flag) {
-    ASSERT_DEATH({  // NOLINT
-      *flag = true;
-      return;
-    }, "");
+    ASSERT_DEATH(
+        {  // NOLINT
+          *flag = true;
+          return;
+        },
+        "");
   }
 };
 
@@ -1180,8 +1161,7 @@ TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
   // _exit(2) is called in that case by ForkingDeathTest, but not by
   // our MockDeathTest.
   ASSERT_EQ(2U, factory_->AbortCalls());
-  EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
-            factory_->AbortArgument(0));
+  EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, factory_->AbortArgument(0));
   EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
             factory_->AbortArgument(1));
   EXPECT_TRUE(factory_->TestDeleted());
@@ -1197,12 +1177,16 @@ TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
 TEST(StreamingAssertionsDeathTest, DeathTest) {
   EXPECT_DEATH(_exit(1), "") << "unexpected failure";
   ASSERT_DEATH(_exit(1), "") << "unexpected failure";
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_DEATH(_exit(0), "") << "expected failure";
-  }, "expected failure");
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_DEATH(_exit(0), "") << "expected failure";
-  }, "expected failure");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_DEATH(_exit(0), "") << "expected failure";
+      },
+      "expected failure");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_DEATH(_exit(0), "") << "expected failure";
+      },
+      "expected failure");
 }
 
 // Tests that GetLastErrnoDescription returns an empty string when the
@@ -1214,7 +1198,7 @@ TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
   EXPECT_STREQ("", GetLastErrnoDescription().c_str());
 }
 
-# if GTEST_OS_WINDOWS
+#if GTEST_OS_WINDOWS
 TEST(AutoHandleTest, AutoHandleWorks) {
   HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
   ASSERT_NE(INVALID_HANDLE_VALUE, handle);
@@ -1239,15 +1223,15 @@ TEST(AutoHandleTest, AutoHandleWorks) {
   testing::internal::AutoHandle auto_handle2;
   EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
 }
-# endif  // GTEST_OS_WINDOWS
+#endif  // GTEST_OS_WINDOWS
 
-# if GTEST_OS_WINDOWS
+#if GTEST_OS_WINDOWS
 typedef unsigned __int64 BiggestParsable;
 typedef signed __int64 BiggestSignedParsable;
-# else
+#else
 typedef unsigned long long BiggestParsable;
 typedef signed long long BiggestSignedParsable;
-# endif  // GTEST_OS_WINDOWS
+#endif  // GTEST_OS_WINDOWS
 
 // We cannot use std::numeric_limits<T>::max() as it clashes with the
 // max() macro defined by <windows.h>.
@@ -1338,11 +1322,11 @@ TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
   EXPECT_EQ(123, char_result);
 }
 
-# if GTEST_OS_WINDOWS
+#if GTEST_OS_WINDOWS
 TEST(EnvironmentTest, HandleFitsIntoSizeT) {
   ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
 }
-# endif  // GTEST_OS_WINDOWS
+#endif  // GTEST_OS_WINDOWS
 
 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
 // failures when death tests are available on the system.
@@ -1358,23 +1342,27 @@ TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
 }
 
 TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
-  testing::GTEST_FLAG(death_test_style) = "fast";
+  GTEST_FLAG_SET(death_test_style, "fast");
   EXPECT_FALSE(InDeathTestChild());
-  EXPECT_DEATH({
-    fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
-    fflush(stderr);
-    _exit(1);
-  }, "Inside");
+  EXPECT_DEATH(
+      {
+        fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
+        fflush(stderr);
+        _exit(1);
+      },
+      "Inside");
 }
 
 TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
-  testing::GTEST_FLAG(death_test_style) = "threadsafe";
+  GTEST_FLAG_SET(death_test_style, "threadsafe");
   EXPECT_FALSE(InDeathTestChild());
-  EXPECT_DEATH({
-    fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
-    fflush(stderr);
-    _exit(1);
-  }, "Inside");
+  EXPECT_DEATH(
+      {
+        fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
+        fflush(stderr);
+        _exit(1);
+      },
+      "Inside");
 }
 
 void DieWithMessage(const char* message) {
@@ -1502,8 +1490,7 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
     // doesn't expand into an "if" statement without an "else"
     ;  // NOLINT
 
-  if (AlwaysFalse())
-    ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
+  if (AlwaysFalse()) ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
 
   if (AlwaysFalse())
     ;  // NOLINT
@@ -1522,21 +1509,18 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
 
   switch (0)
-    default:
-      ASSERT_DEATH_IF_SUPPORTED(_exit(1), "")
-          << "exit in default switch handler";
+  default:
+    ASSERT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in default switch handler";
 
   switch (0)
-    case 0:
-      EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
+  case 0:
+    EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
 
   GTEST_DISABLE_MSC_WARNINGS_POP_()
 }
 
 // Tests that a test case whose name ends with "DeathTest" works fine
 // on Windows.
-TEST(NotADeathTest, Test) {
-  SUCCEED();
-}
+TEST(NotADeathTest, Test) { SUCCEED(); }
 
 }  // namespace
index 7219680d0749777784f645147b50395db09ba95d..f2515e377e4c7f4210325a730cc5ed6a56e23e4a 100644 (file)
 
 #if GTEST_HAS_DEATH_TEST
 
-# if GTEST_HAS_SEH
-#  include <windows.h>          // For RaiseException().
-# endif
+#if GTEST_HAS_SEH
+#include <windows.h>  // For RaiseException().
+#endif
 
-# include "gtest/gtest-spi.h"
+#include "gtest/gtest-spi.h"
 
-# if GTEST_HAS_EXCEPTIONS
+#if GTEST_HAS_EXCEPTIONS
 
-#  include <exception>  // For std::exception.
+#include <exception>  // For std::exception.
 
 // Tests that death tests report thrown exceptions as failures and that the
 // exceptions do not escape death test macros.
@@ -53,7 +53,7 @@ TEST(CxxExceptionDeathTest, ExceptionIsFailure) {
   } catch (...) {  // NOLINT
     FAIL() << "An exception escaped a death test macro invocation "
            << "with catch_exceptions "
-           << (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled");
+           << (GTEST_FLAG_GET(catch_exceptions) ? "enabled" : "disabled");
   }
 }
 
@@ -67,26 +67,25 @@ TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) {
   EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""),
                           "exceptional message");
   // Verifies that the location is mentioned in the failure text.
-  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""),
-                          __FILE__);
+  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), __FILE__);
 }
-# endif  // GTEST_HAS_EXCEPTIONS
+#endif  // GTEST_HAS_EXCEPTIONS
 
-# if GTEST_HAS_SEH
+#if GTEST_HAS_SEH
 // Tests that enabling interception of SEH exceptions with the
 // catch_exceptions flag does not interfere with SEH exceptions being
 // treated as death by death tests.
 TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) {
   EXPECT_DEATH(RaiseException(42, 0x0, 0, NULL), "")
       << "with catch_exceptions "
-      << (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled");
+      << (GTEST_FLAG_GET(catch_exceptions) ? "enabled" : "disabled");
 }
-# endif
+#endif
 
 #endif  // GTEST_HAS_DEATH_TEST
 
 int main(int argc, char** argv) {
   testing::InitGoogleTest(&argc, argv);
-  testing::GTEST_FLAG(catch_exceptions) = GTEST_ENABLE_CATCH_EXCEPTIONS_ != 0;
+  GTEST_FLAG_SET(catch_exceptions, GTEST_ENABLE_CATCH_EXCEPTIONS_ != 0);
   return RUN_ALL_TESTS();
 }
index 02c3655c398268965a2851623523175219bac56c..bc4d87d93841aa725377a10cd29cb0e3032c5939 100755 (executable)
@@ -32,7 +32,7 @@
 """Verifies that Google Test correctly parses environment variables."""
 
 import os
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 
 IS_WINDOWS = os.name == 'nt'
index 52f95864e1e5ff4bd8f1c7e99e15310694181776..365337508027e99689bda1206dfaa380df4e7ce4 100644 (file)
@@ -27,7 +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.
 
-
 // A helper program for testing that Google Test parses the environment
 // variables correctly.
 
@@ -43,72 +42,71 @@ namespace testing {
 // The purpose of this is to make the test more realistic by ensuring
 // that the UnitTest singleton is created before main() is entered.
 // We don't actual run the TEST itself.
-TEST(GTestEnvVarTest, Dummy) {
-}
+TEST(GTestEnvVarTest, Dummy) {}
 
 void PrintFlag(const char* flag) {
   if (strcmp(flag, "break_on_failure") == 0) {
-    cout << GTEST_FLAG(break_on_failure);
+    cout << GTEST_FLAG_GET(break_on_failure);
     return;
   }
 
   if (strcmp(flag, "catch_exceptions") == 0) {
-    cout << GTEST_FLAG(catch_exceptions);
+    cout << GTEST_FLAG_GET(catch_exceptions);
     return;
   }
 
   if (strcmp(flag, "color") == 0) {
-    cout << GTEST_FLAG(color);
+    cout << GTEST_FLAG_GET(color);
     return;
   }
 
   if (strcmp(flag, "death_test_style") == 0) {
-    cout << GTEST_FLAG(death_test_style);
+    cout << GTEST_FLAG_GET(death_test_style);
     return;
   }
 
   if (strcmp(flag, "death_test_use_fork") == 0) {
-    cout << GTEST_FLAG(death_test_use_fork);
+    cout << GTEST_FLAG_GET(death_test_use_fork);
     return;
   }
 
   if (strcmp(flag, "fail_fast") == 0) {
-    cout << GTEST_FLAG(fail_fast);
+    cout << GTEST_FLAG_GET(fail_fast);
     return;
   }
 
   if (strcmp(flag, "filter") == 0) {
-    cout << GTEST_FLAG(filter);
+    cout << GTEST_FLAG_GET(filter);
     return;
   }
 
   if (strcmp(flag, "output") == 0) {
-    cout << GTEST_FLAG(output);
+    cout << GTEST_FLAG_GET(output);
     return;
   }
 
   if (strcmp(flag, "brief") == 0) {
-    cout << GTEST_FLAG(brief);
+    cout << GTEST_FLAG_GET(brief);
     return;
   }
 
   if (strcmp(flag, "print_time") == 0) {
-    cout << GTEST_FLAG(print_time);
+    cout << GTEST_FLAG_GET(print_time);
     return;
   }
 
   if (strcmp(flag, "repeat") == 0) {
-    cout << GTEST_FLAG(repeat);
+    cout << GTEST_FLAG_GET(repeat);
     return;
   }
 
   if (strcmp(flag, "stack_trace_depth") == 0) {
-    cout << GTEST_FLAG(stack_trace_depth);
+    cout << GTEST_FLAG_GET(stack_trace_depth);
     return;
   }
 
   if (strcmp(flag, "throw_on_failure") == 0) {
-    cout << GTEST_FLAG(throw_on_failure);
+    cout << GTEST_FLAG_GET(throw_on_failure);
     return;
   }
 
index 3aeb2dffeae42fc0338a1eda99cd4d435b79a7b3..1356d4f8b5b7fcb288e403f14ce5082bc5038a66 100755 (executable)
@@ -41,7 +41,7 @@ line flags.
 """
 
 import os
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 # Constants.
 
index 0b2c951bc0083994b066c2d86ae92be32281c685..3bd05a8eb293259862fe7d137db70601ea1f63fd 100644 (file)
@@ -27,7 +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.
 
-
 // Unit test for Google Test test filters.
 //
 // A user can specify which test(s) in a Google Test program to run via
@@ -160,7 +159,7 @@ TEST(HasSkipTest, Test4) { FAIL() << "Expected failure."; }
 
 }  // namespace
 
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
   ::testing::InitGoogleTest(&argc, argv);
   ::testing::UnitTest::GetInstance()->listeners().Append(new MyTestListener());
   return RUN_ALL_TESTS();
index aafad36f3fef449f46ba77db20ecc966b5720b77..fe53f848fcf3080e079a6ce453765a811acb04b5 100644 (file)
 // 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"
+#include "gtest/internal/gtest-filepath.h"
 #include "src/gtest-internal-inl.h"
 
 #if GTEST_OS_WINDOWS_MOBILE
-# include <windows.h>  // NOLINT
+#include <windows.h>  // NOLINT
 #elif GTEST_OS_WINDOWS
-# include <direct.h>  // NOLINT
-#endif  // GTEST_OS_WINDOWS_MOBILE
+#include <direct.h>  // NOLINT
+#endif               // GTEST_OS_WINDOWS_MOBILE
 
 namespace testing {
 namespace internal {
@@ -55,16 +55,16 @@ namespace {
 int remove(const char* path) {
   LPCWSTR wpath = String::AnsiToUtf16(path);
   int ret = DeleteFile(wpath) ? 0 : -1;
-  delete [] wpath;
+  delete[] wpath;
   return ret;
 }
 // Windows CE doesn't have the _rmdir C function.
 int _rmdir(const char* path) {
   FilePath filepath(path);
-  LPCWSTR wpath = String::AnsiToUtf16(
-      filepath.RemoveTrailingPathSeparator().c_str());
+  LPCWSTR wpath =
+      String::AnsiToUtf16(filepath.RemoveTrailingPathSeparator().c_str());
   int ret = RemoveDirectory(wpath) ? 0 : -1;
-  delete [] wpath;
+  delete[] wpath;
   return ret;
 }
 
@@ -78,18 +78,18 @@ TEST(GetCurrentDirTest, ReturnsCurrentDir) {
   const FilePath cwd = FilePath::GetCurrentDir();
   posix::ChDir(original_dir.c_str());
 
-# if GTEST_OS_WINDOWS || GTEST_OS_OS2
+#if GTEST_OS_WINDOWS || GTEST_OS_OS2
 
   // Skips the ":".
   const char* const cwd_without_drive = strchr(cwd.c_str(), ':');
   ASSERT_TRUE(cwd_without_drive != NULL);
   EXPECT_STREQ(GTEST_PATH_SEP_, cwd_without_drive + 1);
 
-# else
+#else
 
   EXPECT_EQ(GTEST_PATH_SEP_, cwd.string());
 
-# endif
+#endif
 }
 
 #endif  // GTEST_OS_WINDOWS_MOBILE
@@ -112,33 +112,34 @@ TEST(RemoveDirectoryNameTest, WhenEmptyName) {
 
 // RemoveDirectoryName "afile" -> "afile"
 TEST(RemoveDirectoryNameTest, ButNoDirectory) {
-  EXPECT_EQ("afile",
-      FilePath("afile").RemoveDirectoryName().string());
+  EXPECT_EQ("afile", FilePath("afile").RemoveDirectoryName().string());
 }
 
 // RemoveDirectoryName "/afile" -> "afile"
 TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) {
   EXPECT_EQ("afile",
-      FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
+            FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
 }
 
 // RemoveDirectoryName "adir/" -> ""
 TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) {
   EXPECT_EQ("",
-      FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string());
+            FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string());
 }
 
 // RemoveDirectoryName "adir/afile" -> "afile"
 TEST(RemoveDirectoryNameTest, ShouldGiveFileName) {
-  EXPECT_EQ("afile",
+  EXPECT_EQ(
+      "afile",
       FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
 }
 
 // RemoveDirectoryName "adir/subdir/afile" -> "afile"
 TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) {
   EXPECT_EQ("afile",
-      FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
-      .RemoveDirectoryName().string());
+            FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
+                .RemoveDirectoryName()
+                .string());
 }
 
 #if GTEST_HAS_ALT_PATH_SEP_
@@ -182,7 +183,7 @@ TEST(RemoveFileNameTest, EmptyName) {
 // RemoveFileName "adir/" -> "adir/"
 TEST(RemoveFileNameTest, ButNoFile) {
   EXPECT_EQ("adir" GTEST_PATH_SEP_,
-      FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string());
+            FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string());
 }
 
 // RemoveFileName "adir/afile" -> "adir/"
@@ -194,14 +195,15 @@ TEST(RemoveFileNameTest, GivesDirName) {
 // RemoveFileName "adir/subdir/afile" -> "adir/subdir/"
 TEST(RemoveFileNameTest, GivesDirAndSubDirName) {
   EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_,
-      FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
-      .RemoveFileName().string());
+            FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
+                .RemoveFileName()
+                .string());
 }
 
 // RemoveFileName "/afile" -> "/"
 TEST(RemoveFileNameTest, GivesRootDir) {
   EXPECT_EQ(GTEST_PATH_SEP_,
-      FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().string());
+            FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().string());
 }
 
 #if GTEST_HAS_ALT_PATH_SEP_
@@ -235,44 +237,43 @@ TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) {
 #endif
 
 TEST(MakeFileNameTest, GenerateWhenNumberIsZero) {
-  FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"),
-      0, "xml");
+  FilePath actual =
+      FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), 0, "xml");
   EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
 }
 
 TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) {
-  FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"),
-      12, "xml");
+  FilePath actual =
+      FilePath::MakeFileName(FilePath("foo"), FilePath("bar"), 12, "xml");
   EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
 }
 
 TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) {
   FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_),
-      FilePath("bar"), 0, "xml");
+                                           FilePath("bar"), 0, "xml");
   EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
 }
 
 TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) {
   FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_),
-      FilePath("bar"), 12, "xml");
+                                           FilePath("bar"), 12, "xml");
   EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
 }
 
 TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) {
-  FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"),
-      0, "xml");
+  FilePath actual =
+      FilePath::MakeFileName(FilePath(""), FilePath("bar"), 0, "xml");
   EXPECT_EQ("bar.xml", actual.string());
 }
 
 TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) {
-  FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"),
-      14, "xml");
+  FilePath actual =
+      FilePath::MakeFileName(FilePath(""), FilePath("bar"), 14, "xml");
   EXPECT_EQ("bar_14.xml", actual.string());
 }
 
 TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) {
-  FilePath actual = FilePath::ConcatPaths(FilePath("foo"),
-                                          FilePath("bar.xml"));
+  FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath("bar.xml"));
   EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
 }
 
@@ -283,8 +284,7 @@ TEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) {
 }
 
 TEST(ConcatPathsTest, Path1BeingEmpty) {
-  FilePath actual = FilePath::ConcatPaths(FilePath(""),
-                                          FilePath("bar.xml"));
+  FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath("bar.xml"));
   EXPECT_EQ("bar.xml", actual.string());
 }
 
@@ -294,8 +294,7 @@ TEST(ConcatPathsTest, Path2BeingEmpty) {
 }
 
 TEST(ConcatPathsTest, BothPathBeingEmpty) {
-  FilePath actual = FilePath::ConcatPaths(FilePath(""),
-                                          FilePath(""));
+  FilePath actual = FilePath::ConcatPaths(FilePath(""), FilePath(""));
   EXPECT_EQ("", actual.string());
 }
 
@@ -307,16 +306,16 @@ TEST(ConcatPathsTest, Path1ContainsPathSep) {
 }
 
 TEST(ConcatPathsTest, Path2ContainsPathSep) {
-  FilePath actual = FilePath::ConcatPaths(
-      FilePath("foo" GTEST_PATH_SEP_),
-      FilePath("bar" GTEST_PATH_SEP_ "bar.xml"));
+  FilePath actual =
+      FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_),
+                            FilePath("bar" GTEST_PATH_SEP_ "bar.xml"));
   EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml",
             actual.string());
 }
 
 TEST(ConcatPathsTest, Path2EndsWithPathSep) {
-  FilePath actual = FilePath::ConcatPaths(FilePath("foo"),
-                                          FilePath("bar" GTEST_PATH_SEP_));
+  FilePath actual =
+      FilePath::ConcatPaths(FilePath("foo"), FilePath("bar" GTEST_PATH_SEP_));
   EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.string());
 }
 
@@ -332,7 +331,8 @@ TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) {
 
 // RemoveTrailingPathSeparator "foo/" -> "foo"
 TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) {
-  EXPECT_EQ("foo",
+  EXPECT_EQ(
+      "foo",
       FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string());
 #if GTEST_HAS_ALT_PATH_SEP_
   EXPECT_EQ("foo", FilePath("foo/").RemoveTrailingPathSeparator().string());
@@ -343,18 +343,19 @@ TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) {
 TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) {
   EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
             FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_)
-                .RemoveTrailingPathSeparator().string());
+                .RemoveTrailingPathSeparator()
+                .string());
 }
 
 // RemoveTrailingPathSeparator "foo/bar" -> "foo/bar"
 TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) {
-  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
-            FilePath("foo" GTEST_PATH_SEP_ "bar")
-                .RemoveTrailingPathSeparator().string());
+  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar", FilePath("foo" GTEST_PATH_SEP_ "bar")
+                                             .RemoveTrailingPathSeparator()
+                                             .string());
 }
 
 TEST(DirectoryTest, RootDirectoryExists) {
-#if GTEST_OS_WINDOWS  // We are on Windows.
+#if GTEST_OS_WINDOWS              // We are on Windows.
   char current_drive[_MAX_PATH];  // NOLINT
   current_drive[0] = static_cast<char>(_getdrive() + 'A' - 1);
   current_drive[1] = ':';
@@ -393,12 +394,12 @@ TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) {
 
 TEST(DirectoryTest, CurrentDirectoryExists) {
 #if GTEST_OS_WINDOWS  // We are on Windows.
-# ifndef _WIN32_CE  // Windows CE doesn't have a current directory.
+#ifndef _WIN32_CE     // Windows CE doesn't have a current directory.
 
   EXPECT_TRUE(FilePath(".").DirectoryExists());
   EXPECT_TRUE(FilePath(".\\").DirectoryExists());
 
-# endif  // _WIN32_CE
+#endif  // _WIN32_CE
 #else
   EXPECT_TRUE(FilePath(".").DirectoryExists());
   EXPECT_TRUE(FilePath("./").DirectoryExists());
@@ -406,34 +407,35 @@ TEST(DirectoryTest, CurrentDirectoryExists) {
 }
 
 // "foo/bar" == foo//bar" == "foo///bar"
-TEST(NormalizeTest, MultipleConsecutiveSepaparatorsInMidstring) {
+TEST(NormalizeTest, MultipleConsecutiveSeparatorsInMidstring) {
   EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
             FilePath("foo" GTEST_PATH_SEP_ "bar").string());
   EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
             FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
-  EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
-            FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_
-                     GTEST_PATH_SEP_ "bar").string());
+  EXPECT_EQ(
+      "foo" GTEST_PATH_SEP_ "bar",
+      FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar")
+          .string());
 }
 
 // "/bar" == //bar" == "///bar"
-TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) {
-  EXPECT_EQ(GTEST_PATH_SEP_ "bar",
-    FilePath(GTEST_PATH_SEP_ "bar").string());
-  EXPECT_EQ(GTEST_PATH_SEP_ "bar",
-    FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
+TEST(NormalizeTest, MultipleConsecutiveSeparatorsAtStringStart) {
+  EXPECT_EQ(GTEST_PATH_SEP_ "bar", FilePath(GTEST_PATH_SEP_ "bar").string());
   EXPECT_EQ(GTEST_PATH_SEP_ "bar",
-    FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
+            FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
+  EXPECT_EQ(
+      GTEST_PATH_SEP_ "bar",
+      FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
 }
 
 // "foo/" == foo//" == "foo///"
-TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) {
+TEST(NormalizeTest, MultipleConsecutiveSeparatorsAtStringEnd) {
+  EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo" GTEST_PATH_SEP_).string());
   EXPECT_EQ("foo" GTEST_PATH_SEP_,
-    FilePath("foo" GTEST_PATH_SEP_).string());
-  EXPECT_EQ("foo" GTEST_PATH_SEP_,
-    FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
-  EXPECT_EQ("foo" GTEST_PATH_SEP_,
-    FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
+            FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
+  EXPECT_EQ(
+      "foo" GTEST_PATH_SEP_,
+      FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
 }
 
 #if GTEST_HAS_ALT_PATH_SEP_
@@ -442,12 +444,10 @@ TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) {
 // regardless of their combination (e.g. "foo\" =="foo/\" ==
 // "foo\\/").
 TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) {
-  EXPECT_EQ("foo" GTEST_PATH_SEP_,
-            FilePath("foo/").string());
+  EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo/").string());
   EXPECT_EQ("foo" GTEST_PATH_SEP_,
             FilePath("foo" GTEST_PATH_SEP_ "/").string());
-  EXPECT_EQ("foo" GTEST_PATH_SEP_,
-            FilePath("foo//" GTEST_PATH_SEP_).string());
+  EXPECT_EQ("foo" GTEST_PATH_SEP_, FilePath("foo//" GTEST_PATH_SEP_).string());
 }
 
 #endif
@@ -478,15 +478,15 @@ TEST(AssignmentOperatorTest, ConstAssignedToNonConst) {
 class DirectoryCreationTest : public Test {
  protected:
   void SetUp() override {
-    testdata_path_.Set(FilePath(
-        TempDir() + GetCurrentExecutableName().string() +
-        "_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_));
+    testdata_path_.Set(
+        FilePath(TempDir() + GetCurrentExecutableName().string() +
+                 "_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_));
     testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator());
 
-    unique_file0_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"),
-        0, "txt"));
-    unique_file1_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"),
-        1, "txt"));
+    unique_file0_.Set(
+        FilePath::MakeFileName(testdata_path_, FilePath("unique"), 0, "txt"));
+    unique_file1_.Set(
+        FilePath::MakeFileName(testdata_path_, FilePath("unique"), 1, "txt"));
 
     remove(testdata_file_.c_str());
     remove(unique_file0_.c_str());
@@ -512,8 +512,8 @@ class DirectoryCreationTest : public Test {
   // a directory named 'test' from a file named 'test'. Example names:
   FilePath testdata_path_;  // "/tmp/directory_creation/test/"
   FilePath testdata_file_;  // "/tmp/directory_creation/test"
-  FilePath unique_file0_;  // "/tmp/directory_creation/test/unique.txt"
-  FilePath unique_file1_;  // "/tmp/directory_creation/test/unique_1.txt"
+  FilePath unique_file0_;   // "/tmp/directory_creation/test/unique.txt"
+  FilePath unique_file1_;   // "/tmp/directory_creation/test/unique_1.txt"
 };
 
 TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) {
@@ -530,8 +530,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) {
 }
 
 TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {
-  FilePath file_path(FilePath::GenerateUniqueFileName(testdata_path_,
-      FilePath("unique"), "txt"));
+  FilePath file_path(FilePath::GenerateUniqueFileName(
+      testdata_path_, FilePath("unique"), "txt"));
   EXPECT_EQ(unique_file0_.string(), file_path.string());
   EXPECT_FALSE(file_path.FileOrDirectoryExists());  // file not there
 
@@ -540,8 +540,8 @@ TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {
   CreateTextFile(file_path.c_str());
   EXPECT_TRUE(file_path.FileOrDirectoryExists());
 
-  FilePath file_path2(FilePath::GenerateUniqueFileName(testdata_path_,
-      FilePath("unique"), "txt"));
+  FilePath file_path2(FilePath::GenerateUniqueFileName(
+      testdata_path_, FilePath("unique"), "txt"));
   EXPECT_EQ(unique_file1_.string(), file_path2.string());
   EXPECT_FALSE(file_path2.FileOrDirectoryExists());  // file not there
   CreateTextFile(file_path2.c_str());
@@ -614,14 +614,16 @@ TEST(FilePathTest, IsAbsolutePath) {
   EXPECT_FALSE(FilePath("is" GTEST_PATH_SEP_ "relative").IsAbsolutePath());
   EXPECT_FALSE(FilePath("").IsAbsolutePath());
 #if GTEST_OS_WINDOWS
-  EXPECT_TRUE(FilePath("c:\\" GTEST_PATH_SEP_ "is_not"
-                       GTEST_PATH_SEP_ "relative").IsAbsolutePath());
+  EXPECT_TRUE(
+      FilePath("c:\\" GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
+          .IsAbsolutePath());
   EXPECT_FALSE(FilePath("c:foo" GTEST_PATH_SEP_ "bar").IsAbsolutePath());
-  EXPECT_TRUE(FilePath("c:/" GTEST_PATH_SEP_ "is_not"
-                       GTEST_PATH_SEP_ "relative").IsAbsolutePath());
+  EXPECT_TRUE(
+      FilePath("c:/" GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
+          .IsAbsolutePath());
 #else
   EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
-              .IsAbsolutePath());
+                  .IsAbsolutePath());
 #endif  // GTEST_OS_WINDOWS
 }
 
index 6b32f2d21997189a3cd9eaf313d470bdd84fcc11..2c4a1b18a113dcd690a09b3fb4d65f9db183fea0 100755 (executable)
@@ -47,7 +47,7 @@ try:
 except ImportError:
   pass
 import sys
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 # Constants.
 
@@ -113,6 +113,9 @@ TEST_CASE_REGEX = re.compile(r'^\[\-+\] \d+ tests? from (\w+(/\w+)?)')
 # Regex for parsing test names from Google Test's output.
 TEST_REGEX = re.compile(r'^\[\s*RUN\s*\].*\.(\w+(/\w+)?)')
 
+# Regex for parsing disabled banner from Google Test's output
+DISABLED_BANNER_REGEX = re.compile(r'^\[\s*DISABLED\s*\] (.*)')
+
 # The command line flag to tell Google Test to output the list of tests it
 # will run.
 LIST_TESTS_FLAG = '--gtest_list_tests'
@@ -206,6 +209,17 @@ def RunAndExtractTestList(args = None):
   return (tests_run, p.exit_code)
 
 
+def RunAndExtractDisabledBannerList(args=None):
+  """Runs the test program and returns tests that printed a disabled banner."""
+  p = gtest_test_utils.Subprocess([COMMAND] + (args or []), env=environ)
+  banners_printed = []
+  for line in p.output.split('\n'):
+    match = DISABLED_BANNER_REGEX.match(line)
+    if match is not None:
+      banners_printed.append(match.group(1))
+  return banners_printed
+
+
 def InvokeWithModifiedEnv(extra_env, function, *args, **kwargs):
   """Runs the given function and arguments in a modified environment."""
   try:
@@ -613,6 +627,23 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
       self.assert_(os.path.exists(shard_status_file))
       os.remove(shard_status_file)
 
+  def testDisabledBanner(self):
+    """Tests that the disabled banner prints only tests that match filter."""
+    make_filter = lambda s: ['--%s=%s' % (FILTER_FLAG, s)]
+
+    banners = RunAndExtractDisabledBannerList(make_filter('*'))
+    self.AssertSetEqual(banners, [
+        'BarTest.DISABLED_TestFour', 'BarTest.DISABLED_TestFive',
+        'BazTest.DISABLED_TestC'
+    ])
+
+    banners = RunAndExtractDisabledBannerList(make_filter('Bar*'))
+    self.AssertSetEqual(
+        banners, ['BarTest.DISABLED_TestFour', 'BarTest.DISABLED_TestFive'])
+
+    banners = RunAndExtractDisabledBannerList(make_filter('*-Bar*'))
+    self.AssertSetEqual(banners, ['BazTest.DISABLED_TestC'])
+
   if SUPPORTS_DEATH_TESTS:
     def testShardingWorksWithDeathTests(self):
       """Tests integration with death tests and sharding."""
index d30ec9c78b565d8e8180173d8fc4e8aefad88aea..bc7aa59408371334fdbb7593dde95f2802cc1955 100644 (file)
@@ -27,7 +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.
 
-
 // Unit test for Google Test test filters.
 //
 // A user can specify which test(s) in a Google Test program to run via
@@ -43,87 +42,57 @@ namespace {
 
 // Test case FooTest.
 
-class FooTest : public testing::Test {
-};
+class FooTest : public testing::Test {};
 
-TEST_F(FooTest, Abc) {
-}
+TEST_F(FooTest, Abc) {}
 
-TEST_F(FooTest, Xyz) {
-  FAIL() << "Expected failure.";
-}
+TEST_F(FooTest, Xyz) { FAIL() << "Expected failure."; }
 
 // Test case BarTest.
 
-TEST(BarTest, TestOne) {
-}
+TEST(BarTest, TestOne) {}
 
-TEST(BarTest, TestTwo) {
-}
+TEST(BarTest, TestTwo) {}
 
-TEST(BarTest, TestThree) {
-}
+TEST(BarTest, TestThree) {}
 
-TEST(BarTest, DISABLED_TestFour) {
-  FAIL() << "Expected failure.";
-}
+TEST(BarTest, DISABLED_TestFour) { FAIL() << "Expected failure."; }
 
-TEST(BarTest, DISABLED_TestFive) {
-  FAIL() << "Expected failure.";
-}
+TEST(BarTest, DISABLED_TestFive) { FAIL() << "Expected failure."; }
 
 // Test case BazTest.
 
-TEST(BazTest, TestOne) {
-  FAIL() << "Expected failure.";
-}
+TEST(BazTest, TestOne) { FAIL() << "Expected failure."; }
 
-TEST(BazTest, TestA) {
-}
+TEST(BazTest, TestA) {}
 
-TEST(BazTest, TestB) {
-}
+TEST(BazTest, TestB) {}
 
-TEST(BazTest, DISABLED_TestC) {
-  FAIL() << "Expected failure.";
-}
+TEST(BazTest, DISABLED_TestC) { FAIL() << "Expected failure."; }
 
 // Test case HasDeathTest
 
-TEST(HasDeathTest, Test1) {
-  EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*");
-}
+TEST(HasDeathTest, Test1) { EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); }
 
 // We need at least two death tests to make sure that the all death tests
 // aren't on the first shard.
-TEST(HasDeathTest, Test2) {
-  EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*");
-}
+TEST(HasDeathTest, Test2) { EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); }
 
 // Test case FoobarTest
 
-TEST(DISABLED_FoobarTest, Test1) {
-  FAIL() << "Expected failure.";
-}
+TEST(DISABLED_FoobarTest, Test1) { FAIL() << "Expected failure."; }
 
-TEST(DISABLED_FoobarTest, DISABLED_Test2) {
-  FAIL() << "Expected failure.";
-}
+TEST(DISABLED_FoobarTest, DISABLED_Test2) { FAIL() << "Expected failure."; }
 
 // Test case FoobarbazTest
 
-TEST(DISABLED_FoobarbazTest, TestA) {
-  FAIL() << "Expected failure.";
-}
+TEST(DISABLED_FoobarbazTest, TestA) { FAIL() << "Expected failure."; }
 
-class ParamTest : public testing::TestWithParam<int> {
-};
+class ParamTest : public testing::TestWithParam<int> {};
 
-TEST_P(ParamTest, TestX) {
-}
+TEST_P(ParamTest, TestX) {}
 
-TEST_P(ParamTest, TestY) {
-}
+TEST_P(ParamTest, TestY) {}
 
 INSTANTIATE_TEST_SUITE_P(SeqP, ParamTest, testing::Values(1, 2));
 INSTANTIATE_TEST_SUITE_P(SeqQ, ParamTest, testing::Values(5, 6));
index 32ba628535ce32dd44faf1d5fc47e8a2fbf25392..265793442f97758b28fb2732cced44575a185fd0 100644 (file)
@@ -35,16 +35,17 @@ This script tests such functionality by invoking
 googletest-global-environment-unittest_ (a program written with Google Test).
 """
 
-import gtest_test_utils
+import re
+from googletest.test import gtest_test_utils
 
 
-def RunAndReturnOutput():
+def RunAndReturnOutput(args=None):
   """Runs the test program and returns its output."""
 
   return gtest_test_utils.Subprocess([
       gtest_test_utils.GetTestExecutablePath(
           'googletest-global-environment-unittest_')
-  ]).output
+  ] + (args or [])).output
 
 
 class GTestGlobalEnvironmentUnitTest(gtest_test_utils.TestCase):
@@ -67,6 +68,63 @@ class GTestGlobalEnvironmentUnitTest(gtest_test_utils.TestCase):
     # The test case shouldn't have been run.
     self.assertNotIn('Unexpected call', txt)
 
+  def testEnvironmentSetUpAndTornDownForEachRepeat(self):
+    """Tests the behavior of test environments and gtest_repeat."""
+
+    # When --gtest_recreate_environments_when_repeating is true, the global test
+    # environment should be set up and torn down for each iteration.
+    txt = RunAndReturnOutput([
+        '--gtest_repeat=2',
+        '--gtest_recreate_environments_when_repeating=true',
+    ])
+
+    expected_pattern = ('(.|\n)*'
+                        r'Repeating all tests \(iteration 1\)'
+                        '(.|\n)*'
+                        'Global test environment set-up.'
+                        '(.|\n)*'
+                        'SomeTest.DoesFoo'
+                        '(.|\n)*'
+                        'Global test environment tear-down'
+                        '(.|\n)*'
+                        r'Repeating all tests \(iteration 2\)'
+                        '(.|\n)*'
+                        'Global test environment set-up.'
+                        '(.|\n)*'
+                        'SomeTest.DoesFoo'
+                        '(.|\n)*'
+                        'Global test environment tear-down'
+                        '(.|\n)*')
+    self.assertRegex(txt, expected_pattern)
+
+  def testEnvironmentSetUpAndTornDownOnce(self):
+    """Tests environment and --gtest_recreate_environments_when_repeating."""
+
+    # By default the environment should only be set up and torn down once, at
+    # the start and end of the test respectively.
+    txt = RunAndReturnOutput([
+        '--gtest_repeat=2',
+    ])
+
+    expected_pattern = ('(.|\n)*'
+                        r'Repeating all tests \(iteration 1\)'
+                        '(.|\n)*'
+                        'Global test environment set-up.'
+                        '(.|\n)*'
+                        'SomeTest.DoesFoo'
+                        '(.|\n)*'
+                        r'Repeating all tests \(iteration 2\)'
+                        '(.|\n)*'
+                        'SomeTest.DoesFoo'
+                        '(.|\n)*'
+                        'Global test environment tear-down'
+                        '(.|\n)*')
+    self.assertRegex(txt, expected_pattern)
+
+    self.assertEqual(len(re.findall('Global test environment set-up', txt)), 1)
+    self.assertEqual(
+        len(re.findall('Global test environment tear-down', txt)), 1)
+
 
 if __name__ == '__main__':
   gtest_test_utils.Main()
index 8ef47b8f97463c2e3ad44225479d3bc06338792c..179283b85334f04a2cc99c1e6c082a6702627cac 100644 (file)
@@ -32,8 +32,8 @@
 
 import json
 import os
-import gtest_json_test_utils
-import gtest_test_utils
+from googletest.test import gtest_json_test_utils
+from googletest.test import gtest_test_utils
 
 GTEST_OUTPUT_SUBDIR = 'json_outfiles'
 GTEST_OUTPUT_1_TEST = 'gtest_xml_outfile1_test_'
@@ -71,6 +71,8 @@ EXPECTED_1 = {
             u'*',
         u'testsuite': [{
             u'name': u'TestSomeProperties',
+            u'file': u'gtest_xml_outfile1_test_.cc',
+            u'line': 41,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -115,6 +117,8 @@ EXPECTED_2 = {
             u'*',
         u'testsuite': [{
             u'name': u'TestSomeProperties',
+            u'file': u'gtest_xml_outfile2_test_.cc',
+            u'line': 41,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'timestamp': u'*',
index 41c85651449984a7b1418db2ed58b51fd36a0559..e0fbe465092195c5e497ea4c56b1a1289faa5970 100644 (file)
@@ -37,8 +37,8 @@ import os
 import re
 import sys
 
-import gtest_json_test_utils
-import gtest_test_utils
+from googletest.test import gtest_json_test_utils
+from googletest.test import gtest_test_utils
 
 GTEST_FILTER_FLAG = '--gtest_filter'
 GTEST_LIST_TESTS_FLAG = '--gtest_list_tests'
@@ -90,6 +90,8 @@ EXPECTED_NON_EMPTY = {
             u'*',
         u'testsuite': [{
             u'name': u'Succeeds',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 51,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -114,6 +116,10 @@ EXPECTED_NON_EMPTY = {
         u'testsuite': [{
             u'name':
                 u'Fails',
+            u'file':
+                u'gtest_xml_output_unittest_.cc',
+            u'line':
+                59,
             u'status':
                 u'RUN',
             u'result':
@@ -148,6 +154,8 @@ EXPECTED_NON_EMPTY = {
             u'*',
         u'testsuite': [{
             u'name': u'DISABLED_test_not_run',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 66,
             u'status': u'NOTRUN',
             u'result': u'SUPPRESSED',
             u'time': u'*',
@@ -171,6 +179,8 @@ EXPECTED_NON_EMPTY = {
             u'*',
         u'testsuite': [{
             u'name': u'Skipped',
+            u'file': 'gtest_xml_output_unittest_.cc',
+            u'line': 73,
             u'status': u'RUN',
             u'result': u'SKIPPED',
             u'time': u'*',
@@ -178,6 +188,8 @@ EXPECTED_NON_EMPTY = {
             u'classname': u'SkippedTest'
         }, {
             u'name': u'SkippedWithMessage',
+            u'file': 'gtest_xml_output_unittest_.cc',
+            u'line': 77,
             u'status': u'RUN',
             u'result': u'SKIPPED',
             u'time': u'*',
@@ -186,6 +198,10 @@ EXPECTED_NON_EMPTY = {
         }, {
             u'name':
                 u'SkippedAfterFailure',
+            u'file':
+                'gtest_xml_output_unittest_.cc',
+            u'line':
+                81,
             u'status':
                 u'RUN',
             u'result':
@@ -220,6 +236,8 @@ EXPECTED_NON_EMPTY = {
             u'*',
         u'testsuite': [{
             u'name': u'Succeeds',
+            u'file': 'gtest_xml_output_unittest_.cc',
+            u'line': 86,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -228,6 +246,10 @@ EXPECTED_NON_EMPTY = {
         }, {
             u'name':
                 u'Fails',
+            u'file':
+                u'gtest_xml_output_unittest_.cc',
+            u'line':
+                91,
             u'status':
                 u'RUN',
             u'result':
@@ -251,6 +273,8 @@ EXPECTED_NON_EMPTY = {
             }]
         }, {
             u'name': u'DISABLED_test',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 96,
             u'status': u'NOTRUN',
             u'result': u'SUPPRESSED',
             u'time': u'*',
@@ -275,6 +299,10 @@ EXPECTED_NON_EMPTY = {
         u'testsuite': [{
             u'name':
                 u'OutputsCData',
+            u'file':
+                u'gtest_xml_output_unittest_.cc',
+            u'line':
+                100,
             u'status':
                 u'RUN',
             u'result':
@@ -311,6 +339,10 @@ EXPECTED_NON_EMPTY = {
         u'testsuite': [{
             u'name':
                 u'InvalidCharactersInMessage',
+            u'file':
+                u'gtest_xml_output_unittest_.cc',
+            u'line':
+                107,
             u'status':
                 u'RUN',
             u'result':
@@ -349,6 +381,8 @@ EXPECTED_NON_EMPTY = {
             u'aye',
         u'testsuite': [{
             u'name': u'OneProperty',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 119,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -357,6 +391,8 @@ EXPECTED_NON_EMPTY = {
             u'key_1': u'1'
         }, {
             u'name': u'IntValuedProperty',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 123,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -365,6 +401,8 @@ EXPECTED_NON_EMPTY = {
             u'key_int': u'1'
         }, {
             u'name': u'ThreeProperties',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 127,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -375,6 +413,8 @@ EXPECTED_NON_EMPTY = {
             u'key_3': u'3'
         }, {
             u'name': u'TwoValuesForOneKeyUsesLastValue',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 133,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -399,6 +439,8 @@ EXPECTED_NON_EMPTY = {
             u'*',
         u'testsuite': [{
             u'name': u'RecordProperty',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 138,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -407,6 +449,8 @@ EXPECTED_NON_EMPTY = {
             u'key': u'1'
         }, {
             u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 151,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -415,6 +459,8 @@ EXPECTED_NON_EMPTY = {
             u'key_for_utility_int': u'1'
         }, {
             u'name': u'ExternalUtilityThatCallsRecordStringValuedProperty',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 155,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -440,6 +486,8 @@ EXPECTED_NON_EMPTY = {
         u'testsuite': [{
             u'name': u'HasTypeParamAttribute',
             u'type_param': u'int',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 171,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -464,6 +512,8 @@ EXPECTED_NON_EMPTY = {
         u'testsuite': [{
             u'name': u'HasTypeParamAttribute',
             u'type_param': u'long',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 171,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -488,6 +538,8 @@ EXPECTED_NON_EMPTY = {
         u'testsuite': [{
             u'name': u'HasTypeParamAttribute',
             u'type_param': u'int',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 178,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -512,6 +564,8 @@ EXPECTED_NON_EMPTY = {
         u'testsuite': [{
             u'name': u'HasTypeParamAttribute',
             u'type_param': u'long',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 178,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -536,6 +590,8 @@ EXPECTED_NON_EMPTY = {
         u'testsuite': [{
             u'name': u'HasValueParamAttribute/0',
             u'value_param': u'33',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 162,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -544,6 +600,8 @@ EXPECTED_NON_EMPTY = {
         }, {
             u'name': u'HasValueParamAttribute/1',
             u'value_param': u'42',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 162,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -552,6 +610,8 @@ EXPECTED_NON_EMPTY = {
         }, {
             u'name': u'AnotherTestThatHasValueParamAttribute/0',
             u'value_param': u'33',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 163,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -560,6 +620,8 @@ EXPECTED_NON_EMPTY = {
         }, {
             u'name': u'AnotherTestThatHasValueParamAttribute/1',
             u'value_param': u'42',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 163,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
@@ -603,6 +665,8 @@ EXPECTED_FILTERED = {
             u'*',
         u'testsuite': [{
             u'name': u'Succeeds',
+            u'file': u'gtest_xml_output_unittest_.cc',
+            u'line': 51,
             u'status': u'RUN',
             u'result': u'COMPLETED',
             u'time': u'*',
index 81423a339e8fd28aa2b4253013b3c23ce3533749..9d56883d741d80d7bad8301e20620fca6b156002 100755 (executable)
@@ -38,7 +38,7 @@ Google Test) the command line flags.
 """
 
 import re
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 # Constants.
 
index 493c6f00464a90d635d8df096bffec5173e6e44d..5577e8961cdc2b3190bb11aada789ec9376b11be 100644 (file)
@@ -27,7 +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.
 
-
 // Unit test for Google Test's --gtest_list_tests flag.
 //
 // A user can ask Google Test to list all tests that will run
 #include "gtest/gtest.h"
 
 // Several different test cases and tests that will be listed.
-TEST(Foo, Bar1) {
-}
+TEST(Foo, Bar1) {}
 
-TEST(Foo, Bar2) {
-}
+TEST(Foo, Bar2) {}
 
-TEST(Foo, DISABLED_Bar3) {
-}
+TEST(Foo, DISABLED_Bar3) {}
 
-TEST(Abc, Xyz) {
-}
+TEST(Abc, Xyz) {}
 
-TEST(Abc, Def) {
-}
+TEST(Abc, Def) {}
 
-TEST(FooBar, Baz) {
-}
+TEST(FooBar, Baz) {}
 
-class FooTest : public testing::Test {
-};
+class FooTest : public testing::Test {};
 
-TEST_F(FooTest, Test1) {
-}
+TEST_F(FooTest, Test1) {}
 
-TEST_F(FooTest, DISABLED_Test2) {
-}
+TEST_F(FooTest, DISABLED_Test2) {}
 
-TEST_F(FooTest, Test3) {
-}
+TEST_F(FooTest, Test3) {}
 
-TEST(FooDeathTest, Test1) {
-}
+TEST(FooDeathTest, Test1) {}
 
 // A group of value-parameterized tests.
 
@@ -86,70 +74,66 @@ class MyType {
 };
 
 // Teaches Google Test how to print a MyType.
-void PrintTo(const MyType& x, std::ostream* os) {
-  *os << x.value();
-}
+void PrintTo(const MyType& x, std::ostream* os) { *os << x.value(); }
 
-class ValueParamTest : public testing::TestWithParam<MyType> {
-};
+class ValueParamTest : public testing::TestWithParam<MyType> {};
 
-TEST_P(ValueParamTest, TestA) {
-}
+TEST_P(ValueParamTest, TestA) {}
 
-TEST_P(ValueParamTest, TestB) {
-}
+TEST_P(ValueParamTest, TestB) {}
 
 INSTANTIATE_TEST_SUITE_P(
     MyInstantiation, ValueParamTest,
-    testing::Values(MyType("one line"),
-                    MyType("two\nlines"),
-                    MyType("a very\nloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong line")));  // NOLINT
+    testing::Values(
+        MyType("one line"), MyType("two\nlines"),
+        MyType("a "
+               "very\nloooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
+               "ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
+               "ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
+               "ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
+               "ooooong line")));  // NOLINT
 
 // A group of typed tests.
 
 // A deliberately long type name for testing the line-truncating
 // behavior when printing a type parameter.
-class VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName {  // NOLINT
+class
+    VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName {  // NOLINT
 };
 
 template <typename T>
-class TypedTest : public testing::Test {
-};
+class TypedTest : public testing::Test {};
 
 template <typename T, int kSize>
-class MyArray {
-};
+class MyArray {};
 
-typedef testing::Types<VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName,  // NOLINT
-                       int*, MyArray<bool, 42> > MyTypes;
+typedef testing::Types<
+    VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName,  // NOLINT
+    int*, MyArray<bool, 42> >
+    MyTypes;
 
 TYPED_TEST_SUITE(TypedTest, MyTypes);
 
-TYPED_TEST(TypedTest, TestA) {
-}
+TYPED_TEST(TypedTest, TestA) {}
 
-TYPED_TEST(TypedTest, TestB) {
-}
+TYPED_TEST(TypedTest, TestB) {}
 
 // A group of type-parameterized tests.
 
 template <typename T>
-class TypeParamTest : public testing::Test {
-};
+class TypeParamTest : public testing::Test {};
 
 TYPED_TEST_SUITE_P(TypeParamTest);
 
-TYPED_TEST_P(TypeParamTest, TestA) {
-}
+TYPED_TEST_P(TypeParamTest, TestA) {}
 
-TYPED_TEST_P(TypeParamTest, TestB) {
-}
+TYPED_TEST_P(TypeParamTest, TestB) {}
 
 REGISTER_TYPED_TEST_SUITE_P(TypeParamTest, TestA, TestB);
 
 INSTANTIATE_TYPED_TEST_SUITE_P(My, TypeParamTest, MyTypes);
 
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
   ::testing::InitGoogleTest(&argc, argv);
 
   return RUN_ALL_TESTS();
index 10457afe39a7dbd1fa0f733928678728dcd1b955..89d01b37ff403107e53c7e455a0d4cce3488c0de 100644 (file)
@@ -41,10 +41,10 @@ using ::testing::AddGlobalTestEnvironment;
 using ::testing::Environment;
 using ::testing::InitGoogleTest;
 using ::testing::Test;
-using ::testing::TestSuite;
 using ::testing::TestEventListener;
 using ::testing::TestInfo;
 using ::testing::TestPartResult;
+using ::testing::TestSuite;
 using ::testing::UnitTest;
 
 // Used by tests to register their events.
@@ -65,8 +65,8 @@ class EventRecordingListener : public TestEventListener {
   void OnTestIterationStart(const UnitTest& /*unit_test*/,
                             int iteration) override {
     Message message;
-    message << GetFullMethodName("OnTestIterationStart")
-            << "(" << iteration << ")";
+    message << GetFullMethodName("OnTestIterationStart") << "(" << iteration
+            << ")";
     g_events->push_back(message.GetString());
   }
 
@@ -112,8 +112,8 @@ class EventRecordingListener : public TestEventListener {
   void OnTestIterationEnd(const UnitTest& /*unit_test*/,
                           int iteration) override {
     Message message;
-    message << GetFullMethodName("OnTestIterationEnd")
-            << "("  << iteration << ")";
+    message << GetFullMethodName("OnTestIterationEnd") << "(" << iteration
+            << ")";
     g_events->push_back(message.GetString());
   }
 
@@ -122,9 +122,7 @@ class EventRecordingListener : public TestEventListener {
   }
 
  private:
-  std::string GetFullMethodName(const char* name) {
-    return name_ + "." + name;
-  }
+  std::string GetFullMethodName(const char* name) { return name_ + "." + name; }
 
   std::string name_;
 };
@@ -252,22 +250,21 @@ void VerifyResults(const std::vector<std::string>& data,
   EXPECT_EQ(expected_data_size, actual_size);
 
   // Compares the common prefix.
-  const size_t shorter_size = expected_data_size <= actual_size ?
-      expected_data_size : actual_size;
+  const size_t shorter_size =
+      expected_data_size <= actual_size ? expected_data_size : actual_size;
   size_t i = 0;
   for (; i < shorter_size; ++i) {
-    ASSERT_STREQ(expected_data[i], data[i].c_str())
-        << "at position " << i;
+    ASSERT_STREQ(expected_data[i], data[i].c_str()) << "at position " << i;
   }
 
   // Prints extra elements in the actual data.
   for (; i < actual_size; ++i) {
-    printf("  Actual event #%lu: %s\n",
-        static_cast<unsigned long>(i), data[i].c_str());
+    printf("  Actual event #%lu: %s\n", static_cast<unsigned long>(i),
+           data[i].c_str());
   }
 }
 
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
   std::vector<std::string> events;
   g_events = &events;
   InitGoogleTest(&argc, argv);
@@ -284,7 +281,8 @@ int main(int argc, char **argv) {
   GTEST_CHECK_(events.size() == 0)
       << "AddGlobalTestEnvironment should not generate any events itself.";
 
-  ::testing::GTEST_FLAG(repeat) = 2;
+  GTEST_FLAG_SET(repeat, 2);
+  GTEST_FLAG_SET(recreate_environments_when_repeating, true);
   int ret_val = RUN_ALL_TESTS();
 
 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
@@ -505,14 +503,12 @@ int main(int argc, char **argv) {
                                          "1st.OnTestProgramEnd"};
 #endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
 
-  VerifyResults(events,
-                expected_events,
-                sizeof(expected_events)/sizeof(expected_events[0]));
+  VerifyResults(events, expected_events,
+                sizeof(expected_events) / sizeof(expected_events[0]));
 
   // We need to check manually for ad hoc test failures that happen after
   // RUN_ALL_TESTS finishes.
-  if (UnitTest::GetInstance()->Failed())
-    ret_val = 1;
+  if (UnitTest::GetInstance()->Failed()) ret_val = 1;
 
   return ret_val;
 }
index 962d519114e6e4e3dc3df19fde7545571bc031bc..252a861977a2d04a2ed264b2ea04e9318252e3a5 100644 (file)
@@ -31,7 +31,6 @@
 // Tests for the Message class.
 
 #include "gtest/gtest-message.h"
-
 #include "gtest/gtest.h"
 
 namespace {
@@ -69,8 +68,9 @@ TEST(MessageTest, StreamsFloat) {
 
 // Tests streaming a double.
 TEST(MessageTest, StreamsDouble) {
-  const std::string s = (Message() << 1260570880.4555497 << " "
-                                  << 1260572265.1954534).GetString();
+  const std::string s =
+      (Message() << 1260570880.4555497 << " " << 1260572265.1954534)
+          .GetString();
   // Both numbers should be printed with enough precision.
   EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s.c_str());
   EXPECT_PRED_FORMAT2(testing::IsSubstring, " 1260572265.19", s.c_str());
@@ -108,8 +108,7 @@ TEST(MessageTest, StreamsString) {
 
 // Tests that we can output strings containing embedded NULs.
 TEST(MessageTest, StreamsStringWithEmbeddedNUL) {
-  const char char_array_with_nul[] =
-      "Here's a NUL\0 and some more string";
+  const char char_array_with_nul[] = "Here's a NUL\0 and some more string";
   const ::std::string string_with_nul(char_array_with_nul,
                                       sizeof(char_array_with_nul) - 1);
   EXPECT_EQ("Here's a NUL\\0 and some more string",
@@ -129,10 +128,11 @@ TEST(MessageTest, StreamsInt) {
 // Tests that basic IO manipulators (endl, ends, and flush) can be
 // streamed to Message.
 TEST(MessageTest, StreamsBasicIoManip) {
-  EXPECT_EQ("Line 1.\nA NUL char \\0 in line 2.",
-               (Message() << "Line 1." << std::endl
-                         << "A NUL char " << std::ends << std::flush
-                         << " in line 2.").GetString());
+  EXPECT_EQ(
+      "Line 1.\nA NUL char \\0 in line 2.",
+      (Message() << "Line 1." << std::endl
+                 << "A NUL char " << std::ends << std::flush << " in line 2.")
+          .GetString());
 }
 
 // Tests Message::GetString()
index 11fb1f224629a125521923fc68e13edd9242dc4e..1265c22511a8408d7d89a5cd10eb1ee01403c6ad 100644 (file)
@@ -39,9 +39,9 @@
 #include "gtest/gtest.h"
 
 #if GTEST_OS_WINDOWS_MOBILE
-# include <windows.h>
+#include <windows.h>
 #elif GTEST_OS_WINDOWS
-# include <direct.h>
+#include <direct.h>
 #elif GTEST_OS_OS2
 // For strcasecmp on OS/2
 #include <strings.h>
@@ -61,33 +61,33 @@ FilePath GetAbsolutePathOf(const FilePath& relative_path) {
 // Testing UnitTestOptions::GetOutputFormat/GetOutputFile.
 
 TEST(XmlOutputTest, GetOutputFormatDefault) {
-  GTEST_FLAG(output) = "";
+  GTEST_FLAG_SET(output, "");
   EXPECT_STREQ("", UnitTestOptions::GetOutputFormat().c_str());
 }
 
 TEST(XmlOutputTest, GetOutputFormat) {
-  GTEST_FLAG(output) = "xml:filename";
+  GTEST_FLAG_SET(output, "xml:filename");
   EXPECT_STREQ("xml", UnitTestOptions::GetOutputFormat().c_str());
 }
 
 TEST(XmlOutputTest, GetOutputFileDefault) {
-  GTEST_FLAG(output) = "";
+  GTEST_FLAG_SET(output, "");
   EXPECT_EQ(GetAbsolutePathOf(FilePath("test_detail.xml")).string(),
             UnitTestOptions::GetAbsolutePathToOutputFile());
 }
 
 TEST(XmlOutputTest, GetOutputFileSingleFile) {
-  GTEST_FLAG(output) = "xml:filename.abc";
+  GTEST_FLAG_SET(output, "xml:filename.abc");
   EXPECT_EQ(GetAbsolutePathOf(FilePath("filename.abc")).string(),
             UnitTestOptions::GetAbsolutePathToOutputFile());
 }
 
 TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) {
-  GTEST_FLAG(output) = "xml:path" GTEST_PATH_SEP_;
+  GTEST_FLAG_SET(output, "xml:path" GTEST_PATH_SEP_);
   const std::string expected_output_file =
-      GetAbsolutePathOf(
-          FilePath(std::string("path") + GTEST_PATH_SEP_ +
-                   GetCurrentExecutableName().string() + ".xml")).string();
+      GetAbsolutePathOf(FilePath(std::string("path") + GTEST_PATH_SEP_ +
+                                 GetCurrentExecutableName().string() + ".xml"))
+          .string();
   const std::string& output_file =
       UnitTestOptions::GetAbsolutePathToOutputFile();
 #if GTEST_OS_WINDOWS
@@ -115,13 +115,10 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) {
   const bool success = exe_str == "app";
 #else
   const bool success =
-      exe_str == "googletest-options-test" ||
-      exe_str == "gtest_all_test" ||
-      exe_str == "lt-gtest_all_test" ||
-      exe_str == "gtest_dll_test";
+      exe_str == "googletest-options-test" || exe_str == "gtest_all_test" ||
+      exe_str == "lt-gtest_all_test" || exe_str == "gtest_dll_test";
 #endif  // GTEST_OS_WINDOWS
-  if (!success)
-    FAIL() << "GetCurrentExecutableName() returns " << exe_str;
+  if (!success) FAIL() << "GetCurrentExecutableName() returns " << exe_str;
 }
 
 #if !GTEST_OS_FUCHSIA
@@ -144,33 +141,37 @@ class XmlOutputChangeDirTest : public Test {
 };
 
 TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) {
-  GTEST_FLAG(output) = "";
-  EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_,
-                                  FilePath("test_detail.xml")).string(),
-            UnitTestOptions::GetAbsolutePathToOutputFile());
+  GTEST_FLAG_SET(output, "");
+  EXPECT_EQ(
+      FilePath::ConcatPaths(original_working_dir_, FilePath("test_detail.xml"))
+          .string(),
+      UnitTestOptions::GetAbsolutePathToOutputFile());
 }
 
 TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) {
-  GTEST_FLAG(output) = "xml";
-  EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_,
-                                  FilePath("test_detail.xml")).string(),
-            UnitTestOptions::GetAbsolutePathToOutputFile());
+  GTEST_FLAG_SET(output, "xml");
+  EXPECT_EQ(
+      FilePath::ConcatPaths(original_working_dir_, FilePath("test_detail.xml"))
+          .string(),
+      UnitTestOptions::GetAbsolutePathToOutputFile());
 }
 
 TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) {
-  GTEST_FLAG(output) = "xml:filename.abc";
-  EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_,
-                                  FilePath("filename.abc")).string(),
-            UnitTestOptions::GetAbsolutePathToOutputFile());
+  GTEST_FLAG_SET(output, "xml:filename.abc");
+  EXPECT_EQ(
+      FilePath::ConcatPaths(original_working_dir_, FilePath("filename.abc"))
+          .string(),
+      UnitTestOptions::GetAbsolutePathToOutputFile());
 }
 
 TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {
-  GTEST_FLAG(output) = "xml:path" GTEST_PATH_SEP_;
+  GTEST_FLAG_SET(output, "xml:path" GTEST_PATH_SEP_);
   const std::string expected_output_file =
       FilePath::ConcatPaths(
           original_working_dir_,
           FilePath(std::string("path") + GTEST_PATH_SEP_ +
-                   GetCurrentExecutableName().string() + ".xml")).string();
+                   GetCurrentExecutableName().string() + ".xml"))
+          .string();
   const std::string& output_file =
       UnitTestOptions::GetAbsolutePathToOutputFile();
 #if GTEST_OS_WINDOWS
@@ -182,11 +183,11 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {
 
 TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsoluteFile) {
 #if GTEST_OS_WINDOWS
-  GTEST_FLAG(output) = "xml:c:\\tmp\\filename.abc";
+  GTEST_FLAG_SET(output, "xml:c:\\tmp\\filename.abc");
   EXPECT_EQ(FilePath("c:\\tmp\\filename.abc").string(),
             UnitTestOptions::GetAbsolutePathToOutputFile());
 #else
-  GTEST_FLAG(output) ="xml:/tmp/filename.abc";
+  GTEST_FLAG_SET(output, "xml:/tmp/filename.abc");
   EXPECT_EQ(FilePath("/tmp/filename.abc").string(),
             UnitTestOptions::GetAbsolutePathToOutputFile());
 #endif
@@ -199,7 +200,7 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsolutePath) {
   const std::string path = "/tmp/";
 #endif
 
-  GTEST_FLAG(output) = "xml:" + path;
+  GTEST_FLAG_SET(output, "xml:" + path);
   const std::string expected_output_file =
       path + GetCurrentExecutableName().string() + ".xml";
   const std::string& output_file =
index 3fab3b97d8f1a22b641d755ab8359e5b03c92209..1f24fb7915394a24b472ce033c71d990cd8cec0d 100644 (file)
@@ -12,7 +12,7 @@ Expected equality of these values:
   3
 Stack trace: (omitted)
 
-\e[0;32m[==========] \e[mRunning 88 tests from 41 test suites.
+\e[0;32m[==========] \e[mRunning 89 tests from 42 test suites.
 \e[0;32m[----------] \e[mGlobal test environment set-up.
 FooEnvironment::SetUp() called.
 BarEnvironment::SetUp() called.
@@ -956,6 +956,17 @@ Stack trace: (omitted)
 ~DynamicFixture()
 \e[0;31m[  FAILED  ] \e[mBadDynamicFixture2.Derived
 DynamicFixture::TearDownTestSuite
+\e[0;32m[----------] \e[m1 test from TestSuiteThatFailsToSetUp
+googletest-output-test_.cc:#: Failure
+Value of: false
+  Actual: false
+Expected: true
+Stack trace: (omitted)
+
+\e[0;32m[ RUN      ] \e[mTestSuiteThatFailsToSetUp.ShouldNotRun
+googletest-output-test_.cc:#: Skipped
+
+\e[0;32m[  SKIPPED ] \e[mTestSuiteThatFailsToSetUp.ShouldNotRun
 \e[0;32m[----------] \e[m1 test from PrintingFailingParams/FailingParamTest
 \e[0;32m[ RUN      ] \e[mPrintingFailingParams/FailingParamTest.Fails/0
 googletest-output-test_.cc:#: Failure
@@ -1032,8 +1043,10 @@ Failed
 Expected fatal failure.
 Stack trace: (omitted)
 
-\e[0;32m[==========] \e[m88 tests from 41 test suites ran.
+\e[0;32m[==========] \e[m89 tests from 42 test suites ran.
 \e[0;32m[  PASSED  ] \e[m31 tests.
+\e[0;32m[  SKIPPED ] \e[m1 test, listed below:
+\e[0;32m[  SKIPPED ] \e[mTestSuiteThatFailsToSetUp.ShouldNotRun
 \e[0;31m[  FAILED  ] \e[m57 tests, listed below:
 \e[0;31m[  FAILED  ] \e[mNonfatalFailureTest.EscapesStringOperands
 \e[0;31m[  FAILED  ] \e[mNonfatalFailureTest.DiffForLongStrings
@@ -1094,6 +1107,9 @@ Stack trace: (omitted)
 \e[0;31m[  FAILED  ] \e[mGoogleTestVerification.UninstantiatedTypeParameterizedTestSuite<DetectNotInstantiatedTypesTest>
 
 57 FAILED TESTS
+\e[0;31m[  FAILED  ] \e[mTestSuiteThatFailsToSetUp: SetUpTestSuite or TearDownTestSuite
+
+ 1 FAILED TEST SUITE
 \e[0;33m  YOU HAVE 1 DISABLED TEST
 
 \e[mNote: Google Test filter = FatalFailureTest.*:LoggingTest.*
index 09028f66f90bf2382bb78c79bb4e3c39adc30170..ff44483331fbd420d5f926d9a5406ed870b5b049 100755 (executable)
@@ -42,7 +42,7 @@ import difflib
 import os
 import re
 import sys
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 
 # The flag for generating the golden file
index 074f64ef62142e9d151b16c03a50169cb7a5a7cc..c2f96d980d263646dba9ee45037e3ed87eaacbe3 100644 (file)
 // desired messages.  Therefore, most tests in this file are MEANT TO
 // FAIL.
 
+#include <stdlib.h>
+
 #include "gtest/gtest-spi.h"
 #include "gtest/gtest.h"
 #include "src/gtest-internal-inl.h"
 
-#include <stdlib.h>
-
 #if _MSC_VER
 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */)
 #endif  //  _MSC_VER
@@ -56,9 +56,7 @@ namespace posix = ::testing::internal::posix;
 // Tests catching fatal failures.
 
 // A subroutine used by the following test.
-void TestEq1(int x) {
-  ASSERT_EQ(1, x);
-}
+void TestEq1(int x) { ASSERT_EQ(1, x); }
 
 // This function calls a test subroutine, catches the fatal failure it
 // generates, and then returns early.
@@ -76,24 +74,19 @@ void TryTestSubroutine() {
   FAIL() << "This should never be reached.";
 }
 
-TEST(PassingTest, PassingTest1) {
-}
+TEST(PassingTest, PassingTest1) {}
 
-TEST(PassingTest, PassingTest2) {
-}
+TEST(PassingTest, PassingTest2) {}
 
 // Tests that parameters of failing parameterized tests are printed in the
 // failing test summary.
 class FailingParamTest : public testing::TestWithParam<int> {};
 
-TEST_P(FailingParamTest, Fails) {
-  EXPECT_EQ(1, GetParam());
-}
+TEST_P(FailingParamTest, Fails) { EXPECT_EQ(1, GetParam()); }
 
 // This generates a test which will fail. Google Test is expected to print
 // its parameter when it outputs the list of all failed tests.
-INSTANTIATE_TEST_SUITE_P(PrintingFailingParams,
-                         FailingParamTest,
+INSTANTIATE_TEST_SUITE_P(PrintingFailingParams, FailingParamTest,
                          testing::Values(2));
 
 // Tests that an empty value for the test suite basename yields just
@@ -146,18 +139,16 @@ TEST(FatalFailureTest, FatalFailureInNestedSubroutine) {
 // Tests HasFatalFailure() after a failed EXPECT check.
 TEST(FatalFailureTest, NonfatalFailureInSubroutine) {
   printf("(expecting a failure on false)\n");
-  EXPECT_TRUE(false);  // Generates a nonfatal failure
+  EXPECT_TRUE(false);               // Generates a nonfatal failure
   ASSERT_FALSE(HasFatalFailure());  // This should succeed.
 }
 
 // Tests interleaving user logging and Google Test assertions.
 TEST(LoggingTest, InterleavingLoggingAndAssertions) {
-  static const int a[4] = {
-    3, 9, 2, 6
-  };
+  static const int a[4] = {3, 9, 2, 6};
 
   printf("(expecting 2 failures on (3) >= (a[i]))\n");
-  for (int i = 0; i < static_cast<int>(sizeof(a)/sizeof(*a)); i++) {
+  for (int i = 0; i < static_cast<int>(sizeof(a) / sizeof(*a)); i++) {
     printf("i == %d\n", i);
     EXPECT_GE(3, a[i]);
   }
@@ -297,16 +288,14 @@ struct CheckPoints {
 static void ThreadWithScopedTrace(CheckPoints* check_points) {
   {
     SCOPED_TRACE("Trace B");
-    ADD_FAILURE()
-        << "Expected failure #1 (in thread B, only trace B alive).";
+    ADD_FAILURE() << "Expected failure #1 (in thread B, only trace B alive).";
     check_points->n1.Notify();
     check_points->n2.WaitForNotification();
 
     ADD_FAILURE()
         << "Expected failure #3 (in thread B, trace A & B both alive).";
   }  // Trace B dies here.
-  ADD_FAILURE()
-      << "Expected failure #4 (in thread B, only trace A alive).";
+  ADD_FAILURE() << "Expected failure #4 (in thread B, only trace A alive).";
   check_points->n3.Notify();
 }
 
@@ -325,11 +314,9 @@ TEST(SCOPED_TRACETest, WorksConcurrently) {
     check_points.n2.Notify();
     check_points.n3.WaitForNotification();
 
-    ADD_FAILURE()
-        << "Expected failure #5 (in thread A, only trace A alive).";
+    ADD_FAILURE() << "Expected failure #5 (in thread A, only trace A alive).";
   }  // Trace A dies here.
-  ADD_FAILURE()
-      << "Expected failure #6 (in thread A, no trace alive).";
+  ADD_FAILURE() << "Expected failure #6 (in thread A, no trace alive).";
   thread.Join();
 }
 #endif  // GTEST_IS_THREADSAFE
@@ -412,9 +399,7 @@ class FatalFailureInFixtureConstructorTest : public testing::Test {
   }
 
  private:
-  void Init() {
-    FAIL() << "Expected failure #1, in the test fixture c'tor.";
-  }
+  void Init() { FAIL() << "Expected failure #1, in the test fixture c'tor."; }
 };
 
 TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) {
@@ -436,9 +421,7 @@ class NonFatalFailureInSetUpTest : public testing::Test {
   void TearDown() override { FAIL() << "Expected failure #3, in TearDown()."; }
 
  private:
-  void Deinit() {
-    FAIL() << "Expected failure #4, in the test fixture d'tor.";
-  }
+  void Deinit() { FAIL() << "Expected failure #4, in the test fixture d'tor."; }
 };
 
 TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) {
@@ -458,9 +441,7 @@ class FatalFailureInSetUpTest : public testing::Test {
   void TearDown() override { FAIL() << "Expected failure #2, in TearDown()."; }
 
  private:
-  void Deinit() {
-    FAIL() << "Expected failure #3, in the test fixture d'tor.";
-  }
+  void Deinit() { FAIL() << "Expected failure #3, in the test fixture d'tor."; }
 };
 
 TEST_F(FatalFailureInSetUpTest, FailureInSetUp) {
@@ -488,14 +469,12 @@ TEST(GtestFailAtTest, MessageContainsSpecifiedFileAndLineNumber) {
 
 namespace foo {
 
-class MixedUpTestSuiteTest : public testing::Test {
-};
+class MixedUpTestSuiteTest : public testing::Test {};
 
 TEST_F(MixedUpTestSuiteTest, FirstTestFromNamespaceFoo) {}
 TEST_F(MixedUpTestSuiteTest, SecondTestFromNamespaceFoo) {}
 
-class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {
-};
+class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {};
 
 TEST_F(MixedUpTestSuiteWithSameTestNameTest,
        TheSecondTestWithThisNameShouldFail) {}
@@ -504,16 +483,14 @@ TEST_F(MixedUpTestSuiteWithSameTestNameTest,
 
 namespace bar {
 
-class MixedUpTestSuiteTest : public testing::Test {
-};
+class MixedUpTestSuiteTest : public testing::Test {};
 
 // The following two tests are expected to fail.  We rely on the
 // golden file to check that Google Test generates the right error message.
 TEST_F(MixedUpTestSuiteTest, ThisShouldFail) {}
 TEST_F(MixedUpTestSuiteTest, ThisShouldFailToo) {}
 
-class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {
-};
+class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {};
 
 // Expected to fail.  We rely on the golden file to check that Google Test
 // generates the right error message.
@@ -527,8 +504,7 @@ TEST_F(MixedUpTestSuiteWithSameTestNameTest,
 // test case checks the scenario where TEST_F appears before TEST, and
 // the second one checks where TEST appears before TEST_F.
 
-class TEST_F_before_TEST_in_same_test_case : public testing::Test {
-};
+class TEST_F_before_TEST_in_same_test_case : public testing::Test {};
 
 TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {}
 
@@ -536,15 +512,13 @@ TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {}
 // generates the right error message.
 TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {}
 
-class TEST_before_TEST_F_in_same_test_case : public testing::Test {
-};
+class TEST_before_TEST_F_in_same_test_case : public testing::Test {};
 
 TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {}
 
 // Expected to fail.  We rely on the golden file to check that Google Test
 // generates the right error message.
-TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) {
-}
+TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) {}
 
 // Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE().
 int global_integer = 0;
@@ -552,9 +526,9 @@ int global_integer = 0;
 // Tests that EXPECT_NONFATAL_FAILURE() can reference global variables.
 TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) {
   global_integer = 0;
-  EXPECT_NONFATAL_FAILURE({
-    EXPECT_EQ(1, global_integer) << "Expected non-fatal failure.";
-  }, "Expected non-fatal failure.");
+  EXPECT_NONFATAL_FAILURE(
+      { EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; },
+      "Expected non-fatal failure.");
 }
 
 // Tests that EXPECT_NONFATAL_FAILURE() can reference local variables
@@ -563,53 +537,48 @@ TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) {
   int m = 0;
   static int n;
   n = 1;
-  EXPECT_NONFATAL_FAILURE({
-    EXPECT_EQ(m, n) << "Expected non-fatal failure.";
-  }, "Expected non-fatal failure.");
+  EXPECT_NONFATAL_FAILURE({ EXPECT_EQ(m, n) << "Expected non-fatal failure."; },
+                          "Expected non-fatal failure.");
 }
 
 // Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly
 // one non-fatal failure and no fatal failure.
 TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) {
-  EXPECT_NONFATAL_FAILURE({
-    ADD_FAILURE() << "Expected non-fatal failure.";
-  }, "Expected non-fatal failure.");
+  EXPECT_NONFATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; },
+                          "Expected non-fatal failure.");
 }
 
 // Tests that EXPECT_NONFATAL_FAILURE() fails when there is no
 // non-fatal failure.
 TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) {
   printf("(expecting a failure)\n");
-  EXPECT_NONFATAL_FAILURE({
-  }, "");
+  EXPECT_NONFATAL_FAILURE({}, "");
 }
 
 // Tests that EXPECT_NONFATAL_FAILURE() fails when there are two
 // non-fatal failures.
 TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) {
   printf("(expecting a failure)\n");
-  EXPECT_NONFATAL_FAILURE({
-    ADD_FAILURE() << "Expected non-fatal failure 1.";
-    ADD_FAILURE() << "Expected non-fatal failure 2.";
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {
+        ADD_FAILURE() << "Expected non-fatal failure 1.";
+        ADD_FAILURE() << "Expected non-fatal failure 2.";
+      },
+      "");
 }
 
 // Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal
 // failure.
 TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) {
   printf("(expecting a failure)\n");
-  EXPECT_NONFATAL_FAILURE({
-    FAIL() << "Expected fatal failure.";
-  }, "");
+  EXPECT_NONFATAL_FAILURE({ FAIL() << "Expected fatal failure."; }, "");
 }
 
 // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
 // tested returns.
 TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
   printf("(expecting a failure)\n");
-  EXPECT_NONFATAL_FAILURE({
-    return;
-  }, "");
+  EXPECT_NONFATAL_FAILURE({ return; }, "");
 }
 
 #if GTEST_HAS_EXCEPTIONS
@@ -619,10 +588,8 @@ TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
 TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
   printf("(expecting a failure)\n");
   try {
-    EXPECT_NONFATAL_FAILURE({
-      throw 0;
-    }, "");
-  } catch(int) {  // NOLINT
+    EXPECT_NONFATAL_FAILURE({ throw 0; }, "");
+  } catch (int) {  // NOLINT
   }
 }
 
@@ -631,9 +598,9 @@ TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
 // Tests that EXPECT_FATAL_FAILURE() can reference global variables.
 TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
   global_integer = 0;
-  EXPECT_FATAL_FAILURE({
-    ASSERT_EQ(1, global_integer) << "Expected fatal failure.";
-  }, "Expected fatal failure.");
+  EXPECT_FATAL_FAILURE(
+      { ASSERT_EQ(1, global_integer) << "Expected fatal failure."; },
+      "Expected fatal failure.");
 }
 
 // Tests that EXPECT_FATAL_FAILURE() can reference local static
@@ -641,58 +608,51 @@ TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
 TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) {
   static int n;
   n = 1;
-  EXPECT_FATAL_FAILURE({
-    ASSERT_EQ(0, n) << "Expected fatal failure.";
-  }, "Expected fatal failure.");
+  EXPECT_FATAL_FAILURE({ ASSERT_EQ(0, n) << "Expected fatal failure."; },
+                       "Expected fatal failure.");
 }
 
 // Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly
 // one fatal failure and no non-fatal failure.
 TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) {
-  EXPECT_FATAL_FAILURE({
-    FAIL() << "Expected fatal failure.";
-  }, "Expected fatal failure.");
+  EXPECT_FATAL_FAILURE({ FAIL() << "Expected fatal failure."; },
+                       "Expected fatal failure.");
 }
 
 // Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal
 // failure.
 TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) {
   printf("(expecting a failure)\n");
-  EXPECT_FATAL_FAILURE({
-  }, "");
+  EXPECT_FATAL_FAILURE({}, "");
 }
 
 // A helper for generating a fatal failure.
-void FatalFailure() {
-  FAIL() << "Expected fatal failure.";
-}
+void FatalFailure() { FAIL() << "Expected fatal failure."; }
 
 // Tests that EXPECT_FATAL_FAILURE() fails when there are two
 // fatal failures.
 TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) {
   printf("(expecting a failure)\n");
-  EXPECT_FATAL_FAILURE({
-    FatalFailure();
-    FatalFailure();
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {
+        FatalFailure();
+        FatalFailure();
+      },
+      "");
 }
 
 // Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal
 // failure.
 TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) {
   printf("(expecting a failure)\n");
-  EXPECT_FATAL_FAILURE({
-    ADD_FAILURE() << "Expected non-fatal failure.";
-  }, "");
+  EXPECT_FATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; }, "");
 }
 
 // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
 // tested returns.
 TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
   printf("(expecting a failure)\n");
-  EXPECT_FATAL_FAILURE({
-    return;
-  }, "");
+  EXPECT_FATAL_FAILURE({ return; }, "");
 }
 
 #if GTEST_HAS_EXCEPTIONS
@@ -702,10 +662,8 @@ TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
 TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) {
   printf("(expecting a failure)\n");
   try {
-    EXPECT_FATAL_FAILURE({
-      throw 0;
-    }, "");
-  } catch(int) {  // NOLINT
+    EXPECT_FATAL_FAILURE({ throw 0; }, "");
+  } catch (int) {  // NOLINT
   }
 }
 
@@ -717,21 +675,14 @@ std::string ParamNameFunc(const testing::TestParamInfo<std::string>& info) {
   return info.param;
 }
 
-class ParamTest : public testing::TestWithParam<std::string> {
-};
+class ParamTest : public testing::TestWithParam<std::string> {};
 
-TEST_P(ParamTest, Success) {
-  EXPECT_EQ("a", GetParam());
-}
+TEST_P(ParamTest, Success) { EXPECT_EQ("a", GetParam()); }
 
-TEST_P(ParamTest, Failure) {
-  EXPECT_EQ("b", GetParam()) << "Expected failure";
-}
+TEST_P(ParamTest, Failure) { EXPECT_EQ("b", GetParam()) << "Expected failure"; }
 
-INSTANTIATE_TEST_SUITE_P(PrintingStrings,
-                         ParamTest,
-                         testing::Values(std::string("a")),
-                         ParamNameFunc);
+INSTANTIATE_TEST_SUITE_P(PrintingStrings, ParamTest,
+                         testing::Values(std::string("a")), ParamNameFunc);
 
 // The case where a suite has INSTANTIATE_TEST_SUITE_P but not TEST_P.
 using NoTests = ParamTest;
@@ -739,20 +690,17 @@ INSTANTIATE_TEST_SUITE_P(ThisIsOdd, NoTests, ::testing::Values("Hello"));
 
 // fails under kErrorOnUninstantiatedParameterizedTest=true
 class DetectNotInstantiatedTest : public testing::TestWithParam<int> {};
-TEST_P(DetectNotInstantiatedTest, Used) { }
+TEST_P(DetectNotInstantiatedTest, Used) {}
 
 // This would make the test failure from the above go away.
 // INSTANTIATE_TEST_SUITE_P(Fix, DetectNotInstantiatedTest, testing::Values(1));
 
 template <typename T>
-class TypedTest : public testing::Test {
-};
+class TypedTest : public testing::Test {};
 
 TYPED_TEST_SUITE(TypedTest, testing::Types<int>);
 
-TYPED_TEST(TypedTest, Success) {
-  EXPECT_EQ(0, TypeParam());
-}
+TYPED_TEST(TypedTest, Success) { EXPECT_EQ(0, TypeParam()); }
 
 TYPED_TEST(TypedTest, Failure) {
   EXPECT_EQ(1, TypeParam()) << "Expected failure";
@@ -781,14 +729,11 @@ TYPED_TEST(TypedTestWithNames, Success) {}
 TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); }
 
 template <typename T>
-class TypedTestP : public testing::Test {
-};
+class TypedTestP : public testing::Test {};
 
 TYPED_TEST_SUITE_P(TypedTestP);
 
-TYPED_TEST_P(TypedTestP, Success) {
-  EXPECT_EQ(0U, TypeParam());
-}
+TYPED_TEST_P(TypedTestP, Success) { EXPECT_EQ(0U, TypeParam()); }
 
 TYPED_TEST_P(TypedTestP, Failure) {
   EXPECT_EQ(1U, TypeParam()) << "Expected failure";
@@ -813,7 +758,7 @@ class TypedTestPNames {
 };
 
 INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes,
-                              TypedTestPNames);
+                               TypedTestPNames);
 
 template <typename T>
 class DetectNotInstantiatedTypesTest : public testing::Test {};
@@ -835,34 +780,28 @@ REGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest, Used);
 // We rely on the golden file to verify that tests whose test case
 // name ends with DeathTest are run first.
 
-TEST(ADeathTest, ShouldRunFirst) {
-}
+TEST(ADeathTest, ShouldRunFirst) {}
 
 // We rely on the golden file to verify that typed tests whose test
 // case name ends with DeathTest are run first.
 
 template <typename T>
-class ATypedDeathTest : public testing::Test {
-};
+class ATypedDeathTest : public testing::Test {};
 
 typedef testing::Types<int, double> NumericTypes;
 TYPED_TEST_SUITE(ATypedDeathTest, NumericTypes);
 
-TYPED_TEST(ATypedDeathTest, ShouldRunFirst) {
-}
-
+TYPED_TEST(ATypedDeathTest, ShouldRunFirst) {}
 
 // We rely on the golden file to verify that type-parameterized tests
 // whose test case name ends with DeathTest are run first.
 
 template <typename T>
-class ATypeParamDeathTest : public testing::Test {
-};
+class ATypeParamDeathTest : public testing::Test {};
 
 TYPED_TEST_SUITE_P(ATypeParamDeathTest);
 
-TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) {
-}
+TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) {}
 
 REGISTER_TYPED_TEST_SUITE_P(ATypeParamDeathTest, ShouldRunFirst);
 
@@ -874,10 +813,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, ATypeParamDeathTest, NumericTypes);
 // EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}.
 class ExpectFailureTest : public testing::Test {
  public:  // Must be public and not protected due to a bug in g++ 3.4.2.
-  enum FailureMode {
-    FATAL_FAILURE,
-    NONFATAL_FAILURE
-  };
+  enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE };
   static void AddFailure(FailureMode failure) {
     if (failure == FATAL_FAILURE) {
       FAIL() << "Expected fatal failure.";
@@ -893,11 +829,13 @@ TEST_F(ExpectFailureTest, ExpectFatalFailure) {
   EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure.");
   // Expected fatal failure, but got a non-fatal failure.
   printf("(expecting 1 failure)\n");
-  EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Expected non-fatal "
+  EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE),
+                       "Expected non-fatal "
                        "failure.");
   // Wrong message.
   printf("(expecting 1 failure)\n");
-  EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), "Some other fatal failure "
+  EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE),
+                       "Some other fatal failure "
                        "expected.");
 }
 
@@ -910,7 +848,8 @@ TEST_F(ExpectFailureTest, ExpectNonFatalFailure) {
   EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure.");
   // Wrong message.
   printf("(expecting 1 failure)\n");
-  EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Some other non-fatal "
+  EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE),
+                          "Some other non-fatal "
                           "failure.");
 }
 
@@ -975,7 +914,8 @@ TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) {
 TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) {
   // Expected non-fatal failure, but succeeds.
   printf("(expecting 1 failure)\n");
-  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected non-fatal "
+  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(),
+                                         "Expected non-fatal "
                                          "failure.");
   // Expected non-fatal failure, but got a fatal failure.
   printf("(expecting 1 failure)\n");
@@ -1060,20 +1000,26 @@ class BarEnvironment : public testing::Environment {
   }
 };
 
+class TestSuiteThatFailsToSetUp : public testing::Test {
+ public:
+  static void SetUpTestSuite() { EXPECT_TRUE(false); }
+};
+TEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { std::abort(); }
+
 // The main function.
 //
 // The idea is to use Google Test to run all the tests we have defined (some
 // of them are intended to fail), and then compare the test results
 // with the "golden" file.
-int main(int argc, char **argv) {
-  testing::GTEST_FLAG(print_time) = false;
+int main(int argc, char** argv) {
+  GTEST_FLAG_SET(print_time, false);
 
   // We just run the tests, knowing some of them are intended to fail.
   // We will use a separate Python script to compare the output of
   // this program with the golden file.
 
   // It's hard to test InitGoogleTest() directly, as it has many
-  // global side effects.  The following line serves as a sanity test
+  // global side effects.  The following line serves as a test
   // for it.
   testing::InitGoogleTest(&argc, argv);
   bool internal_skip_environment_and_ad_hoc_tests =
@@ -1081,20 +1027,19 @@ int main(int argc, char **argv) {
                  std::string("internal_skip_environment_and_ad_hoc_tests")) > 0;
 
 #if GTEST_HAS_DEATH_TEST
-  if (testing::internal::GTEST_FLAG(internal_run_death_test) != "") {
+  if (GTEST_FLAG_GET(internal_run_death_test) != "") {
     // Skip the usual output capturing if we're running as the child
     // process of an threadsafe-style death test.
-# if GTEST_OS_WINDOWS
+#if GTEST_OS_WINDOWS
     posix::FReopen("nul:", "w", stdout);
-# else
+#else
     posix::FReopen("/dev/null", "w", stdout);
-# endif  // GTEST_OS_WINDOWS
+#endif  // GTEST_OS_WINDOWS
     return RUN_ALL_TESTS();
   }
 #endif  // GTEST_HAS_DEATH_TEST
 
-  if (internal_skip_environment_and_ad_hoc_tests)
-    return RUN_ALL_TESTS();
+  if (internal_skip_environment_and_ad_hoc_tests) return RUN_ALL_TESTS();
 
   // Registers two global test environments.
   // The golden file verifies that they are set up in the order they
@@ -1102,7 +1047,7 @@ int main(int argc, char **argv) {
   testing::AddGlobalTestEnvironment(new FooEnvironment);
   testing::AddGlobalTestEnvironment(new BarEnvironment);
 #if _MSC_VER
-GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4127
-#endif  //  _MSC_VER
+  GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4127
+#endif                               //  _MSC_VER
   return RunAllTests();
 }
index 2a08477a77ebdf0aa55f23444abd6b839d90ba43..b8d609a700c85a283cd30b2c2b3c83623851dab8 100644 (file)
@@ -30,7 +30,7 @@
 
 """Verifies that Google Test warns the user when not initialized properly."""
 
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 binary_name = 'googletest-param-test-invalid-name1-test_'
 COMMAND = gtest_test_utils.GetTestExecutablePath(binary_name)
index 955d699900d8cd8eb19b251d35d6d5f7ee82e604..004733a12c5007da354da92474e17b17fefd842b 100644 (file)
 // (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) {
-}
+TEST_P(DummyTest, Dummy) {}
 
-INSTANTIATE_TEST_SUITE_P(InvalidTestName,
-                         DummyTest,
+INSTANTIATE_TEST_SUITE_P(InvalidTestName, DummyTest,
                          ::testing::Values("InvalidWithQuotes"),
                          ::testing::PrintToStringParamName());
 
@@ -47,4 +44,3 @@ int main(int argc, char *argv[]) {
   testing::InitGoogleTest(&argc, argv);
   return RUN_ALL_TESTS();
 }
-
index ab838f4632291d1cb78e4a11ec3ab0c773b94d5c..d92fa065ae2312bf9ea63272b22612cf372e3ada 100644 (file)
@@ -30,7 +30,7 @@
 
 """Verifies that Google Test warns the user when not initialized properly."""
 
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 binary_name = 'googletest-param-test-invalid-name2-test_'
 COMMAND = gtest_test_utils.GetTestExecutablePath(binary_name)
index 76371df54f0b3e2f277364dd8a22d02823c2eecc..d0c44da544594949c10ad632fe132f9aa629e85e 100644 (file)
 // (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) {
+    const testing::TestParamInfo<const char *> &info) {
   return std::string(info.param);
 }
 
-TEST_P(DummyTest, Dummy) {
-}
+TEST_P(DummyTest, Dummy) {}
 
-INSTANTIATE_TEST_SUITE_P(DuplicateTestNames,
-                         DummyTest,
+INSTANTIATE_TEST_SUITE_P(DuplicateTestNames, DummyTest,
                          ::testing::Values("a", "b", "a", "c"),
                          StringParamTestSuffix);
 }  // namespace
@@ -51,5 +48,3 @@ int main(int argc, char *argv[]) {
   testing::InitGoogleTest(&argc, argv);
   return RUN_ALL_TESTS();
 }
-
-
index 023aa46d69f939cfa853ca022725982cbf14d55f..848ef9752cb090caf6615c3988eb338157c5524a 100644 (file)
 // generators objects produce correct parameter sequences and that
 // Google Test runtime instantiates correct tests from those sequences.
 
-#include "gtest/gtest.h"
+#include "test/googletest-param-test-test.h"
 
-# include <algorithm>
-# include <iostream>
-# include <list>
-# include <set>
-# include <sstream>
-# include <string>
-# include <vector>
+#include <algorithm>
+#include <iostream>
+#include <list>
+#include <set>
+#include <sstream>
+#include <string>
+#include <vector>
 
-# include "src/gtest-internal-inl.h"  // for UnitTestOptions
-# include "test/googletest-param-test-test.h"
+#include "gtest/gtest.h"
+#include "src/gtest-internal-inl.h"  // for UnitTestOptions
 
-using ::std::vector;
 using ::std::sort;
+using ::std::vector;
 
 using ::testing::AddGlobalTestEnvironment;
 using ::testing::Bool;
@@ -85,15 +85,14 @@ void VerifyGenerator(const ParamGenerator<T>& generator,
     // We cannot use EXPECT_EQ() here as the values may be tuples,
     // which don't support <<.
     EXPECT_TRUE(expected_values[i] == *it)
-        << "where i is " << i
-        << ", expected_values[i] is " << PrintValue(expected_values[i])
-        << ", *it is " << PrintValue(*it)
+        << "where i is " << i << ", expected_values[i] is "
+        << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it)
         << ", and 'it' is an iterator created with the copy constructor.\n";
     ++it;
   }
   EXPECT_TRUE(it == generator.end())
-        << "At the presumed end of sequence when accessing via an iterator "
-        << "created with the copy constructor.\n";
+      << "At the presumed end of sequence when accessing via an iterator "
+      << "created with the copy constructor.\n";
 
   // Test the iterator assignment. The following lines verify that
   // the sequence accessed via an iterator initialized via the
@@ -105,15 +104,14 @@ void VerifyGenerator(const ParamGenerator<T>& generator,
         << "At element " << i << " when accessing via an iterator "
         << "created with the assignment operator.\n";
     EXPECT_TRUE(expected_values[i] == *it)
-        << "where i is " << i
-        << ", expected_values[i] is " << PrintValue(expected_values[i])
-        << ", *it is " << PrintValue(*it)
+        << "where i is " << i << ", expected_values[i] is "
+        << PrintValue(expected_values[i]) << ", *it is " << PrintValue(*it)
         << ", and 'it' is an iterator created with the copy constructor.\n";
     ++it;
   }
   EXPECT_TRUE(it == generator.end())
-        << "At the presumed end of sequence when accessing via an iterator "
-        << "created with the assignment operator.\n";
+      << "At the presumed end of sequence when accessing via an iterator "
+      << "created with the assignment operator.\n";
 }
 
 template <typename T>
@@ -216,8 +214,7 @@ class DogAdder {
   DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {}
 
   DogAdder operator=(const DogAdder& other) {
-    if (this != &other)
-      value_ = other.value_;
+    if (this != &other) value_ = other.value_;
     return *this;
   }
   DogAdder operator+(const DogAdder& other) const {
@@ -225,9 +222,7 @@ class DogAdder {
     msg << value_.c_str() << other.value_.c_str();
     return DogAdder(msg.GetString().c_str());
   }
-  bool operator<(const DogAdder& other) const {
-    return value_ < other.value_;
-  }
+  bool operator<(const DogAdder& other) const { return value_ < other.value_; }
   const std::string& value() const { return value_; }
 
  private:
@@ -372,19 +367,17 @@ TEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) {
 }
 
 TEST(ValuesTest, ValuesWorksForMaxLengthList) {
-  const ParamGenerator<int> gen = Values(
-      10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
-      110, 120, 130, 140, 150, 160, 170, 180, 190, 200,
-      210, 220, 230, 240, 250, 260, 270, 280, 290, 300,
-      310, 320, 330, 340, 350, 360, 370, 380, 390, 400,
-      410, 420, 430, 440, 450, 460, 470, 480, 490, 500);
+  const ParamGenerator<int> gen =
+      Values(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150,
+             160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280,
+             290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410,
+             420, 430, 440, 450, 460, 470, 480, 490, 500);
 
   const int expected_values[] = {
-      10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
-      110, 120, 130, 140, 150, 160, 170, 180, 190, 200,
-      210, 220, 230, 240, 250, 260, 270, 280, 290, 300,
-      310, 320, 330, 340, 350, 360, 370, 380, 390, 400,
-      410, 420, 430, 440, 450, 460, 470, 480, 490, 500};
+      10,  20,  30,  40,  50,  60,  70,  80,  90,  100, 110, 120, 130,
+      140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260,
+      270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390,
+      400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500};
   VerifyGenerator(gen, expected_values);
 }
 
@@ -530,7 +523,6 @@ TEST(CombineTest, NonDefaultConstructAssign) {
   EXPECT_TRUE(it == gen.end());
 }
 
-
 // Tests that an generator produces correct sequence after being
 // assigned from another generator.
 TEST(ParamGeneratorTest, AssignmentWorks) {
@@ -573,7 +565,7 @@ class TestGenerationEnvironment : public ::testing::Environment {
       Message msg;
       msg << "TestsExpandedAndRun/" << i;
       if (UnitTestOptions::FilterMatchesTest(
-             "TestExpansionModule/MultipleTestGenerationTest",
+              "TestExpansionModule/MultipleTestGenerationTest",
               msg.GetString().c_str())) {
         perform_check = true;
       }
@@ -595,15 +587,20 @@ class TestGenerationEnvironment : public ::testing::Environment {
   }
 
  private:
-  TestGenerationEnvironment() : fixture_constructor_count_(0), set_up_count_(0),
-                                tear_down_count_(0), test_body_count_(0) {}
+  TestGenerationEnvironment()
+      : fixture_constructor_count_(0),
+        set_up_count_(0),
+        tear_down_count_(0),
+        test_body_count_(0) {}
 
   int fixture_constructor_count_;
   int set_up_count_;
   int tear_down_count_;
   int test_body_count_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationEnvironment);
+  TestGenerationEnvironment(const TestGenerationEnvironment&) = delete;
+  TestGenerationEnvironment& operator=(const TestGenerationEnvironment&) =
+      delete;
 };
 
 const int test_generation_params[] = {36, 42, 72};
@@ -612,7 +609,7 @@ class TestGenerationTest : public TestWithParam<int> {
  public:
   enum {
     PARAMETER_COUNT =
-        sizeof(test_generation_params)/sizeof(test_generation_params[0])
+        sizeof(test_generation_params) / sizeof(test_generation_params[0])
   };
 
   typedef TestGenerationEnvironment<PARAMETER_COUNT> Environment;
@@ -636,9 +633,9 @@ class TestGenerationTest : public TestWithParam<int> {
     for (int i = 0; i < PARAMETER_COUNT; ++i) {
       Message test_name;
       test_name << "TestsExpandedAndRun/" << i;
-      if ( !UnitTestOptions::FilterMatchesTest(
-                "TestExpansionModule/MultipleTestGenerationTest",
-                test_name.GetString())) {
+      if (!UnitTestOptions::FilterMatchesTest(
+              "TestExpansionModule/MultipleTestGenerationTest",
+              test_name.GetString())) {
         all_tests_in_test_case_selected = false;
       }
     }
@@ -668,7 +665,8 @@ class TestGenerationTest : public TestWithParam<int> {
   static vector<int> collected_parameters_;
 
  private:
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestGenerationTest);
+  TestGenerationTest(const TestGenerationTest&) = delete;
+  TestGenerationTest& operator=(const TestGenerationTest&) = delete;
 };
 vector<int> TestGenerationTest::collected_parameters_;
 
@@ -729,8 +727,7 @@ TEST_P(ExternalInstantiationTest, IsMultipleOf33) {
 // Tests that a parameterized test case can be instantiated with multiple
 // generators.
 class MultipleInstantiationTest : public TestWithParam<int> {};
-TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) {
-}
+TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) {}
 INSTANTIATE_TEST_SUITE_P(Sequence1, MultipleInstantiationTest, Values(1, 2));
 INSTANTIATE_TEST_SUITE_P(Sequence2, MultipleInstantiationTest, Range(3, 5));
 
@@ -780,7 +777,7 @@ class NamingTest : public TestWithParam<int> {};
 
 TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) {
   const ::testing::TestInfo* const test_info =
-     ::testing::UnitTest::GetInstance()->current_test_info();
+      ::testing::UnitTest::GetInstance()->current_test_info();
 
   EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_suite_name());
 
@@ -801,7 +798,7 @@ class MacroNamingTest : public TestWithParam<int> {};
 
 TEST_P(PREFIX_WITH_MACRO(NamingTest), PREFIX_WITH_FOO(SomeTestName)) {
   const ::testing::TestInfo* const test_info =
-     ::testing::UnitTest::GetInstance()->current_test_info();
+      ::testing::UnitTest::GetInstance()->current_test_info();
 
   EXPECT_STREQ("FortyTwo/MacroNamingTest", test_info->test_suite_name());
   EXPECT_STREQ("FooSomeTestName/0", test_info->name());
@@ -815,7 +812,7 @@ 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();
+      ::testing::UnitTest::GetInstance()->current_test_info();
 
   EXPECT_STREQ("MacroNamingTestNonParametrized", test_info->test_suite_name());
   EXPECT_STREQ("FooSomeTestName", test_info->name());
@@ -839,9 +836,8 @@ TEST(MacroNameing, LookupNames) {
   EXPECT_NE(  //
       know_suite_names.find("FortyTwo/MacroNamingTest"),
       know_suite_names.end());
-  EXPECT_NE(
-      know_suite_names.find("MacroNamingTestNonParametrized"),
-      know_suite_names.end());
+  EXPECT_NE(know_suite_names.find("MacroNamingTestNonParametrized"),
+            know_suite_names.end());
   // Check that the expected form of the test name actually exists.
   EXPECT_NE(  //
       know_test_names.find("FortyTwo/MacroNamingTest.FooSomeTestName/0"),
@@ -924,7 +920,7 @@ class CustomIntegerNamingTest : public TestWithParam<int> {};
 
 TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) {
   const ::testing::TestInfo* const test_info =
-     ::testing::UnitTest::GetInstance()->current_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());
@@ -949,7 +945,7 @@ class CustomStructNamingTest : public TestWithParam<CustomStruct> {};
 
 TEST_P(CustomStructNamingTest, TestsReportCorrectNames) {
   const ::testing::TestInfo* const test_info =
-     ::testing::UnitTest::GetInstance()->current_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());
@@ -979,7 +975,7 @@ class StatefulNamingTest : public ::testing::TestWithParam<int> {
 
 TEST_P(StatefulNamingTest, TestsReportCorrectNames) {
   const ::testing::TestInfo* const test_info =
-     ::testing::UnitTest::GetInstance()->current_test_info();
+      ::testing::UnitTest::GetInstance()->current_test_info();
   sum_ += GetParam();
   Message test_name_stream;
   test_name_stream << "TestsReportCorrectNames/" << sum_;
@@ -1007,7 +1003,7 @@ class CommentTest : public TestWithParam<Unstreamable> {};
 
 TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) {
   const ::testing::TestInfo* const test_info =
-     ::testing::UnitTest::GetInstance()->current_test_info();
+      ::testing::UnitTest::GetInstance()->current_test_info();
 
   EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());
 }
@@ -1021,7 +1017,8 @@ INSTANTIATE_TEST_SUITE_P(InstantiationWithComments, CommentTest,
 // perform simple tests on both.
 class NonParameterizedBaseTest : public ::testing::Test {
  public:
-  NonParameterizedBaseTest() : n_(17) { }
+  NonParameterizedBaseTest() : n_(17) {}
+
  protected:
   int n_;
 };
@@ -1029,16 +1026,14 @@ class NonParameterizedBaseTest : public ::testing::Test {
 class ParameterizedDerivedTest : public NonParameterizedBaseTest,
                                  public ::testing::WithParamInterface<int> {
  protected:
-  ParameterizedDerivedTest() : count_(0) { }
+  ParameterizedDerivedTest() : count_(0) {}
   int count_;
   static int global_count_;
 };
 
 int ParameterizedDerivedTest::global_count_ = 0;
 
-TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) {
-  EXPECT_EQ(17, n_);
-}
+TEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { EXPECT_EQ(17, n_); }
 
 TEST_P(ParameterizedDerivedTest, SeesSequence) {
   EXPECT_EQ(17, n_);
@@ -1046,11 +1041,10 @@ TEST_P(ParameterizedDerivedTest, SeesSequence) {
   EXPECT_EQ(GetParam(), global_count_++);
 }
 
-class ParameterizedDeathTest : public ::testing::TestWithParam<int> { };
+class ParameterizedDeathTest : public ::testing::TestWithParam<int> {};
 
 TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) {
-  EXPECT_DEATH_IF_SUPPORTED(GetParam(),
-                            ".* value-parameterized test .*");
+  EXPECT_DEATH_IF_SUPPORTED(GetParam(), ".* value-parameterized test .*");
 }
 
 INSTANTIATE_TEST_SUITE_P(RangeZeroToFive, ParameterizedDerivedTest,
@@ -1084,11 +1078,11 @@ class NotInstantiatedTest : public testing::TestWithParam<int> {};
 // ... we mark is as allowed.
 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTest);
 
-TEST_P(NotInstantiatedTest, Used) { }
+TEST_P(NotInstantiatedTest, Used) {}
 
 using OtherName = NotInstantiatedTest;
 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OtherName);
-TEST_P(OtherName, Used) { }
+TEST_P(OtherName, Used) {}
 
 // Used but not instantiated, this would fail. but...
 template <typename T>
@@ -1097,11 +1091,11 @@ TYPED_TEST_SUITE_P(NotInstantiatedTypeTest);
 // ... we mark is as allowed.
 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTypeTest);
 
-TYPED_TEST_P(NotInstantiatedTypeTest, Used) { }
+TYPED_TEST_P(NotInstantiatedTypeTest, Used) {}
 REGISTER_TYPED_TEST_SUITE_P(NotInstantiatedTypeTest, Used);
 }  // namespace works_here
 
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
   // Used in TestGenerationTest test suite.
   AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance());
   // Used in GeneratorEvaluationTest test suite. Tests that the updated value
index 891937538d0126e94cd3d947adec31a56134afc2..6d77e1049abc83906546e950be3f778474a440d3 100644 (file)
 
 // Test fixture for testing definition and instantiation of a test
 // in separate translation units.
-class ExternalInstantiationTest : public ::testing::TestWithParam<int> {
-};
+class ExternalInstantiationTest : public ::testing::TestWithParam<int> {};
 
 // Test fixture for testing instantiation of a test in multiple
 // translation units.
 class InstantiationInMultipleTranslationUnitsTest
-    : public ::testing::TestWithParam<int> {
-};
+    : public ::testing::TestWithParam<int> {};
 
 #endif  // GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_
index 2a29fb1d0686e2a4ec7c67c8912ff6a38f89ccd0..71727a674f099d11f26a1d00a4af6c6135fb3509 100644 (file)
@@ -46,8 +46,7 @@ ParamGenerator<int> extern_gen = Values(33);
 // 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_SUITE_P(MultiplesOf33,
-                         ExternalInstantiationTest,
+INSTANTIATE_TEST_SUITE_P(MultiplesOf33, ExternalInstantiationTest,
                          Values(33, 66));
 
 // Tests that a parameterized test case can be instantiated
@@ -55,7 +54,5 @@ INSTANTIATE_TEST_SUITE_P(MultiplesOf33,
 // in googletest-param-test-test.cc and
 // InstantiationInMultipleTranslationUnitsTest fixture is defined in
 // gtest-param-test_test.h
-INSTANTIATE_TEST_SUITE_P(Sequence2,
-                         InstantiationInMultipleTranslationUnitsTest,
-                         Values(42*3, 42*4, 42*5));
-
+INSTANTIATE_TEST_SUITE_P(Sequence2, InstantiationInMultipleTranslationUnitsTest,
+                         Values(42 * 3, 42 * 4, 42 * 5));
index 1e0c8616322a727e90dab4ef194ccbb035c120ab..c20dfa4c4ca847a36ac30a54fcc2b31dc936e213 100644 (file)
 #include "gtest/internal/gtest-port.h"
 
 #if GTEST_OS_MAC
-# include <time.h>
+#include <time.h>
 #endif  // GTEST_OS_MAC
 
+#include <chrono>  // NOLINT
 #include <list>
 #include <memory>
+#include <thread>   // NOLINT
 #include <utility>  // For std::pair and std::make_pair.
 #include <vector>
 
-#include "gtest/gtest.h"
 #include "gtest/gtest-spi.h"
+#include "gtest/gtest.h"
 #include "src/gtest-internal-inl.h"
 
 using std::make_pair;
@@ -236,8 +238,8 @@ TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
   }
 
   switch (0)
-    case 0:
-      GTEST_CHECK_(true) << "Check failed in switch case";
+  case 0:
+    GTEST_CHECK_(true) << "Check failed in switch case";
 }
 
 // Verifies behavior of FormatFileLocation.
@@ -279,8 +281,8 @@ TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
 }
 
 #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA || \
-    GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
-    GTEST_OS_NETBSD || GTEST_OS_OPENBSD
+    GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD ||    \
+    GTEST_OS_NETBSD || GTEST_OS_OPENBSD || GTEST_OS_GNU_HURD
 void* ThreadFunc(void* data) {
   internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
   mutex->Lock();
@@ -289,36 +291,61 @@ void* ThreadFunc(void* data) {
 }
 
 TEST(GetThreadCountTest, ReturnsCorrectValue) {
-  const size_t starting_count = GetThreadCount();
-  pthread_t       thread_id;
+  size_t starting_count;
+  size_t thread_count_after_create;
+  size_t thread_count_after_join;
+
+  // We can't guarantee that no other thread was created or destroyed between
+  // any two calls to GetThreadCount(). We make multiple attempts, hoping that
+  // background noise is not constant and we would see the "right" values at
+  // some point.
+  for (int attempt = 0; attempt < 20; ++attempt) {
+    starting_count = GetThreadCount();
+    pthread_t thread_id;
+
+    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);
+    }
 
-  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());
-  }
+    thread_count_after_create = GetThreadCount();
 
-  void* dummy;
-  ASSERT_EQ(0, pthread_join(thread_id, &dummy));
+    void* dummy;
+    ASSERT_EQ(0, pthread_join(thread_id, &dummy));
 
-  // 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() == starting_count)
-      break;
+    // Join before we decide whether we need to retry the test. Retry if an
+    // arbitrary other thread was created or destroyed in the meantime.
+    if (thread_count_after_create != starting_count + 1) continue;
+
+    // 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.
+    bool thread_count_matches = false;
+    for (int i = 0; i < 5; ++i) {
+      thread_count_after_join = GetThreadCount();
+      if (thread_count_after_join == starting_count) {
+        thread_count_matches = true;
+        break;
+      }
+
+      std::this_thread::sleep_for(std::chrono::milliseconds(100));
+    }
+
+    // Retry if an arbitrary other thread was created or destroyed.
+    if (!thread_count_matches) continue;
 
-    SleepMilliseconds(100);
+    break;
   }
 
-  EXPECT_EQ(starting_count, GetThreadCount());
+  EXPECT_EQ(thread_count_after_create, starting_count + 1);
+  EXPECT_EQ(thread_count_after_join, starting_count);
 }
 #else
 TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
@@ -330,13 +357,13 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
   const bool a_false_condition = false;
   const char regex[] =
 #ifdef _MSC_VER
-     "googletest-port-test\\.cc\\(\\d+\\):"
+      "googletest-port-test\\.cc\\(\\d+\\):"
 #elif GTEST_USES_POSIX_RE
-     "googletest-port-test\\.cc:[0-9]+"
+      "googletest-port-test\\.cc:[0-9]+"
 #else
-     "googletest-port-test\\.cc:\\d+"
+      "googletest-port-test\\.cc:\\d+"
 #endif  // _MSC_VER
-     ".*a_false_condition.*Extra info.*";
+      ".*a_false_condition.*Extra info.*";
 
   EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
                             regex);
@@ -345,10 +372,12 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
 #if GTEST_HAS_DEATH_TEST
 
 TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
-  EXPECT_EXIT({
-      GTEST_CHECK_(true) << "Extra info";
-      ::std::cerr << "Success\n";
-      exit(0); },
+  EXPECT_EXIT(
+      {
+        GTEST_CHECK_(true) << "Extra info";
+        ::std::cerr << "Success\n";
+        exit(0);
+      },
       ::testing::ExitedWithCode(0), "Success");
 }
 
@@ -358,17 +387,13 @@ 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_USES_PCRE
-# if GTEST_HAS_POSIX_RE
-
+#if GTEST_HAS_ABSL
+  EXPECT_TRUE(GTEST_USES_RE2);
+#elif GTEST_HAS_POSIX_RE
   EXPECT_TRUE(GTEST_USES_POSIX_RE);
-
-# else
-
+#else
   EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
-
-# endif
-#endif  // !GTEST_USES_PCRE
+#endif
 }
 
 #if GTEST_USES_POSIX_RE
@@ -396,9 +421,9 @@ TYPED_TEST(RETest, ImplicitConstructorWorks) {
 
 // Tests that RE's constructors reject invalid regular expressions.
 TYPED_TEST(RETest, RejectsInvalidRegex) {
-  EXPECT_NONFATAL_FAILURE({
-    const RE invalid(TypeParam("?"));
-  }, "\"?\" is not a valid POSIX Extended regular expression.");
+  EXPECT_NONFATAL_FAILURE(
+      { const RE invalid(TypeParam("?")); },
+      "\"?\" is not a valid POSIX Extended regular expression.");
 }
 
 // Tests RE::FullMatch().
@@ -792,8 +817,7 @@ TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
   EXPECT_TRUE(MatchRegexAtHead("a?b", "ab"));
 }
 
-TEST(MatchRegexAtHeadTest,
-     WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
+TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
   EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
   EXPECT_FALSE(MatchRegexAtHead("\\s?b", "  b"));
 
@@ -849,17 +873,14 @@ TEST(RETest, ImplicitConstructorWorks) {
 
 // Tests that RE's constructors reject invalid regular expressions.
 TEST(RETest, RejectsInvalidRegex) {
-  EXPECT_NONFATAL_FAILURE({
-    const RE normal(NULL);
-  }, "NULL is not a valid simple regular expression");
+  EXPECT_NONFATAL_FAILURE({ const RE normal(NULL); },
+                          "NULL is not a valid simple regular expression");
 
-  EXPECT_NONFATAL_FAILURE({
-    const RE normal(".*(\\w+");
-  }, "'(' is unsupported");
+  EXPECT_NONFATAL_FAILURE({ const RE normal(".*(\\w+"); },
+                          "'(' is unsupported");
 
-  EXPECT_NONFATAL_FAILURE({
-    const RE invalid("^?");
-  }, "'?' can only follow a repeatable token");
+  EXPECT_NONFATAL_FAILURE({ const RE invalid("^?"); },
+                          "'?' can only follow a repeatable token");
 }
 
 // Tests RE::FullMatch().
@@ -1001,12 +1022,13 @@ TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
 TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
   // AssertHeld() is flaky only in the presence of multiple threads accessing
   // the lock. In this case, the test is robust.
-  EXPECT_DEATH_IF_SUPPORTED({
-    Mutex m;
-    { MutexLock lock(&m); }
-    m.AssertHeld();
-  },
-  "thread .*hold");
+  EXPECT_DEATH_IF_SUPPORTED(
+      {
+        Mutex m;
+        { MutexLock lock(&m); }
+        m.AssertHeld();
+      },
+      "thread .*hold");
 }
 
 TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
@@ -1017,15 +1039,15 @@ TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
 
 class AtomicCounterWithMutex {
  public:
-  explicit AtomicCounterWithMutex(Mutex* mutex) :
-    value_(0), mutex_(mutex), random_(42) {}
+  explicit AtomicCounterWithMutex(Mutex* mutex)
+      : value_(0), mutex_(mutex), random_(42) {}
 
   void Increment() {
     MutexLock lock(mutex_);
     int temp = value_;
     {
       // We need to put up a memory barrier to prevent reads and writes to
-      // value_ rearranged with the call to SleepMilliseconds when observed
+      // value_ rearranged with the call to sleep_for when observed
       // from other threads.
 #if GTEST_HAS_PTHREAD
       // On POSIX, locking a mutex puts up a memory barrier.  We cannot use
@@ -1036,7 +1058,8 @@ class AtomicCounterWithMutex {
           pthread_mutex_init(&memory_barrier_mutex, nullptr));
       GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));
 
-      SleepMilliseconds(static_cast<int>(random_.Generate(30)));
+      std::this_thread::sleep_for(
+          std::chrono::milliseconds(random_.Generate(30)));
 
       GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
       GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));
@@ -1044,10 +1067,11 @@ class AtomicCounterWithMutex {
       // On Windows, performing an interlocked access puts up a memory barrier.
       volatile LONG dummy = 0;
       ::InterlockedIncrement(&dummy);
-      SleepMilliseconds(static_cast<int>(random_.Generate(30)));
+      std::this_thread::sleep_for(
+          std::chrono::milliseconds(random_.Generate(30)));
       ::InterlockedIncrement(&dummy);
 #else
-# error "Memory barrier not implemented on this platform."
+#error "Memory barrier not implemented on this platform."
 #endif  // GTEST_HAS_PTHREAD
     }
     value_ = temp + 1;
@@ -1057,12 +1081,11 @@ class AtomicCounterWithMutex {
  private:
   volatile int value_;
   Mutex* const mutex_;  // Protects value_.
-  Random       random_;
+  Random random_;
 };
 
 void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
-  for (int i = 0; i < param.second; ++i)
-      param.first->Increment();
+  for (int i = 0; i < param.second; ++i) param.first->Increment();
 }
 
 // Tests that the mutex only lets one thread at a time to lock it.
@@ -1078,14 +1101,12 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
   // Creates and runs kThreadCount threads that increment locked_counter
   // kCycleCount times each.
   for (int i = 0; i < kThreadCount; ++i) {
-    counting_threads[i].reset(new ThreadType(&CountingThreadFunc,
-                                             make_pair(&locked_counter,
-                                                       kCycleCount),
-                                             &threads_can_start));
+    counting_threads[i].reset(new ThreadType(
+        &CountingThreadFunc, make_pair(&locked_counter, kCycleCount),
+        &threads_can_start));
   }
   threads_can_start.Notify();
-  for (int i = 0; i < kThreadCount; ++i)
-    counting_threads[i]->Join();
+  for (int i = 0; i < kThreadCount; ++i) counting_threads[i]->Join();
 
   // If the mutex lets more than one thread to increment the counter at a
   // time, they are likely to encounter a race condition and have some
@@ -1095,7 +1116,7 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
 }
 
 template <typename T>
-void RunFromThread(void (func)(T), T param) {
+void RunFromThread(void(func)(T), T param) {
   ThreadWithParam<T> thread(func, param, nullptr);
   thread.Join();
 }
@@ -1161,7 +1182,8 @@ class DestructorCall {
 #endif
   static std::vector<DestructorCall*>* const list_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(DestructorCall);
+  DestructorCall(const DestructorCall&) = delete;
+  DestructorCall& operator=(const DestructorCall&) = delete;
 };
 
 std::vector<DestructorCall*>* const DestructorCall::list_ =
index e1e8e1c7a083bb956572ff74f5589a16090571a3..acfecf97b8105b963f8226d18196020710d7b995 100644 (file)
@@ -27,7 +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.
 
-
 // Google Test - The Google C++ Testing and Mocking Framework
 //
 // This file tests the universal value printer.
 // Some user-defined types for testing the universal value printer.
 
 // An anonymous enum type.
-enum AnonymousEnum {
-  kAE1 = -1,
-  kAE2 = 1
-};
+enum AnonymousEnum { kAE1 = -1, kAE2 = 1 };
 
 // An enum without a user-defined printer.
-enum EnumWithoutPrinter {
-  kEWP1 = -2,
-  kEWP2 = 42
-};
+enum EnumWithoutPrinter { kEWP1 = -2, kEWP2 = 42 };
 
 // An enum with a << operator.
-enum EnumWithStreaming {
-  kEWS1 = 10
-};
+enum EnumWithStreaming { kEWS1 = 10 };
 
 std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) {
   return os << (e == kEWS1 ? "kEWS1" : "invalid");
 }
 
 // An enum with a PrintTo() function.
-enum EnumWithPrintTo {
-  kEWPT1 = 1
-};
+enum EnumWithPrintTo { kEWPT1 = 1 };
 
 void PrintTo(EnumWithPrintTo e, std::ostream* os) {
   *os << (e == kEWPT1 ? "kEWPT1" : "invalid");
@@ -108,6 +97,7 @@ template <typename T>
 class UnprintableTemplateInGlobal {
  public:
   UnprintableTemplateInGlobal() : value_() {}
+
  private:
   T value_;
 };
@@ -133,6 +123,7 @@ class UnprintableInFoo {
  public:
   UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); }
   double z() const { return z_; }
+
  private:
   char xy_[8];
   double z_;
@@ -149,8 +140,7 @@ void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) {
 }
 
 // A type with a user-defined << for printing its pointer.
-struct PointerPrintable {
-};
+struct PointerPrintable {};
 
 ::std::ostream& operator<<(::std::ostream& os,
                            const PointerPrintable* /* x */) {
@@ -164,6 +154,7 @@ class PrintableViaPrintToTemplate {
   explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {}
 
   const T& value() const { return value_; }
+
  private:
   T value_;
 };
@@ -180,6 +171,7 @@ class StreamableTemplateInFoo {
   StreamableTemplateInFoo() : value_() {}
 
   const T& value() const { return value_; }
+
  private:
   T value_;
 };
@@ -255,7 +247,6 @@ class UniversalPrinter<Wrapper<T>> {
 };
 }  // namespace internal
 
-
 namespace gtest_printers_test {
 
 using ::std::deque;
@@ -350,29 +341,21 @@ TEST(PrintCharTest, PlainChar) {
 // signed char.
 TEST(PrintCharTest, SignedChar) {
   EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0')));
-  EXPECT_EQ("'\\xCE' (-50)",
-            Print(static_cast<signed char>(-50)));
+  EXPECT_EQ("'\\xCE' (-50)", Print(static_cast<signed char>(-50)));
 }
 
 // unsigned char.
 TEST(PrintCharTest, UnsignedChar) {
   EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0')));
-  EXPECT_EQ("'b' (98, 0x62)",
-            Print(static_cast<unsigned char>('b')));
+  EXPECT_EQ("'b' (98, 0x62)", Print(static_cast<unsigned char>('b')));
 }
 
-TEST(PrintCharTest, Char16) {
-  EXPECT_EQ("U+0041", Print(u'A'));
-}
+TEST(PrintCharTest, Char16) { EXPECT_EQ("U+0041", Print(u'A')); }
 
-TEST(PrintCharTest, Char32) {
-  EXPECT_EQ("U+0041", Print(U'A'));
-}
+TEST(PrintCharTest, Char32) { EXPECT_EQ("U+0041", Print(U'A')); }
 
 #ifdef __cpp_char8_t
-TEST(PrintCharTest, Char8) {
-  EXPECT_EQ("U+0041", Print(u8'A'));
-}
+TEST(PrintCharTest, Char8) { EXPECT_EQ("U+0041", Print(u8'A')); }
 #endif
 
 // Tests printing other simple, built-in types.
@@ -414,8 +397,8 @@ TEST(PrintTypeSizeTest, Wchar_t) {
 TEST(PrintBuiltInTypeTest, Integer) {
   EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255)));  // uint8
   EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128)));  // int8
-  EXPECT_EQ("65535", Print(std::numeric_limits<uint16_t>::max()));  // uint16
-  EXPECT_EQ("-32768", Print(std::numeric_limits<int16_t>::min()));  // int16
+  EXPECT_EQ("65535", Print(std::numeric_limits<uint16_t>::max()));     // uint16
+  EXPECT_EQ("-32768", Print(std::numeric_limits<int16_t>::min()));     // int16
   EXPECT_EQ("4294967295",
             Print(std::numeric_limits<uint32_t>::max()));  // uint32
   EXPECT_EQ("-2147483648",
@@ -446,8 +429,26 @@ TEST(PrintBuiltInTypeTest, Size_t) {
 #if !GTEST_OS_WINDOWS
   // Windows has no ssize_t type.
   EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2)));  // ssize_t.
-#endif  // !GTEST_OS_WINDOWS
+#endif                                               // !GTEST_OS_WINDOWS
+}
+
+// gcc/clang __{u,}int128_t values.
+#if defined(__SIZEOF_INT128__)
+TEST(PrintBuiltInTypeTest, Int128) {
+  // Small ones
+  EXPECT_EQ("0", Print(__int128_t{0}));
+  EXPECT_EQ("0", Print(__uint128_t{0}));
+  EXPECT_EQ("12345", Print(__int128_t{12345}));
+  EXPECT_EQ("12345", Print(__uint128_t{12345}));
+  EXPECT_EQ("-12345", Print(__int128_t{-12345}));
+
+  // Large ones
+  EXPECT_EQ("340282366920938463463374607431768211455", Print(~__uint128_t{}));
+  __int128_t max_128 = static_cast<__int128_t>(~__uint128_t{} / 2);
+  EXPECT_EQ("-170141183460469231731687303715884105728", Print(~max_128));
+  EXPECT_EQ("170141183460469231731687303715884105727", Print(max_128));
 }
+#endif  // __SIZEOF_INT128__
 
 // Floating-points.
 TEST(PrintBuiltInTypeTest, FloatingPoints) {
@@ -455,6 +456,16 @@ TEST(PrintBuiltInTypeTest, FloatingPoints) {
   EXPECT_EQ("-2.5", Print(-2.5));  // double
 }
 
+#if GTEST_HAS_RTTI
+TEST(PrintBuiltInTypeTest, TypeInfo) {
+  struct MyStruct {};
+  auto res = Print(typeid(MyStruct{}));
+  // We can't guarantee that we can demangle the name, but either name should
+  // contain the substring "MyStruct".
+  EXPECT_NE(res.find("MyStruct"), res.npos) << res;
+}
+#endif  // GTEST_HAS_RTTI
+
 // 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.
@@ -488,8 +499,9 @@ TEST(PrintCStringTest, Null) {
 // Tests that C strings are escaped properly.
 TEST(PrintCStringTest, EscapesProperly) {
   const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a";
-  EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"?\\\\\\a\\b\\f"
-            "\\n\\r\\t\\v\\x7F\\xFF a\"",
+  EXPECT_EQ(PrintPointer(p) +
+                " pointing to \"'\\\"?\\\\\\a\\b\\f"
+                "\\n\\r\\t\\v\\x7F\\xFF a\"",
             Print(p));
 }
 
@@ -608,10 +620,12 @@ TEST(PrintWideCStringTest, Null) {
 
 // Tests that wide C strings are escaped properly.
 TEST(PrintWideCStringTest, EscapesProperly) {
-  const wchar_t s[] = {'\'', '"', '?', '\\', '\a', '\b', '\f', '\n', '\r',
-                       '\t', '\v', 0xD3, 0x576, 0x8D3, 0xC74D, ' ', 'a', '\0'};
-  EXPECT_EQ(PrintPointer(s) + " pointing to L\"'\\\"?\\\\\\a\\b\\f"
-            "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"",
+  const wchar_t s[] = {'\'',  '"',   '?',    '\\', '\a', '\b',
+                       '\f',  '\n',  '\r',   '\t', '\v', 0xD3,
+                       0x576, 0x8D3, 0xC74D, ' ',  'a',  '\0'};
+  EXPECT_EQ(PrintPointer(s) +
+                " pointing to L\"'\\\"?\\\\\\a\\b\\f"
+                "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"",
             Print(static_cast<const wchar_t*>(s)));
 }
 #endif  // native wchar_t
@@ -693,10 +707,9 @@ TEST(PrintPointerTest, NonMemberFunctionPointer) {
   // standard disallows casting between pointers to functions and
   // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
   // this limitation.
-  EXPECT_EQ(
-      PrintPointer(reinterpret_cast<const void*>(
-          reinterpret_cast<internal::BiggestInt>(&MyFunction))),
-      Print(&MyFunction));
+  EXPECT_EQ(PrintPointer(reinterpret_cast<const void*>(
+                reinterpret_cast<internal::BiggestInt>(&MyFunction))),
+            Print(&MyFunction));
   int (*p)(bool) = NULL;  // NOLINT
   EXPECT_EQ("NULL", Print(p));
 }
@@ -705,14 +718,13 @@ TEST(PrintPointerTest, NonMemberFunctionPointer) {
 // another.
 template <typename StringType>
 AssertionResult HasPrefix(const StringType& str, const StringType& prefix) {
-  if (str.find(prefix, 0) == 0)
-    return AssertionSuccess();
+  if (str.find(prefix, 0) == 0) return AssertionSuccess();
 
   const bool is_wide_string = sizeof(prefix[0]) > 1;
   const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
   return AssertionFailure()
-      << begin_string_quote << prefix << "\" is not a prefix of "
-      << begin_string_quote << str << "\"\n";
+         << begin_string_quote << prefix << "\" is not a prefix of "
+         << begin_string_quote << str << "\"\n";
 }
 
 // Tests printing member variable pointers.  Although they are called
@@ -733,8 +745,7 @@ TEST(PrintPointerTest, MemberVariablePointer) {
   EXPECT_TRUE(HasPrefix(Print(&Foo::value),
                         Print(sizeof(&Foo::value)) + "-byte object "));
   int Foo::*p = NULL;  // NOLINT
-  EXPECT_TRUE(HasPrefix(Print(p),
-                        Print(sizeof(p)) + "-byte object "));
+  EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
 }
 
 // Tests printing member function pointers.  Although they are called
@@ -748,8 +759,7 @@ TEST(PrintPointerTest, MemberFunctionPointer) {
       HasPrefix(Print(&Foo::MyVirtualMethod),
                 Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object "));
   int (Foo::*p)(char) = NULL;  // NOLINT
-  EXPECT_TRUE(HasPrefix(Print(p),
-                        Print(sizeof(p)) + "-byte object "));
+  EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
 }
 
 // Tests printing C arrays.
@@ -763,29 +773,26 @@ std::string PrintArrayHelper(T (&a)[N]) {
 
 // One-dimensional array.
 TEST(PrintArrayTest, OneDimensionalArray) {
-  int a[5] = { 1, 2, 3, 4, 5 };
+  int a[5] = {1, 2, 3, 4, 5};
   EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a));
 }
 
 // Two-dimensional array.
 TEST(PrintArrayTest, TwoDimensionalArray) {
-  int a[2][5] = {
-    { 1, 2, 3, 4, 5 },
-    { 6, 7, 8, 9, 0 }
-  };
+  int a[2][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}};
   EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a));
 }
 
 // Array of const elements.
 TEST(PrintArrayTest, ConstArray) {
-  const bool a[1] = { false };
+  const bool a[1] = {false};
   EXPECT_EQ("{ false }", PrintArrayHelper(a));
 }
 
 // char array without terminating NUL.
 TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) {
   // Array a contains '\0' in the middle and doesn't end with '\0'.
-  char a[] = { 'H', '\0', 'i' };
+  char a[] = {'H', '\0', 'i'};
   EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
 }
 
@@ -806,9 +813,7 @@ TEST(PrintArrayTest, Char8ArrayWithNoTerminatingNul) {
 // char8_t array with terminating NUL.
 TEST(PrintArrayTest, Char8ArrayWithTerminatingNul) {
   const char8_t a[] = u8"\0世界";
-  EXPECT_EQ(
-      "u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"",
-      PrintArrayHelper(a));
+  EXPECT_EQ("u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", PrintArrayHelper(a));
 }
 #endif
 
@@ -861,7 +866,7 @@ TEST(PrintArrayTest, ObjectArray) {
 
 // Array with many elements.
 TEST(PrintArrayTest, BigArray) {
-  int a[100] = { 1, 2, 3 };
+  int a[100] = {1, 2, 3};
   EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }",
             PrintArrayHelper(a));
 }
@@ -881,11 +886,14 @@ TEST(PrintStringTest, StringAmbiguousHex) {
   // '\x6', '\x6B', or '\x6BA'.
 
   // a hex escaping sequence following by a decimal digit
-  EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12" "3")));
+  EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12"
+                                                    "3")));
   // a hex escaping sequence following by a hex digit (lower-case)
-  EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6" "bananas")));
+  EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6"
+                                                          "bananas")));
   // a hex escaping sequence following by a hex digit (upper-case)
-  EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6" "BANANA")));
+  EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6"
+                                                          "BANANA")));
   // a hex escaping sequence following by a non-xdigit
   EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!")));
 }
@@ -895,19 +903,21 @@ TEST(PrintStringTest, StringAmbiguousHex) {
 // ::std::wstring.
 TEST(PrintWideStringTest, StringInStdNamespace) {
   const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
-  const ::std::wstring str(s, sizeof(s)/sizeof(wchar_t));
-  EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
-            "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
-            Print(str));
+  const ::std::wstring str(s, sizeof(s) / sizeof(wchar_t));
+  EXPECT_EQ(
+      "L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
+      "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
+      Print(str));
 }
 
 TEST(PrintWideStringTest, StringAmbiguousHex) {
   // same for wide strings.
-  EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12" L"3")));
-  EXPECT_EQ("L\"mm\\x6\" L\"bananas\"",
-            Print(::std::wstring(L"mm\x6" L"bananas")));
-  EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"",
-            Print(::std::wstring(L"NOM\x6" L"BANANA")));
+  EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12"
+                                                       L"3")));
+  EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", Print(::std::wstring(L"mm\x6"
+                                                             L"bananas")));
+  EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", Print(::std::wstring(L"NOM\x6"
+                                                             L"BANANA")));
   EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!")));
 }
 #endif  // GTEST_HAS_STD_WSTRING
@@ -1021,7 +1031,6 @@ TEST(PrintStlContainerTest, NonEmptyDeque) {
   EXPECT_EQ("{ 1, 3 }", Print(non_empty));
 }
 
-
 TEST(PrintStlContainerTest, OneElementHashMap) {
   ::std::unordered_map<int, char> map1;
   map1[1] = 'a';
@@ -1037,11 +1046,9 @@ TEST(PrintStlContainerTest, HashMultiMap) {
   const std::string result = Print(map1);
   EXPECT_TRUE(result == "{ (5, true), (5, false) }" ||
               result == "{ (5, false), (5, true) }")
-                  << " where Print(map1) returns \"" << result << "\".";
+      << " where Print(map1) returns \"" << result << "\".";
 }
 
-
-
 TEST(PrintStlContainerTest, HashSet) {
   ::std::unordered_set<int> set1;
   set1.insert(1);
@@ -1050,7 +1057,7 @@ TEST(PrintStlContainerTest, HashSet) {
 
 TEST(PrintStlContainerTest, HashMultiSet) {
   const int kSize = 5;
-  int a[kSize] = { 1, 1, 2, 5, 1 };
+  int a[kSize] = {1, 1, 2, 5, 1};
   ::std::unordered_multiset<int> set1(a, a + kSize);
 
   // Elements of hash_multiset can be printed in any order.
@@ -1066,8 +1073,8 @@ TEST(PrintStlContainerTest, HashMultiSet) {
       ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0);
       numbers.push_back(result[i] - '0');
     } else {
-      EXPECT_EQ(expected_pattern[i], result[i]) << " where result is "
-                                                << result;
+      EXPECT_EQ(expected_pattern[i], result[i])
+          << " where result is " << result;
     }
   }
 
@@ -1077,7 +1084,6 @@ TEST(PrintStlContainerTest, HashMultiSet) {
   EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));
 }
 
-
 TEST(PrintStlContainerTest, List) {
   const std::string a[] = {"hello", "world"};
   const list<std::string> strings(a, a + 2);
@@ -1107,20 +1113,19 @@ TEST(PrintStlContainerTest, MultiMap) {
 }
 
 TEST(PrintStlContainerTest, Set) {
-  const unsigned int a[] = { 3, 0, 5 };
+  const unsigned int a[] = {3, 0, 5};
   set<unsigned int> set1(a, a + 3);
   EXPECT_EQ("{ 0, 3, 5 }", Print(set1));
 }
 
 TEST(PrintStlContainerTest, MultiSet) {
-  const int a[] = { 1, 1, 2, 5, 1 };
+  const int a[] = {1, 1, 2, 5, 1};
   multiset<int> set1(a, a + 5);
   EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
 }
 
-
 TEST(PrintStlContainerTest, SinglyLinkedList) {
-  int a[] = { 9, 2, 8 };
+  int a[] = {9, 2, 8};
   const std::forward_list<int> ints(a, a + 3);
   EXPECT_EQ("{ 9, 2, 8 }", Print(ints));
 }
@@ -1138,32 +1143,34 @@ TEST(PrintStlContainerTest, Vector) {
 }
 
 TEST(PrintStlContainerTest, LongSequence) {
-  const int a[100] = { 1, 2, 3 };
+  const int a[100] = {1, 2, 3};
   const vector<int> v(a, a + 100);
-  EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
-            "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v));
+  EXPECT_EQ(
+      "{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
+      "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }",
+      Print(v));
 }
 
 TEST(PrintStlContainerTest, NestedContainer) {
-  const int a1[] = { 1, 2 };
-  const int a2[] = { 3, 4, 5 };
+  const int a1[] = {1, 2};
+  const int a2[] = {3, 4, 5};
   const list<int> l1(a1, a1 + 2);
   const list<int> l2(a2, a2 + 3);
 
-  vector<list<int> > v;
+  vector<list<int>> v;
   v.push_back(l1);
   v.push_back(l2);
   EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v));
 }
 
 TEST(PrintStlContainerTest, OneDimensionalNativeArray) {
-  const int a[3] = { 1, 2, 3 };
+  const int a[3] = {1, 2, 3};
   NativeArray<int> b(a, 3, RelationToSourceReference());
   EXPECT_EQ("{ 1, 2, 3 }", Print(b));
 }
 
 TEST(PrintStlContainerTest, TwoDimensionalNativeArray) {
-  const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
+  const int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
   NativeArray<int[3]> b(a, 2, RelationToSourceReference());
   EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b));
 }
@@ -1215,20 +1222,18 @@ TEST(PrintStdTupleTest, VariousSizes) {
       t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str,  // NOLINT
           nullptr, "10");
   EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
-            " pointing to \"8\", NULL, \"10\")",
+                " pointing to \"8\", NULL, \"10\")",
             Print(t10));
 }
 
 // Nested tuples.
 TEST(PrintStdTupleTest, NestedTuple) {
-  ::std::tuple< ::std::tuple<int, bool>, char> nested(
-      ::std::make_tuple(5, true), 'a');
+  ::std::tuple<::std::tuple<int, bool>, char> nested(::std::make_tuple(5, true),
+                                                     'a');
   EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
 }
 
-TEST(PrintNullptrT, Basic) {
-  EXPECT_EQ("(nullptr)", Print(nullptr));
-}
+TEST(PrintNullptrT, Basic) { EXPECT_EQ("(nullptr)", Print(nullptr)); }
 
 TEST(PrintReferenceWrapper, Printable) {
   int x = 5;
@@ -1252,8 +1257,7 @@ TEST(PrintReferenceWrapper, Unprintable) {
 
 // Unprintable types in the global namespace.
 TEST(PrintUnprintableTypeTest, InGlobalNamespace) {
-  EXPECT_EQ("1-byte object <00>",
-            Print(UnprintableTemplateInGlobal<char>()));
+  EXPECT_EQ("1-byte object <00>", Print(UnprintableTemplateInGlobal<char>()));
 }
 
 // Unprintable types in a user namespace.
@@ -1270,14 +1274,15 @@ struct Big {
 };
 
 TEST(PrintUnpritableTypeTest, BigObject) {
-  EXPECT_EQ("257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 "
-            "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
-            "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
-            "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 "
-            "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
-            "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
-            "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>",
-            Print(Big()));
+  EXPECT_EQ(
+      "257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 "
+      "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
+      "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
+      "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 "
+      "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
+      "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
+      "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>",
+      Print(Big()));
 }
 
 // Tests printing user-defined streamable types.
@@ -1320,8 +1325,7 @@ TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {
 
 // Tests printing user-defined types that have a PrintTo() function.
 TEST(PrintPrintableTypeTest, InUserNamespace) {
-  EXPECT_EQ("PrintableViaPrintTo: 0",
-            Print(::foo::PrintableViaPrintTo()));
+  EXPECT_EQ("PrintableViaPrintTo: 0", Print(::foo::PrintableViaPrintTo()));
 }
 
 // Tests printing a pointer to a user-defined type that has a <<
@@ -1343,16 +1347,14 @@ TEST(PrintReferenceTest, PrintsAddressAndValue) {
   int n = 5;
   EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n));
 
-  int a[2][3] = {
-    { 0, 1, 2 },
-    { 3, 4, 5 }
-  };
+  int a[2][3] = {{0, 1, 2}, {3, 4, 5}};
   EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }",
             PrintByRef(a));
 
   const ::foo::UnprintableInFoo x;
-  EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object "
-            "<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
+  EXPECT_EQ("@" + PrintPointer(&x) +
+                " 16-byte object "
+                "<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
             PrintByRef(x));
 }
 
@@ -1368,33 +1370,29 @@ TEST(PrintReferenceTest, HandlesFunctionPointer) {
   // this limitation.
   const std::string fp_string = PrintPointer(reinterpret_cast<const void*>(
       reinterpret_cast<internal::BiggestInt>(fp)));
-  EXPECT_EQ("@" + fp_pointer_string + " " + fp_string,
-            PrintByRef(fp));
+  EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, PrintByRef(fp));
 }
 
 // Tests that the universal printer prints a member function pointer
 // passed by reference.
 TEST(PrintReferenceTest, HandlesMemberFunctionPointer) {
   int (Foo::*p)(char ch) = &Foo::MyMethod;
-  EXPECT_TRUE(HasPrefix(
-      PrintByRef(p),
-      "@" + PrintPointer(reinterpret_cast<const void*>(&p)) + " " +
-          Print(sizeof(p)) + "-byte object "));
+  EXPECT_TRUE(HasPrefix(PrintByRef(p),
+                        "@" + PrintPointer(reinterpret_cast<const void*>(&p)) +
+                            " " + Print(sizeof(p)) + "-byte object "));
 
   char (Foo::*p2)(int n) = &Foo::MyVirtualMethod;
-  EXPECT_TRUE(HasPrefix(
-      PrintByRef(p2),
-      "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) + " " +
-          Print(sizeof(p2)) + "-byte object "));
+  EXPECT_TRUE(HasPrefix(PrintByRef(p2),
+                        "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) +
+                            " " + Print(sizeof(p2)) + "-byte object "));
 }
 
 // Tests that the universal printer prints a member variable pointer
 // passed by reference.
 TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
   int Foo::*p = &Foo::value;  // NOLINT
-  EXPECT_TRUE(HasPrefix(
-      PrintByRef(p),
-      "@" + PrintPointer(&p) + " " + Print(sizeof(p)) + "-byte object "));
+  EXPECT_TRUE(HasPrefix(PrintByRef(p), "@" + PrintPointer(&p) + " " +
+                                           Print(sizeof(p)) + "-byte object "));
 }
 
 // Tests that FormatForComparisonFailureMessage(), which is used to print
@@ -1403,8 +1401,7 @@ TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
 
 // scalar
 TEST(FormatForComparisonFailureMessageTest, WorksForScalar) {
-  EXPECT_STREQ("123",
-               FormatForComparisonFailureMessage(123, 124).c_str());
+  EXPECT_STREQ("123", FormatForComparisonFailureMessage(123, 124).c_str());
 }
 
 // non-char pointer
@@ -1418,9 +1415,8 @@ TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) {
 TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) {
   // In expression 'array == x', 'array' is compared by pointer.
   // Therefore we want to print an array operand as a pointer.
-  int n[] = { 1, 2, 3 };
-  EXPECT_EQ(PrintPointer(n),
-            FormatForComparisonFailureMessage(n, n).c_str());
+  int n[] = {1, 2, 3};
+  EXPECT_EQ(PrintPointer(n), FormatForComparisonFailureMessage(n, n).c_str());
 }
 
 // Tests formatting a char pointer when it's compared with another pointer.
@@ -1436,8 +1432,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) {
 
   // const char*
   const char* s = "hello";
-  EXPECT_EQ(PrintPointer(s),
-            FormatForComparisonFailureMessage(s, s).c_str());
+  EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());
 
   // char*
   char ch = 'a';
@@ -1454,8 +1449,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) {
 
   // const wchar_t*
   const wchar_t* s = L"hello";
-  EXPECT_EQ(PrintPointer(s),
-            FormatForComparisonFailureMessage(s, s).c_str());
+  EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());
 
   // wchar_t*
   wchar_t ch = L'a';
@@ -1552,13 +1546,11 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) {
 // Useful for testing PrintToString().  We cannot use EXPECT_EQ()
 // there as its implementation uses PrintToString().  The caller must
 // ensure that 'value' has no side effect.
-#define EXPECT_PRINT_TO_STRING_(value, expected_string)         \
-  EXPECT_TRUE(PrintToString(value) == (expected_string))        \
+#define EXPECT_PRINT_TO_STRING_(value, expected_string)  \
+  EXPECT_TRUE(PrintToString(value) == (expected_string)) \
       << " where " #value " prints as " << (PrintToString(value))
 
-TEST(PrintToStringTest, WorksForScalar) {
-  EXPECT_PRINT_TO_STRING_(123, "123");
-}
+TEST(PrintToStringTest, WorksForScalar) { EXPECT_PRINT_TO_STRING_(123, "123"); }
 
 TEST(PrintToStringTest, WorksForPointerToConstChar) {
   const char* p = "hello";
@@ -1583,7 +1575,7 @@ TEST(PrintToStringTest, EscapesForPointerToNonConstChar) {
 }
 
 TEST(PrintToStringTest, WorksForArray) {
-  int n[3] = { 1, 2, 3 };
+  int n[3] = {1, 2, 3};
   EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }");
 }
 
@@ -1600,8 +1592,8 @@ 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.
+TEST(PrintToStringTest, ContainsNonLatin) {
+  // 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"
@@ -1617,57 +1609,58 @@ TEST(IsValidUTF8Test, IllFormedUTF8) {
   // 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) {
+  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]);
   }
 }
@@ -1816,15 +1809,15 @@ TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
 }
 
 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) {
-  Strings result = UniversalTersePrintTupleFieldsToStrings(
-      ::std::make_tuple(1));
+  Strings result =
+      UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1));
   ASSERT_EQ(1u, result.size());
   EXPECT_EQ("1", result[0]);
 }
 
 TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) {
-  Strings result = UniversalTersePrintTupleFieldsToStrings(
-      ::std::make_tuple(1, 'a'));
+  Strings result =
+      UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1, 'a'));
   ASSERT_EQ(2u, result.size());
   EXPECT_EQ("1", result[0]);
   EXPECT_EQ("'a' (97, 0x61)", result[1]);
@@ -1873,6 +1866,7 @@ TEST_F(PrintAnyTest, NonEmpty) {
 
 #if GTEST_INTERNAL_HAS_OPTIONAL
 TEST(PrintOptionalTest, Basic) {
+  EXPECT_EQ("(nullopt)", PrintToString(internal::Nullopt()));
   internal::Optional<int> value;
   EXPECT_EQ("(nullopt)", PrintToString(value));
   value = {7};
index c82162fc99f8bbecf4a8caf2ce0a29bf64b3c24a..9d1fd0295cd101c9de195b067a4aa876a9e4b123 100755 (executable)
@@ -31,7 +31,7 @@
 
 """Verifies that SetUpTestSuite and TearDownTestSuite errors are noticed."""
 
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 COMMAND = gtest_test_utils.GetTestExecutablePath(
     'googletest-setuptestsuite-test_')
index a4bc4ef441d9be4802e2c010df8f1c3d96dfaf40..d20899f568661417e1f5d9389a27ec9e0563f9d9 100644 (file)
 // (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"
 
 class SetupFailTest : public ::testing::Test {
  protected:
-  static void SetUpTestSuite() {
-    ASSERT_EQ("", "SET_UP_FAIL");
-  }
+  static void SetUpTestSuite() { ASSERT_EQ("", "SET_UP_FAIL"); }
 };
 
 TEST_F(SetupFailTest, NoopPassingTest) {}
 
 class TearDownFailTest : public ::testing::Test {
  protected:
-  static void TearDownTestSuite() {
-    ASSERT_EQ("", "TEAR_DOWN_FAIL");
-  }
+  static void TearDownTestSuite() { ASSERT_EQ("", "TEAR_DOWN_FAIL"); }
 };
 
 TEST_F(TearDownFailTest, NoopPassingTest) {}
index 573cc5eca3fce458aa3ac3e39850f47bb382e55b..9d2adc1286b278533faae0e6616db8accd1f2667 100755 (executable)
@@ -31,7 +31,7 @@
 """Verifies that test shuffling works."""
 
 import os
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 # Command to run the googletest-shuffle-test_ program.
 COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-shuffle-test_')
index 4505663ae433c4fd53205c160fbc2ab3e8e66ed4..a14e22f98cf8c8093775ea6b6761f02675e2c0a6 100644 (file)
@@ -27,7 +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.
 
-
 // Verifies that test shuffling works.
 
 #include "gtest/gtest.h"
@@ -88,7 +87,7 @@ class TestNamePrinter : public EmptyTestEventListener {
 
 }  // namespace
 
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
   InitGoogleTest(&argc, argv);
 
   // Replaces the default printer with TestNamePrinter, which prints
index 44cf7ca044b850dadc0df89628225c07dea27c91..076e5be2fa44c16e0c66e64654efa2b19612c68c 100644 (file)
@@ -28,7 +28,6 @@
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 #include "gtest/gtest-test-part.h"
-
 #include "gtest/gtest.h"
 
 using testing::Message;
@@ -52,17 +51,14 @@ class TestPartResultTest : public Test {
   TestPartResult r1_, r2_, r3_, r4_;
 };
 
-
 TEST_F(TestPartResultTest, ConstructorWorks) {
   Message message;
   message << "something is terribly wrong";
   message << static_cast<const char*>(testing::internal::kStackTraceMarker);
   message << "some unimportant stack trace";
 
-  const TestPartResult result(TestPartResult::kNonFatalFailure,
-                              "some_file.cc",
-                              42,
-                              message.GetString().c_str());
+  const TestPartResult result(TestPartResult::kNonFatalFailure, "some_file.cc",
+                              42, message.GetString().c_str());
 
   EXPECT_EQ(TestPartResult::kNonFatalFailure, result.type());
   EXPECT_STREQ("some_file.cc", result.file_name());
@@ -72,9 +68,7 @@ TEST_F(TestPartResultTest, ConstructorWorks) {
 }
 
 TEST_F(TestPartResultTest, ResultAccessorsWork) {
-  const TestPartResult success(TestPartResult::kSuccess,
-                               "file.cc",
-                               42,
+  const TestPartResult success(TestPartResult::kSuccess, "file.cc", 42,
                                "message");
   EXPECT_TRUE(success.passed());
   EXPECT_FALSE(success.failed());
@@ -83,19 +77,15 @@ TEST_F(TestPartResultTest, ResultAccessorsWork) {
   EXPECT_FALSE(success.skipped());
 
   const TestPartResult nonfatal_failure(TestPartResult::kNonFatalFailure,
-                                        "file.cc",
-                                        42,
-                                        "message");
+                                        "file.cc", 42, "message");
   EXPECT_FALSE(nonfatal_failure.passed());
   EXPECT_TRUE(nonfatal_failure.failed());
   EXPECT_TRUE(nonfatal_failure.nonfatally_failed());
   EXPECT_FALSE(nonfatal_failure.fatally_failed());
   EXPECT_FALSE(nonfatal_failure.skipped());
 
-  const TestPartResult fatal_failure(TestPartResult::kFatalFailure,
-                                     "file.cc",
-                                     42,
-                                     "message");
+  const TestPartResult fatal_failure(TestPartResult::kFatalFailure, "file.cc",
+                                     42, "message");
   EXPECT_FALSE(fatal_failure.passed());
   EXPECT_TRUE(fatal_failure.failed());
   EXPECT_FALSE(fatal_failure.nonfatally_failed());
index ea627c479d5b19824ca67b98089cf400c33c279a..772bbc5f39b993064b4cd0bc24cc472c719d6c9e 100755 (executable)
@@ -36,7 +36,7 @@ Google Test) with different environments and command line flags.
 """
 
 import os
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 
 # Constants.
index 83bb914c7e474a812d5745a3ec50b95b38a658e4..3b81a5a1db667cd0acc50e2955fa5a199bfadbab 100644 (file)
 // (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 throw-on-failure mode with exceptions disabled.
 //
 // This program must be compiled with exceptions disabled.  It will be
 // 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"
+#include <stdio.h>   // for fflush, fprintf, NULL, etc.
+#include <stdlib.h>  // for exit
 
-#include <stdio.h>                      // for fflush, fprintf, NULL, etc.
-#include <stdlib.h>                     // for exit
-#include <exception>                    // for set_terminate
+#include <exception>  // for set_terminate
+
+#include "gtest/gtest.h"
 
 // This terminate handler aborts the program using exit() rather than abort().
 // This avoids showing pop-ups on Windows systems and core dumps on Unix-like
index 69595a0ddede807ae3711e9ef5f7b0ae92207563..73c91764a5b8a93e1a1acd41a87f9e4c7fe9cf02 100755 (executable)
@@ -31,7 +31,7 @@
 
 """Verifies that Google Test warns the user when not initialized properly."""
 
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 COMMAND = gtest_test_utils.GetTestExecutablePath('googletest-uninitialized-test_')
 
index b4434d51eebfd8726bd3f04c2d0426bba960298c..88b61fcefd5e5eb81ff0f6783e18bb9ff2a53108 100644 (file)
@@ -27,7 +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.
 
-
 #include "gtest/gtest.h"
 
 TEST(DummyTest, Dummy) {
@@ -37,6 +36,4 @@ TEST(DummyTest, Dummy) {
   // testing::InitGoogleTest() being called first.
 }
 
-int main() {
-  return RUN_ALL_TESTS();
-}
+int main() { return RUN_ALL_TESTS(); }
index e83ca2e11b1b626f323b92853a01821b8a353190..f2eae12058b747925668281aabda1aa8dbbdb80b 100644 (file)
 // (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 <vector>
 
-#include "test/gtest-typed-test_test.h"
 #include "gtest/gtest.h"
+#include "test/gtest-typed-test_test.h"
 
 // Tests that the same type-parameterized test case can be
 // instantiated in different translation units linked together.
index 5fc678cb0d5d1d025d69356c2b1b6d10e45ed66a..af23f86d14dd143981ba8f82d77fe3d5cead7a1a 100644 (file)
@@ -27,7 +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.
 
-
 #include "test/gtest-typed-test_test.h"
 
 #include <set>
@@ -50,9 +49,7 @@ class CommonTest : public Test {
   // For some technical reason, SetUpTestSuite() and TearDownTestSuite()
   // must be public.
  public:
-  static void SetUpTestSuite() {
-    shared_ = new T(5);
-  }
+  static void SetUpTestSuite() { shared_ = new T(5); }
 
   static void TearDownTestSuite() {
     delete shared_;
@@ -130,8 +127,7 @@ TYPED_TEST(CommonTest, ValuesAreStillCorrect) {
 // translation unit.
 
 template <typename T>
-class TypedTest1 : public Test {
-};
+class TypedTest1 : public Test {};
 
 // Verifies that the second argument of TYPED_TEST_SUITE can be a
 // single type.
@@ -139,8 +135,7 @@ TYPED_TEST_SUITE(TypedTest1, int);
 TYPED_TEST(TypedTest1, A) {}
 
 template <typename T>
-class TypedTest2 : public Test {
-};
+class TypedTest2 : public Test {};
 
 // Verifies that the second argument of TYPED_TEST_SUITE can be a
 // Types<...> type list.
@@ -155,15 +150,12 @@ TYPED_TEST(TypedTest2, A) {}
 namespace library1 {
 
 template <typename T>
-class NumericTest : public Test {
-};
+class NumericTest : public Test {};
 
 typedef Types<int, long> NumericTypes;
 TYPED_TEST_SUITE(NumericTest, NumericTypes);
 
-TYPED_TEST(NumericTest, DefaultIsZero) {
-  EXPECT_EQ(0, TypeParam());
-}
+TYPED_TEST(NumericTest, DefaultIsZero) { EXPECT_EQ(0, TypeParam()); }
 
 }  // namespace library1
 
@@ -265,8 +257,7 @@ TEST_F(TypedTestSuitePStateDeathTest, DetectsTestAfterRegistration) {
 // and SetUp()/TearDown() work correctly in type-parameterized tests.
 
 template <typename T>
-class DerivedTest : public CommonTest<T> {
-};
+class DerivedTest : public CommonTest<T> {};
 
 TYPED_TEST_SUITE_P(DerivedTest);
 
@@ -290,8 +281,8 @@ TYPED_TEST_P(DerivedTest, ValuesAreStillCorrect) {
   EXPECT_EQ(2, this->value_);
 }
 
-REGISTER_TYPED_TEST_SUITE_P(DerivedTest,
-                           ValuesAreCorrect, ValuesAreStillCorrect);
+REGISTER_TYPED_TEST_SUITE_P(DerivedTest, ValuesAreCorrect,
+                            ValuesAreStillCorrect);
 
 typedef Types<short, long> MyTwoTypes;
 INSTANTIATE_TYPED_TEST_SUITE_P(My, DerivedTest, MyTwoTypes);
@@ -334,14 +325,13 @@ class TypeParametrizedTestNames {
 };
 
 INSTANTIATE_TYPED_TEST_SUITE_P(CustomName, TypeParametrizedTestWithNames,
-                              TwoTypes, TypeParametrizedTestNames);
+                               TwoTypes, TypeParametrizedTestNames);
 
 // Tests that multiple TYPED_TEST_SUITE_P's can be defined in the same
 // translation unit.
 
 template <typename T>
-class TypedTestP1 : public Test {
-};
+class TypedTestP1 : public Test {};
 
 TYPED_TEST_SUITE_P(TypedTestP1);
 
@@ -359,8 +349,7 @@ using IntBeforeRegisterTypedTestSuiteP = int;
 REGISTER_TYPED_TEST_SUITE_P(TypedTestP1, A, B);
 
 template <typename T>
-class TypedTestP2 : public Test {
-};
+class TypedTestP2 : public Test {};
 
 TYPED_TEST_SUITE_P(TypedTestP2);
 
@@ -396,21 +385,17 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, ContainerTest, MyContainers);
 namespace library2 {
 
 template <typename T>
-class NumericTest : public Test {
-};
+class NumericTest : public Test {};
 
 TYPED_TEST_SUITE_P(NumericTest);
 
-TYPED_TEST_P(NumericTest, DefaultIsZero) {
-  EXPECT_EQ(0, TypeParam());
-}
+TYPED_TEST_P(NumericTest, DefaultIsZero) { EXPECT_EQ(0, TypeParam()); }
 
 TYPED_TEST_P(NumericTest, ZeroIsLessThanOne) {
   EXPECT_LT(TypeParam(0), TypeParam(1));
 }
 
-REGISTER_TYPED_TEST_SUITE_P(NumericTest,
-                           DefaultIsZero, ZeroIsLessThanOne);
+REGISTER_TYPED_TEST_SUITE_P(NumericTest, DefaultIsZero, ZeroIsLessThanOne);
 typedef Types<int, double> NumericTypes;
 INSTANTIATE_TYPED_TEST_SUITE_P(My, NumericTest, NumericTypes);
 
@@ -418,20 +403,20 @@ 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 { };
+template <typename T>
+class TrimmedTest : public Test {};
 TYPED_TEST_SUITE_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_SUITE_P(
-    TrimmedTest,
-    Test1, Test2,Test3 , Test4 ,Test5 );  // NOLINT
-template <typename T1, typename T2> struct MyPair {};
+REGISTER_TYPED_TEST_SUITE_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_SUITE_P(My, TrimmedTest, TrimTypes);
 
 }  // namespace library2
-
index 8ce559c99f7341ceb8a0b2b89c4b1a97026fa5ae..f3ef0a5962970e18bbd096414271b746b6d525c4 100644 (file)
@@ -40,21 +40,18 @@ using testing::Test;
 // and gtest-typed-test2_test.cc.
 
 template <typename T>
-class ContainerTest : public Test {
-};
+class ContainerTest : public Test {};
 
 TYPED_TEST_SUITE_P(ContainerTest);
 
-TYPED_TEST_P(ContainerTest, CanBeDefaultConstructed) {
-  TypeParam container;
-}
+TYPED_TEST_P(ContainerTest, CanBeDefaultConstructed) { TypeParam container; }
 
 TYPED_TEST_P(ContainerTest, InitialSizeIsZero) {
   TypeParam container;
   EXPECT_EQ(0U, container.size());
 }
 
-REGISTER_TYPED_TEST_SUITE_P(ContainerTest,
-                            CanBeDefaultConstructed, InitialSizeIsZero);
+REGISTER_TYPED_TEST_SUITE_P(ContainerTest, CanBeDefaultConstructed,
+                            InitialSizeIsZero);
 
 #endif  // GOOGLETEST_TEST_GTEST_TYPED_TEST_TEST_H_
index 8ef505838c70dfc6e3354e85189fc3faf0b0aa7d..2a13fa32ff9abad7646bae7b9f3ff426b78f51eb 100644 (file)
 // This file contains tests verifying correctness of data provided via
 // UnitTest's public methods.
 
-#include "gtest/gtest.h"
-
 #include <string.h>  // For strcmp.
+
 #include <algorithm>
 
+#include "gtest/gtest.h"
+
 using ::testing::InitGoogleTest;
 
 namespace testing {
@@ -56,13 +57,12 @@ class UnitTestHelper {
   static TestSuite const** GetSortedTestSuites() {
     UnitTest& unit_test = *UnitTest::GetInstance();
     auto const** const test_suites = new const TestSuite*[static_cast<size_t>(
-      unit_test.total_test_suite_count())];
+        unit_test.total_test_suite_count())];
 
     for (int i = 0; i < unit_test.total_test_suite_count(); ++i)
       test_suites[i] = unit_test.GetTestSuite(i);
 
-    std::sort(test_suites,
-              test_suites + unit_test.total_test_suite_count(),
+    std::sort(test_suites, test_suites + unit_test.total_test_suite_count(),
               LessByName<TestSuite>());
     return test_suites;
   }
@@ -73,8 +73,7 @@ class UnitTestHelper {
     UnitTest& unit_test = *UnitTest::GetInstance();
     for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
       const TestSuite* test_suite = unit_test.GetTestSuite(i);
-      if (0 == strcmp(test_suite->name(), name))
-        return test_suite;
+      if (0 == strcmp(test_suite->name(), name)) return test_suite;
     }
     return nullptr;
   }
@@ -84,7 +83,7 @@ class UnitTestHelper {
   // array.
   static TestInfo const** GetSortedTests(const TestSuite* test_suite) {
     TestInfo const** const tests = new const TestInfo*[static_cast<size_t>(
-      test_suite->total_test_count())];
+        test_suite->total_test_count())];
 
     for (int i = 0; i < test_suite->total_test_count(); ++i)
       tests[i] = test_suite->GetTestInfo(i);
@@ -95,7 +94,8 @@ class UnitTestHelper {
   }
 };
 
-template <typename T> class TestSuiteWithCommentTest : public Test {};
+template <typename T>
+class TestSuiteWithCommentTest : public Test {};
 TYPED_TEST_SUITE(TestSuiteWithCommentTest, Types<int>);
 TYPED_TEST(TestSuiteWithCommentTest, Dummy) {}
 
@@ -319,7 +319,7 @@ class FinalSuccessChecker : public Environment {
 }  // namespace internal
 }  // namespace testing
 
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
   InitGoogleTest(&argc, argv);
 
   AddGlobalTestEnvironment(new testing::internal::FinalSuccessChecker());
index ada4cb30ef68c55db81356529186834e25c1ac24..f507eac475756e5dc44521bbe56b7f9568edfb95 100644 (file)
 // (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 <stdlib.h>
 #include <string.h>
+
 #include <stdexcept>
 
+#include "gtest/gtest.h"
+
 class ThrowListener : public testing::EmptyTestEventListener {
   void OnTestPartResult(const testing::TestPartResult& result) override {
     if (result.type() == testing::TestPartResult::kFatalFailure) {
@@ -55,9 +55,7 @@ void Fail(const char* msg) {
   exit(1);
 }
 
-static void AssertFalse() {
-  ASSERT_EQ(2, 3) << "Expected failure";
-}
+static void AssertFalse() { ASSERT_EQ(2, 3) << "Expected failure"; }
 
 // Tests that an assertion failure throws a subclass of
 // std::runtime_error.
@@ -65,21 +63,21 @@ TEST(Test, Test) {
   // A successful assertion shouldn't throw.
   try {
     EXPECT_EQ(3, 3);
-  } catch(...) {
+  } catch (...) {
     Fail("A successful assertion wrongfully threw.");
   }
 
   // A successful assertion shouldn't throw.
   try {
     EXPECT_EQ(3, 4);
-  } catch(...) {
+  } catch (...) {
     Fail("A failed non-fatal assertion wrongfully threw.");
   }
 
   // A failed assertion should throw.
   try {
     AssertFalse();
-  } catch(const testing::AssertionException& e) {
+  } catch (const testing::AssertionException& e) {
     if (strstr(e.what(), "Expected failure") != nullptr) throw;
 
     printf("%s",
@@ -87,7 +85,7 @@ TEST(Test, Test) {
            "but the message is incorrect.  Instead of containing \"Expected "
            "failure\", it is:\n");
     Fail(e.what());
-  } catch(...) {
+  } catch (...) {
     Fail("A failed assertion threw the wrong type of exception.");
   }
   Fail("A failed assertion should've thrown but didn't.");
@@ -95,9 +93,7 @@ TEST(Test, Test) {
 
 int kTestForContinuingTest = 0;
 
-TEST(Test, Test2) {
-  kTestForContinuingTest = 1;
-}
+TEST(Test, Test2) { kTestForContinuingTest = 1; }
 
 int main(int argc, char** argv) {
   testing::InitGoogleTest(&argc, argv);
index 064bfc50b918451e2907bd5856673ddcd2701941..122eaf3ca80212efe7d8210a9f8dd9ef72c64b15 100644 (file)
 //
 // Tests using global test environments.
 
-#include <stdlib.h>
 #include <stdio.h>
+#include <stdlib.h>
+
 #include "gtest/gtest.h"
 #include "src/gtest-internal-inl.h"
 
-namespace testing {
-GTEST_DECLARE_string_(filter);
-}
-
 namespace {
 
-enum FailureType {
-  NO_FAILURE, NON_FATAL_FAILURE, FATAL_FAILURE
-};
+enum FailureType { NO_FAILURE, NON_FATAL_FAILURE, FATAL_FAILURE };
 
 // For testing using global test environments.
 class MyEnvironment : public testing::Environment {
@@ -83,9 +78,7 @@ class MyEnvironment : public testing::Environment {
 
   // We call this function to set the type of failure SetUp() should
   // generate.
-  void set_failure_in_set_up(FailureType type) {
-    failure_in_set_up_ = type;
-  }
+  void set_failure_in_set_up(FailureType type) { failure_in_set_up_ = type; }
 
   // Was SetUp() run?
   bool set_up_was_run() const { return set_up_was_run_; }
@@ -104,9 +97,7 @@ bool test_was_run;
 
 // The sole purpose of this TEST is to enable us to check whether it
 // was run.
-TEST(FooTest, Bar) {
-  test_was_run = true;
-}
+TEST(FooTest, Bar) { test_was_run = true; }
 
 // Prints the message and aborts the program if condition is false.
 void Check(bool condition, const char* msg) {
@@ -130,7 +121,7 @@ int RunAllTests(MyEnvironment* env, FailureType failure) {
 
 }  // namespace
 
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
   testing::InitGoogleTest(&argc, argv);
 
   // Registers a global test environment, and verifies that the
@@ -174,7 +165,7 @@ int main(int argc, char **argv) {
 
   // Verifies that RUN_ALL_TESTS() doesn't do global set-up or
   // tear-down when there is no test to run.
-  testing::GTEST_FLAG(filter) = "-*";
+  GTEST_FLAG_SET(filter, "-*");
   Check(RunAllTests(env, NO_FAILURE) == 0,
         "RUN_ALL_TESTS() should return zero, as there is no test to run.");
   Check(!env->set_up_was_run(),
index 8d953bbd9dc4db72367a9508213224e880bea0c3..642ab865062b02aeef713867c6f49ab745e23210 100755 (executable)
@@ -39,27 +39,29 @@ SYNOPSIS
 
 import os
 import re
-import gtest_test_utils
+import sys
+from googletest.test import gtest_test_utils
 
 
 IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
+IS_GNUHURD = os.name == 'posix' and os.uname()[0] == 'GNU'
 IS_GNUKFREEBSD = os.name == 'posix' and os.uname()[0] == 'GNU/kFreeBSD'
+IS_OPENBSD = os.name == 'posix' and os.uname()[0] == 'OpenBSD'
 IS_WINDOWS = os.name == 'nt'
 
 PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_help_test_')
 FLAG_PREFIX = '--gtest_'
 DEATH_TEST_STYLE_FLAG = FLAG_PREFIX + 'death_test_style'
 STREAM_RESULT_TO_FLAG = FLAG_PREFIX + 'stream_result_to'
-UNKNOWN_FLAG = FLAG_PREFIX + 'unknown_flag_for_testing'
+UNKNOWN_GTEST_PREFIXED_FLAG = FLAG_PREFIX + 'unknown_flag_for_testing'
 LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests'
-INCORRECT_FLAG_VARIANTS = [re.sub('^--', '-', LIST_TESTS_FLAG),
-                           re.sub('^--', '/', LIST_TESTS_FLAG),
-                           re.sub('_', '-', LIST_TESTS_FLAG)]
 INTERNAL_FLAG_FOR_TESTING = FLAG_PREFIX + 'internal_flag_for_testing'
 
 SUPPORTS_DEATH_TESTS = "DeathTest" in gtest_test_utils.Subprocess(
     [PROGRAM_PATH, LIST_TESTS_FLAG]).output
 
+HAS_ABSL_FLAGS = '--has_absl_flags' in sys.argv
+
 # The help message must match this regex.
 HELP_REGEX = re.compile(
     FLAG_PREFIX + r'list_tests.*' +
@@ -109,18 +111,37 @@ class GTestHelpTest(gtest_test_utils.TestCase):
     """
 
     exit_code, output = RunWithFlag(flag)
-    self.assertEquals(0, exit_code)
-    self.assert_(HELP_REGEX.search(output), output)
+    if HAS_ABSL_FLAGS:
+      # The Abseil flags library prints the ProgramUsageMessage() with
+      # --help and returns 1.
+      self.assertEqual(1, exit_code)
+    else:
+      self.assertEqual(0, exit_code)
+
+    self.assertTrue(HELP_REGEX.search(output), output)
 
-    if IS_LINUX or IS_GNUKFREEBSD:
-      self.assert_(STREAM_RESULT_TO_FLAG in output, output)
+    if IS_LINUX or IS_GNUHURD or IS_GNUKFREEBSD or IS_OPENBSD:
+      self.assertIn(STREAM_RESULT_TO_FLAG, output)
     else:
-      self.assert_(STREAM_RESULT_TO_FLAG not in output, output)
+      self.assertNotIn(STREAM_RESULT_TO_FLAG, output)
 
     if SUPPORTS_DEATH_TESTS and not IS_WINDOWS:
-      self.assert_(DEATH_TEST_STYLE_FLAG in output, output)
+      self.assertIn(DEATH_TEST_STYLE_FLAG, output)
     else:
-      self.assert_(DEATH_TEST_STYLE_FLAG not in output, output)
+      self.assertNotIn(DEATH_TEST_STYLE_FLAG, output)
+
+  def TestUnknownFlagWithAbseil(self, flag):
+    """Verifies correct behavior when an unknown flag is specified.
+
+    The right message must be printed and the tests must
+    skipped when the given flag is specified.
+
+    Args:
+      flag:  A flag to pass to the binary or None.
+    """
+    exit_code, output = RunWithFlag(flag)
+    self.assertEqual(1, exit_code)
+    self.assertIn('ERROR: Unknown command line flag', output)
 
   def TestNonHelpFlag(self, flag):
     """Verifies correct behavior when no help flag is specified.
@@ -133,27 +154,21 @@ class GTestHelpTest(gtest_test_utils.TestCase):
     """
 
     exit_code, output = RunWithFlag(flag)
-    self.assert_(exit_code != 0)
-    self.assert_(not HELP_REGEX.search(output), output)
+    self.assertNotEqual(exit_code, 0)
+    self.assertFalse(HELP_REGEX.search(output), output)
 
   def testPrintsHelpWithFullFlag(self):
     self.TestHelpFlag('--help')
 
-  def testPrintsHelpWithShortFlag(self):
-    self.TestHelpFlag('-h')
-
-  def testPrintsHelpWithQuestionFlag(self):
-    self.TestHelpFlag('-?')
-
-  def testPrintsHelpWithWindowsStyleQuestionFlag(self):
-    self.TestHelpFlag('/?')
-
   def testPrintsHelpWithUnrecognizedGoogleTestFlag(self):
-    self.TestHelpFlag(UNKNOWN_FLAG)
-
-  def testPrintsHelpWithIncorrectFlagStyle(self):
-    for incorrect_flag in INCORRECT_FLAG_VARIANTS:
-      self.TestHelpFlag(incorrect_flag)
+    # The behavior is slightly different when Abseil flags is
+    # used. Abseil flags rejects all unknown flags, while the builtin
+    # GTest flags implementation interprets an unknown flag with a
+    # '--gtest_' prefix as a request for help.
+    if HAS_ABSL_FLAGS:
+      self.TestUnknownFlagWithAbseil(UNKNOWN_GTEST_PREFIXED_FLAG)
+    else:
+      self.TestHelpFlag(UNKNOWN_GTEST_PREFIXED_FLAG)
 
   def testRunsTestsWithoutHelpFlag(self):
     """Verifies that when no help flag is specified, the tests are run
@@ -169,4 +184,6 @@ class GTestHelpTest(gtest_test_utils.TestCase):
 
 
 if __name__ == '__main__':
+  if '--has_absl_flags' in sys.argv:
+    sys.argv.remove('--has_absl_flags')
   gtest_test_utils.Main()
index 750ae6ce95fcbcb338ed5db2b588f15cdd5c2f9e..da289f05f3f4189282e8a2253c0a28d59d2c308a 100644 (file)
@@ -27,7 +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.
 
-
 // This program is meant to be run by gtest_help_test.py.  Do not run
 // it directly.
 
index 62bbfc288f82b387cd83446c0a05ba167b1aa754..f62896c9234b6c9f173798bb07702235537e1515 100644 (file)
@@ -50,6 +50,8 @@ def normalize(obj):
     elif key == 'failure':
       value = re.sub(r'^.*[/\\](.*:)\d+\n', '\\1*\n', value)
       return re.sub(r'Stack trace:\n(.|\n)*', 'Stack trace:\n*', value)
+    elif key == 'file':
+      return re.sub(r'^.*[/\\](.*)', '\\1', value)
     else:
       return normalize(value)
   if isinstance(obj, dict):
index a442fc169c87fc0debb42d352b28c6371def302a..faacf103c342b8e68c5ed4ba6bb03c018671bd2d 100644 (file)
@@ -40,7 +40,7 @@ This script tests such functionality by invoking gtest_list_output_unittest_
 
 import os
 import re
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 GTEST_LIST_TESTS_FLAG = '--gtest_list_tests'
 GTEST_OUTPUT_FLAG = '--gtest_output'
index eddedeabe8f3bb083dabca600e72f451b8d94cdb..29cd5510a4b1b85216db5e08fc78636ed551155a 100644 (file)
@@ -27,7 +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.
 
-
 #include "gtest/gtest.h"
 
 // Tests that we don't have to define main() when we link to
@@ -35,8 +34,7 @@
 
 namespace {
 
-TEST(GTestMainTest, ShouldSucceed) {
-}
+TEST(GTestMainTest, ShouldSucceed) {}
 
 }  // namespace
 
index bbef9947d99da43a6455f308ca17b7b6cb301bfe..3d4366537430a2383ceaa4d9026133d9604cc85b 100644 (file)
@@ -27,9 +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.
 
-// This file is AUTOMATICALLY GENERATED on 11/05/2019 by command
-// 'gen_gtest_pred_impl.py 5'.  DO NOT EDIT BY HAND!
-
 // Regression test for gtest_pred_impl.h
 //
 // This file is generated by a script and quite long.  If you intend to
@@ -49,8 +46,8 @@
 
 #include <iostream>
 
-#include "gtest/gtest.h"
 #include "gtest/gtest-spi.h"
+#include "gtest/gtest.h"
 
 // A user-defined data type.
 struct Bool {
@@ -80,12 +77,8 @@ bool PredFunction1(T1 v1) {
 
 // The following two functions are needed because a compiler doesn't have
 // a context yet to know which template function must be instantiated.
-bool PredFunction1Int(int v1) {
-  return v1 > 0;
-}
-bool PredFunction1Bool(Bool v1) {
-  return v1 > 0;
-}
+bool PredFunction1Int(int v1) { return v1 > 0; }
+bool PredFunction1Bool(Bool v1) { return v1 > 0; }
 
 // A unary predicate functor.
 struct PredFunctor1 {
@@ -97,22 +90,17 @@ struct PredFunctor1 {
 
 // A unary predicate-formatter function.
 template <typename T1>
-testing::AssertionResult PredFormatFunction1(const char* e1,
-                                             const T1& v1) {
-  if (PredFunction1(v1))
-    return testing::AssertionSuccess();
+testing::AssertionResult PredFormatFunction1(const char* e1, const T1& v1) {
+  if (PredFunction1(v1)) return testing::AssertionSuccess();
 
   return testing::AssertionFailure()
-      << e1
-      << " is expected to be positive, but evaluates to "
-      << v1 << ".";
+         << e1 << " is expected to be positive, but evaluates to " << v1 << ".";
 }
 
 // A unary predicate-formatter functor.
 struct PredFormatFunctor1 {
   template <typename T1>
-  testing::AssertionResult operator()(const char* e1,
-                                      const T1& v1) const {
+  testing::AssertionResult operator()(const char* e1, const T1& v1) const {
     return PredFormatFunction1(e1, v1);
   }
 };
@@ -130,13 +118,12 @@ class Predicate1Test : public testing::Test {
   void TearDown() override {
     // Verifies that each of the predicate's arguments was evaluated
     // exactly once.
-    EXPECT_EQ(1, n1_) <<
-        "The predicate assertion didn't evaluate argument 2 "
-        "exactly once.";
+    EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 "
+                         "exactly once.";
 
     // Verifies that the control flow in the test function is expected.
     if (expected_to_finish_ && !finished_) {
-      FAIL() << "The predicate assertion unexpactedly aborted the test.";
+      FAIL() << "The predicate assertion unexpectedly aborted the test.";
     } else if (!expected_to_finish_ && finished_) {
       FAIL() << "The failed predicate assertion didn't abort the test "
                 "as expected.";
@@ -164,104 +151,100 @@ typedef Predicate1Test ASSERT_PRED1Test;
 // Tests a successful EXPECT_PRED1 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED1Test, FunctionOnBuiltInTypeSuccess) {
-  EXPECT_PRED1(PredFunction1Int,
-               ++n1_);
+  EXPECT_PRED1(PredFunction1Int, ++n1_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED1 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED1Test, FunctionOnUserTypeSuccess) {
-  EXPECT_PRED1(PredFunction1Bool,
-               Bool(++n1_));
+  EXPECT_PRED1(PredFunction1Bool, Bool(++n1_));
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED1 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED1Test, FunctorOnBuiltInTypeSuccess) {
-  EXPECT_PRED1(PredFunctor1(),
-               ++n1_);
+  EXPECT_PRED1(PredFunctor1(), ++n1_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED1 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED1Test, FunctorOnUserTypeSuccess) {
-  EXPECT_PRED1(PredFunctor1(),
-               Bool(++n1_));
+  EXPECT_PRED1(PredFunctor1(), Bool(++n1_));
   finished_ = true;
 }
 
 // Tests a failed EXPECT_PRED1 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED1Test, FunctionOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED1(PredFunction1Int,
-                 n1_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED1(PredFunction1Int, n1_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED1 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED1Test, FunctionOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED1(PredFunction1Bool,
-                 Bool(n1_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED1(PredFunction1Bool, Bool(n1_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED1 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED1Test, FunctorOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED1(PredFunctor1(),
-                 n1_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED1(PredFunctor1(), n1_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED1 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED1Test, FunctorOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED1(PredFunctor1(),
-                 Bool(n1_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED1(PredFunctor1(), Bool(n1_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a successful ASSERT_PRED1 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED1Test, FunctionOnBuiltInTypeSuccess) {
-  ASSERT_PRED1(PredFunction1Int,
-               ++n1_);
+  ASSERT_PRED1(PredFunction1Int, ++n1_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED1 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED1Test, FunctionOnUserTypeSuccess) {
-  ASSERT_PRED1(PredFunction1Bool,
-               Bool(++n1_));
+  ASSERT_PRED1(PredFunction1Bool, Bool(++n1_));
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED1 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED1Test, FunctorOnBuiltInTypeSuccess) {
-  ASSERT_PRED1(PredFunctor1(),
-               ++n1_);
+  ASSERT_PRED1(PredFunctor1(), ++n1_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED1 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED1Test, FunctorOnUserTypeSuccess) {
-  ASSERT_PRED1(PredFunctor1(),
-               Bool(++n1_));
+  ASSERT_PRED1(PredFunctor1(), Bool(++n1_));
   finished_ = true;
 }
 
@@ -269,147 +252,147 @@ TEST_F(ASSERT_PRED1Test, FunctorOnUserTypeSuccess) {
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED1Test, FunctionOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED1(PredFunction1Int,
-                 n1_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED1(PredFunction1Int, n1_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED1 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED1Test, FunctionOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED1(PredFunction1Bool,
-                 Bool(n1_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED1(PredFunction1Bool, Bool(n1_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED1 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED1Test, FunctorOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED1(PredFunctor1(),
-                 n1_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED1(PredFunctor1(), n1_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED1 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED1Test, FunctorOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED1(PredFunctor1(),
-                 Bool(n1_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED1(PredFunctor1(), Bool(n1_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a successful EXPECT_PRED_FORMAT1 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnBuiltInTypeSuccess) {
-  EXPECT_PRED_FORMAT1(PredFormatFunction1,
-                      ++n1_);
+  EXPECT_PRED_FORMAT1(PredFormatFunction1, ++n1_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED_FORMAT1 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnUserTypeSuccess) {
-  EXPECT_PRED_FORMAT1(PredFormatFunction1,
-                      Bool(++n1_));
+  EXPECT_PRED_FORMAT1(PredFormatFunction1, Bool(++n1_));
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED_FORMAT1 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnBuiltInTypeSuccess) {
-  EXPECT_PRED_FORMAT1(PredFormatFunctor1(),
-                      ++n1_);
+  EXPECT_PRED_FORMAT1(PredFormatFunctor1(), ++n1_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED_FORMAT1 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) {
-  EXPECT_PRED_FORMAT1(PredFormatFunctor1(),
-                      Bool(++n1_));
+  EXPECT_PRED_FORMAT1(PredFormatFunctor1(), Bool(++n1_));
   finished_ = true;
 }
 
 // Tests a failed EXPECT_PRED_FORMAT1 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT1(PredFormatFunction1,
-                        n1_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT1(PredFormatFunction1, n1_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED_FORMAT1 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT1(PredFormatFunction1,
-                        Bool(n1_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT1(PredFormatFunction1, Bool(n1_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED_FORMAT1 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT1(PredFormatFunctor1(),
-                        n1_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT1(PredFormatFunctor1(), n1_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED_FORMAT1 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT1(PredFormatFunctor1(),
-                        Bool(n1_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT1(PredFormatFunctor1(), Bool(n1_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a successful ASSERT_PRED_FORMAT1 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnBuiltInTypeSuccess) {
-  ASSERT_PRED_FORMAT1(PredFormatFunction1,
-                      ++n1_);
+  ASSERT_PRED_FORMAT1(PredFormatFunction1, ++n1_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED_FORMAT1 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnUserTypeSuccess) {
-  ASSERT_PRED_FORMAT1(PredFormatFunction1,
-                      Bool(++n1_));
+  ASSERT_PRED_FORMAT1(PredFormatFunction1, Bool(++n1_));
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED_FORMAT1 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnBuiltInTypeSuccess) {
-  ASSERT_PRED_FORMAT1(PredFormatFunctor1(),
-                      ++n1_);
+  ASSERT_PRED_FORMAT1(PredFormatFunctor1(), ++n1_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED_FORMAT1 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) {
-  ASSERT_PRED_FORMAT1(PredFormatFunctor1(),
-                      Bool(++n1_));
+  ASSERT_PRED_FORMAT1(PredFormatFunctor1(), Bool(++n1_));
   finished_ = true;
 }
 
@@ -417,44 +400,48 @@ TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) {
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT1(PredFormatFunction1,
-                        n1_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT1(PredFormatFunction1, n1_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED_FORMAT1 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT1(PredFormatFunction1,
-                        Bool(n1_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT1(PredFormatFunction1, Bool(n1_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED_FORMAT1 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT1(PredFormatFunctor1(),
-                        n1_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT1(PredFormatFunctor1(), n1_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED_FORMAT1 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT1(PredFormatFunctor1(),
-                        Bool(n1_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT1(PredFormatFunctor1(), Bool(n1_++));
+        finished_ = true;
+      },
+      "");
 }
 // Sample functions/functors for testing binary predicate assertions.
 
@@ -466,44 +453,33 @@ bool PredFunction2(T1 v1, T2 v2) {
 
 // The following two functions are needed because a compiler doesn't have
 // a context yet to know which template function must be instantiated.
-bool PredFunction2Int(int v1, int v2) {
-  return v1 + v2 > 0;
-}
-bool PredFunction2Bool(Bool v1, Bool v2) {
-  return v1 + v2 > 0;
-}
+bool PredFunction2Int(int v1, int v2) { return v1 + v2 > 0; }
+bool PredFunction2Bool(Bool v1, Bool v2) { return v1 + v2 > 0; }
 
 // A binary predicate functor.
 struct PredFunctor2 {
   template <typename T1, typename T2>
-  bool operator()(const T1& v1,
-                  const T2& v2) {
+  bool operator()(const T1& v1, const T2& v2) {
     return v1 + v2 > 0;
   }
 };
 
 // A binary predicate-formatter function.
 template <typename T1, typename T2>
-testing::AssertionResult PredFormatFunction2(const char* e1,
-                                             const char* e2,
-                                             const T1& v1,
-                                             const T2& v2) {
-  if (PredFunction2(v1, v2))
-    return testing::AssertionSuccess();
+testing::AssertionResult PredFormatFunction2(const char* e1, const char* e2,
+                                             const T1& v1, const T2& v2) {
+  if (PredFunction2(v1, v2)) return testing::AssertionSuccess();
 
   return testing::AssertionFailure()
-      << e1 << " + " << e2
-      << " is expected to be positive, but evaluates to "
-      << v1 + v2 << ".";
+         << e1 << " + " << e2
+         << " is expected to be positive, but evaluates to " << v1 + v2 << ".";
 }
 
 // A binary predicate-formatter functor.
 struct PredFormatFunctor2 {
   template <typename T1, typename T2>
-  testing::AssertionResult operator()(const char* e1,
-                                      const char* e2,
-                                      const T1& v1,
-                                      const T2& v2) const {
+  testing::AssertionResult operator()(const char* e1, const char* e2,
+                                      const T1& v1, const T2& v2) const {
     return PredFormatFunction2(e1, e2, v1, v2);
   }
 };
@@ -521,16 +497,14 @@ class Predicate2Test : public testing::Test {
   void TearDown() override {
     // Verifies that each of the predicate's arguments was evaluated
     // exactly once.
-    EXPECT_EQ(1, n1_) <<
-        "The predicate assertion didn't evaluate argument 2 "
-        "exactly once.";
-    EXPECT_EQ(1, n2_) <<
-        "The predicate assertion didn't evaluate argument 3 "
-        "exactly once.";
+    EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 "
+                         "exactly once.";
+    EXPECT_EQ(1, n2_) << "The predicate assertion didn't evaluate argument 3 "
+                         "exactly once.";
 
     // Verifies that the control flow in the test function is expected.
     if (expected_to_finish_ && !finished_) {
-      FAIL() << "The predicate assertion unexpactedly aborted the test.";
+      FAIL() << "The predicate assertion unexpectedly aborted the test.";
     } else if (!expected_to_finish_ && finished_) {
       FAIL() << "The failed predicate assertion didn't abort the test "
                 "as expected.";
@@ -560,116 +534,100 @@ typedef Predicate2Test ASSERT_PRED2Test;
 // Tests a successful EXPECT_PRED2 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED2Test, FunctionOnBuiltInTypeSuccess) {
-  EXPECT_PRED2(PredFunction2Int,
-               ++n1_,
-               ++n2_);
+  EXPECT_PRED2(PredFunction2Int, ++n1_, ++n2_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED2 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED2Test, FunctionOnUserTypeSuccess) {
-  EXPECT_PRED2(PredFunction2Bool,
-               Bool(++n1_),
-               Bool(++n2_));
+  EXPECT_PRED2(PredFunction2Bool, Bool(++n1_), Bool(++n2_));
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED2 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED2Test, FunctorOnBuiltInTypeSuccess) {
-  EXPECT_PRED2(PredFunctor2(),
-               ++n1_,
-               ++n2_);
+  EXPECT_PRED2(PredFunctor2(), ++n1_, ++n2_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED2 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED2Test, FunctorOnUserTypeSuccess) {
-  EXPECT_PRED2(PredFunctor2(),
-               Bool(++n1_),
-               Bool(++n2_));
+  EXPECT_PRED2(PredFunctor2(), Bool(++n1_), Bool(++n2_));
   finished_ = true;
 }
 
 // Tests a failed EXPECT_PRED2 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED2Test, FunctionOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED2(PredFunction2Int,
-                 n1_++,
-                 n2_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED2(PredFunction2Int, n1_++, n2_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED2 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED2Test, FunctionOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED2(PredFunction2Bool,
-                 Bool(n1_++),
-                 Bool(n2_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED2(PredFunction2Bool, Bool(n1_++), Bool(n2_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED2 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED2Test, FunctorOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED2(PredFunctor2(),
-                 n1_++,
-                 n2_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED2(PredFunctor2(), n1_++, n2_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED2 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED2Test, FunctorOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED2(PredFunctor2(),
-                 Bool(n1_++),
-                 Bool(n2_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED2(PredFunctor2(), Bool(n1_++), Bool(n2_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a successful ASSERT_PRED2 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED2Test, FunctionOnBuiltInTypeSuccess) {
-  ASSERT_PRED2(PredFunction2Int,
-               ++n1_,
-               ++n2_);
+  ASSERT_PRED2(PredFunction2Int, ++n1_, ++n2_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED2 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED2Test, FunctionOnUserTypeSuccess) {
-  ASSERT_PRED2(PredFunction2Bool,
-               Bool(++n1_),
-               Bool(++n2_));
+  ASSERT_PRED2(PredFunction2Bool, Bool(++n1_), Bool(++n2_));
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED2 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED2Test, FunctorOnBuiltInTypeSuccess) {
-  ASSERT_PRED2(PredFunctor2(),
-               ++n1_,
-               ++n2_);
+  ASSERT_PRED2(PredFunctor2(), ++n1_, ++n2_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED2 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED2Test, FunctorOnUserTypeSuccess) {
-  ASSERT_PRED2(PredFunctor2(),
-               Bool(++n1_),
-               Bool(++n2_));
+  ASSERT_PRED2(PredFunctor2(), Bool(++n1_), Bool(++n2_));
   finished_ = true;
 }
 
@@ -677,163 +635,147 @@ TEST_F(ASSERT_PRED2Test, FunctorOnUserTypeSuccess) {
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED2Test, FunctionOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED2(PredFunction2Int,
-                 n1_++,
-                 n2_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED2(PredFunction2Int, n1_++, n2_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED2 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED2Test, FunctionOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED2(PredFunction2Bool,
-                 Bool(n1_++),
-                 Bool(n2_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED2(PredFunction2Bool, Bool(n1_++), Bool(n2_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED2 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED2Test, FunctorOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED2(PredFunctor2(),
-                 n1_++,
-                 n2_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED2(PredFunctor2(), n1_++, n2_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED2 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED2Test, FunctorOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED2(PredFunctor2(),
-                 Bool(n1_++),
-                 Bool(n2_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED2(PredFunctor2(), Bool(n1_++), Bool(n2_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a successful EXPECT_PRED_FORMAT2 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnBuiltInTypeSuccess) {
-  EXPECT_PRED_FORMAT2(PredFormatFunction2,
-                      ++n1_,
-                      ++n2_);
+  EXPECT_PRED_FORMAT2(PredFormatFunction2, ++n1_, ++n2_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED_FORMAT2 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnUserTypeSuccess) {
-  EXPECT_PRED_FORMAT2(PredFormatFunction2,
-                      Bool(++n1_),
-                      Bool(++n2_));
+  EXPECT_PRED_FORMAT2(PredFormatFunction2, Bool(++n1_), Bool(++n2_));
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED_FORMAT2 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnBuiltInTypeSuccess) {
-  EXPECT_PRED_FORMAT2(PredFormatFunctor2(),
-                      ++n1_,
-                      ++n2_);
+  EXPECT_PRED_FORMAT2(PredFormatFunctor2(), ++n1_, ++n2_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED_FORMAT2 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) {
-  EXPECT_PRED_FORMAT2(PredFormatFunctor2(),
-                      Bool(++n1_),
-                      Bool(++n2_));
+  EXPECT_PRED_FORMAT2(PredFormatFunctor2(), Bool(++n1_), Bool(++n2_));
   finished_ = true;
 }
 
 // Tests a failed EXPECT_PRED_FORMAT2 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT2(PredFormatFunction2,
-                        n1_++,
-                        n2_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT2(PredFormatFunction2, n1_++, n2_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED_FORMAT2 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT2(PredFormatFunction2,
-                        Bool(n1_++),
-                        Bool(n2_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT2(PredFormatFunction2, Bool(n1_++), Bool(n2_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED_FORMAT2 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT2(PredFormatFunctor2(),
-                        n1_++,
-                        n2_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT2(PredFormatFunctor2(), n1_++, n2_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED_FORMAT2 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT2(PredFormatFunctor2(),
-                        Bool(n1_++),
-                        Bool(n2_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT2(PredFormatFunctor2(), Bool(n1_++), Bool(n2_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a successful ASSERT_PRED_FORMAT2 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnBuiltInTypeSuccess) {
-  ASSERT_PRED_FORMAT2(PredFormatFunction2,
-                      ++n1_,
-                      ++n2_);
+  ASSERT_PRED_FORMAT2(PredFormatFunction2, ++n1_, ++n2_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED_FORMAT2 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnUserTypeSuccess) {
-  ASSERT_PRED_FORMAT2(PredFormatFunction2,
-                      Bool(++n1_),
-                      Bool(++n2_));
+  ASSERT_PRED_FORMAT2(PredFormatFunction2, Bool(++n1_), Bool(++n2_));
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED_FORMAT2 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnBuiltInTypeSuccess) {
-  ASSERT_PRED_FORMAT2(PredFormatFunctor2(),
-                      ++n1_,
-                      ++n2_);
+  ASSERT_PRED_FORMAT2(PredFormatFunctor2(), ++n1_, ++n2_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED_FORMAT2 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) {
-  ASSERT_PRED_FORMAT2(PredFormatFunctor2(),
-                      Bool(++n1_),
-                      Bool(++n2_));
+  ASSERT_PRED_FORMAT2(PredFormatFunctor2(), Bool(++n1_), Bool(++n2_));
   finished_ = true;
 }
 
@@ -841,48 +783,48 @@ TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) {
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT2(PredFormatFunction2,
-                        n1_++,
-                        n2_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT2(PredFormatFunction2, n1_++, n2_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED_FORMAT2 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT2(PredFormatFunction2,
-                        Bool(n1_++),
-                        Bool(n2_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT2(PredFormatFunction2, Bool(n1_++), Bool(n2_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED_FORMAT2 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT2(PredFormatFunctor2(),
-                        n1_++,
-                        n2_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT2(PredFormatFunctor2(), n1_++, n2_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED_FORMAT2 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT2(PredFormatFunctor2(),
-                        Bool(n1_++),
-                        Bool(n2_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT2(PredFormatFunctor2(), Bool(n1_++), Bool(n2_++));
+        finished_ = true;
+      },
+      "");
 }
 // Sample functions/functors for testing ternary predicate assertions.
 
@@ -894,49 +836,36 @@ bool PredFunction3(T1 v1, T2 v2, T3 v3) {
 
 // The following two functions are needed because a compiler doesn't have
 // a context yet to know which template function must be instantiated.
-bool PredFunction3Int(int v1, int v2, int v3) {
-  return v1 + v2 + v3 > 0;
-}
-bool PredFunction3Bool(Bool v1, Bool v2, Bool v3) {
-  return v1 + v2 + v3 > 0;
-}
+bool PredFunction3Int(int v1, int v2, int v3) { return v1 + v2 + v3 > 0; }
+bool PredFunction3Bool(Bool v1, Bool v2, Bool v3) { return v1 + v2 + v3 > 0; }
 
 // A ternary predicate functor.
 struct PredFunctor3 {
   template <typename T1, typename T2, typename T3>
-  bool operator()(const T1& v1,
-                  const T2& v2,
-                  const T3& v3) {
+  bool operator()(const T1& v1, const T2& v2, const T3& v3) {
     return v1 + v2 + v3 > 0;
   }
 };
 
 // A ternary predicate-formatter function.
 template <typename T1, typename T2, typename T3>
-testing::AssertionResult PredFormatFunction3(const char* e1,
-                                             const char* e2,
-                                             const char* e3,
-                                             const T1& v1,
-                                             const T2& v2,
-                                             const T3& v3) {
-  if (PredFunction3(v1, v2, v3))
-    return testing::AssertionSuccess();
+testing::AssertionResult PredFormatFunction3(const char* e1, const char* e2,
+                                             const char* e3, const T1& v1,
+                                             const T2& v2, const T3& v3) {
+  if (PredFunction3(v1, v2, v3)) return testing::AssertionSuccess();
 
   return testing::AssertionFailure()
-      << e1 << " + " << e2 << " + " << e3
-      << " is expected to be positive, but evaluates to "
-      << v1 + v2 + v3 << ".";
+         << e1 << " + " << e2 << " + " << e3
+         << " is expected to be positive, but evaluates to " << v1 + v2 + v3
+         << ".";
 }
 
 // A ternary predicate-formatter functor.
 struct PredFormatFunctor3 {
   template <typename T1, typename T2, typename T3>
-  testing::AssertionResult operator()(const char* e1,
-                                      const char* e2,
-                                      const char* e3,
-                                      const T1& v1,
-                                      const T2& v2,
-                                      const T3& v3) const {
+  testing::AssertionResult operator()(const char* e1, const char* e2,
+                                      const char* e3, const T1& v1,
+                                      const T2& v2, const T3& v3) const {
     return PredFormatFunction3(e1, e2, e3, v1, v2, v3);
   }
 };
@@ -954,19 +883,16 @@ class Predicate3Test : public testing::Test {
   void TearDown() override {
     // Verifies that each of the predicate's arguments was evaluated
     // exactly once.
-    EXPECT_EQ(1, n1_) <<
-        "The predicate assertion didn't evaluate argument 2 "
-        "exactly once.";
-    EXPECT_EQ(1, n2_) <<
-        "The predicate assertion didn't evaluate argument 3 "
-        "exactly once.";
-    EXPECT_EQ(1, n3_) <<
-        "The predicate assertion didn't evaluate argument 4 "
-        "exactly once.";
+    EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 "
+                         "exactly once.";
+    EXPECT_EQ(1, n2_) << "The predicate assertion didn't evaluate argument 3 "
+                         "exactly once.";
+    EXPECT_EQ(1, n3_) << "The predicate assertion didn't evaluate argument 4 "
+                         "exactly once.";
 
     // Verifies that the control flow in the test function is expected.
     if (expected_to_finish_ && !finished_) {
-      FAIL() << "The predicate assertion unexpactedly aborted the test.";
+      FAIL() << "The predicate assertion unexpectedly aborted the test.";
     } else if (!expected_to_finish_ && finished_) {
       FAIL() << "The failed predicate assertion didn't abort the test "
                 "as expected.";
@@ -998,128 +924,100 @@ typedef Predicate3Test ASSERT_PRED3Test;
 // Tests a successful EXPECT_PRED3 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED3Test, FunctionOnBuiltInTypeSuccess) {
-  EXPECT_PRED3(PredFunction3Int,
-               ++n1_,
-               ++n2_,
-               ++n3_);
+  EXPECT_PRED3(PredFunction3Int, ++n1_, ++n2_, ++n3_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED3 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED3Test, FunctionOnUserTypeSuccess) {
-  EXPECT_PRED3(PredFunction3Bool,
-               Bool(++n1_),
-               Bool(++n2_),
-               Bool(++n3_));
+  EXPECT_PRED3(PredFunction3Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_));
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED3 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED3Test, FunctorOnBuiltInTypeSuccess) {
-  EXPECT_PRED3(PredFunctor3(),
-               ++n1_,
-               ++n2_,
-               ++n3_);
+  EXPECT_PRED3(PredFunctor3(), ++n1_, ++n2_, ++n3_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED3 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED3Test, FunctorOnUserTypeSuccess) {
-  EXPECT_PRED3(PredFunctor3(),
-               Bool(++n1_),
-               Bool(++n2_),
-               Bool(++n3_));
+  EXPECT_PRED3(PredFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_));
   finished_ = true;
 }
 
 // Tests a failed EXPECT_PRED3 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED3Test, FunctionOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED3(PredFunction3Int,
-                 n1_++,
-                 n2_++,
-                 n3_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED3(PredFunction3Int, n1_++, n2_++, n3_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED3 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED3Test, FunctionOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED3(PredFunction3Bool,
-                 Bool(n1_++),
-                 Bool(n2_++),
-                 Bool(n3_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED3(PredFunction3Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED3 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED3Test, FunctorOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED3(PredFunctor3(),
-                 n1_++,
-                 n2_++,
-                 n3_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED3(PredFunctor3(), n1_++, n2_++, n3_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED3 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED3Test, FunctorOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED3(PredFunctor3(),
-                 Bool(n1_++),
-                 Bool(n2_++),
-                 Bool(n3_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED3(PredFunctor3(), Bool(n1_++), Bool(n2_++), Bool(n3_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a successful ASSERT_PRED3 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED3Test, FunctionOnBuiltInTypeSuccess) {
-  ASSERT_PRED3(PredFunction3Int,
-               ++n1_,
-               ++n2_,
-               ++n3_);
+  ASSERT_PRED3(PredFunction3Int, ++n1_, ++n2_, ++n3_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED3 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED3Test, FunctionOnUserTypeSuccess) {
-  ASSERT_PRED3(PredFunction3Bool,
-               Bool(++n1_),
-               Bool(++n2_),
-               Bool(++n3_));
+  ASSERT_PRED3(PredFunction3Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_));
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED3 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED3Test, FunctorOnBuiltInTypeSuccess) {
-  ASSERT_PRED3(PredFunctor3(),
-               ++n1_,
-               ++n2_,
-               ++n3_);
+  ASSERT_PRED3(PredFunctor3(), ++n1_, ++n2_, ++n3_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED3 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED3Test, FunctorOnUserTypeSuccess) {
-  ASSERT_PRED3(PredFunctor3(),
-               Bool(++n1_),
-               Bool(++n2_),
-               Bool(++n3_));
+  ASSERT_PRED3(PredFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_));
   finished_ = true;
 }
 
@@ -1127,70 +1025,61 @@ TEST_F(ASSERT_PRED3Test, FunctorOnUserTypeSuccess) {
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED3Test, FunctionOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED3(PredFunction3Int,
-                 n1_++,
-                 n2_++,
-                 n3_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED3(PredFunction3Int, n1_++, n2_++, n3_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED3 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED3Test, FunctionOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED3(PredFunction3Bool,
-                 Bool(n1_++),
-                 Bool(n2_++),
-                 Bool(n3_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED3(PredFunction3Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED3 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED3Test, FunctorOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED3(PredFunctor3(),
-                 n1_++,
-                 n2_++,
-                 n3_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED3(PredFunctor3(), n1_++, n2_++, n3_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED3 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED3Test, FunctorOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED3(PredFunctor3(),
-                 Bool(n1_++),
-                 Bool(n2_++),
-                 Bool(n3_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED3(PredFunctor3(), Bool(n1_++), Bool(n2_++), Bool(n3_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a successful EXPECT_PRED_FORMAT3 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnBuiltInTypeSuccess) {
-  EXPECT_PRED_FORMAT3(PredFormatFunction3,
-                      ++n1_,
-                      ++n2_,
-                      ++n3_);
+  EXPECT_PRED_FORMAT3(PredFormatFunction3, ++n1_, ++n2_, ++n3_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED_FORMAT3 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) {
-  EXPECT_PRED_FORMAT3(PredFormatFunction3,
-                      Bool(++n1_),
-                      Bool(++n2_),
+  EXPECT_PRED_FORMAT3(PredFormatFunction3, Bool(++n1_), Bool(++n2_),
                       Bool(++n3_));
   finished_ = true;
 }
@@ -1198,19 +1087,14 @@ TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) {
 // Tests a successful EXPECT_PRED_FORMAT3 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnBuiltInTypeSuccess) {
-  EXPECT_PRED_FORMAT3(PredFormatFunctor3(),
-                      ++n1_,
-                      ++n2_,
-                      ++n3_);
+  EXPECT_PRED_FORMAT3(PredFormatFunctor3(), ++n1_, ++n2_, ++n3_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED_FORMAT3 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) {
-  EXPECT_PRED_FORMAT3(PredFormatFunctor3(),
-                      Bool(++n1_),
-                      Bool(++n2_),
+  EXPECT_PRED_FORMAT3(PredFormatFunctor3(), Bool(++n1_), Bool(++n2_),
                       Bool(++n3_));
   finished_ = true;
 }
@@ -1218,67 +1102,60 @@ TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) {
 // Tests a failed EXPECT_PRED_FORMAT3 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT3(PredFormatFunction3,
-                        n1_++,
-                        n2_++,
-                        n3_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT3(PredFormatFunction3, n1_++, n2_++, n3_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED_FORMAT3 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT3(PredFormatFunction3,
-                        Bool(n1_++),
-                        Bool(n2_++),
-                        Bool(n3_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT3(PredFormatFunction3, Bool(n1_++), Bool(n2_++),
+                            Bool(n3_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED_FORMAT3 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT3(PredFormatFunctor3(),
-                        n1_++,
-                        n2_++,
-                        n3_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT3(PredFormatFunctor3(), n1_++, n2_++, n3_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED_FORMAT3 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT3(PredFormatFunctor3(),
-                        Bool(n1_++),
-                        Bool(n2_++),
-                        Bool(n3_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT3(PredFormatFunctor3(), Bool(n1_++), Bool(n2_++),
+                            Bool(n3_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a successful ASSERT_PRED_FORMAT3 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnBuiltInTypeSuccess) {
-  ASSERT_PRED_FORMAT3(PredFormatFunction3,
-                      ++n1_,
-                      ++n2_,
-                      ++n3_);
+  ASSERT_PRED_FORMAT3(PredFormatFunction3, ++n1_, ++n2_, ++n3_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED_FORMAT3 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) {
-  ASSERT_PRED_FORMAT3(PredFormatFunction3,
-                      Bool(++n1_),
-                      Bool(++n2_),
+  ASSERT_PRED_FORMAT3(PredFormatFunction3, Bool(++n1_), Bool(++n2_),
                       Bool(++n3_));
   finished_ = true;
 }
@@ -1286,19 +1163,14 @@ TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) {
 // Tests a successful ASSERT_PRED_FORMAT3 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnBuiltInTypeSuccess) {
-  ASSERT_PRED_FORMAT3(PredFormatFunctor3(),
-                      ++n1_,
-                      ++n2_,
-                      ++n3_);
+  ASSERT_PRED_FORMAT3(PredFormatFunctor3(), ++n1_, ++n2_, ++n3_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED_FORMAT3 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) {
-  ASSERT_PRED_FORMAT3(PredFormatFunctor3(),
-                      Bool(++n1_),
-                      Bool(++n2_),
+  ASSERT_PRED_FORMAT3(PredFormatFunctor3(), Bool(++n1_), Bool(++n2_),
                       Bool(++n3_));
   finished_ = true;
 }
@@ -1307,52 +1179,50 @@ TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) {
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT3(PredFormatFunction3,
-                        n1_++,
-                        n2_++,
-                        n3_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT3(PredFormatFunction3, n1_++, n2_++, n3_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED_FORMAT3 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT3(PredFormatFunction3,
-                        Bool(n1_++),
-                        Bool(n2_++),
-                        Bool(n3_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT3(PredFormatFunction3, Bool(n1_++), Bool(n2_++),
+                            Bool(n3_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED_FORMAT3 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT3(PredFormatFunctor3(),
-                        n1_++,
-                        n2_++,
-                        n3_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT3(PredFormatFunctor3(), n1_++, n2_++, n3_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED_FORMAT3 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT3(PredFormatFunctor3(),
-                        Bool(n1_++),
-                        Bool(n2_++),
-                        Bool(n3_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT3(PredFormatFunctor3(), Bool(n1_++), Bool(n2_++),
+                            Bool(n3_++));
+        finished_ = true;
+      },
+      "");
 }
 // Sample functions/functors for testing 4-ary predicate assertions.
 
@@ -1374,43 +1244,31 @@ bool PredFunction4Bool(Bool v1, Bool v2, Bool v3, Bool v4) {
 // A 4-ary predicate functor.
 struct PredFunctor4 {
   template <typename T1, typename T2, typename T3, typename T4>
-  bool operator()(const T1& v1,
-                  const T2& v2,
-                  const T3& v3,
-                  const T4& v4) {
+  bool operator()(const T1& v1, const T2& v2, const T3& v3, const T4& v4) {
     return v1 + v2 + v3 + v4 > 0;
   }
 };
 
 // A 4-ary predicate-formatter function.
 template <typename T1, typename T2, typename T3, typename T4>
-testing::AssertionResult PredFormatFunction4(const char* e1,
-                                             const char* e2,
-                                             const char* e3,
-                                             const char* e4,
-                                             const T1& v1,
-                                             const T2& v2,
-                                             const T3& v3,
-                                             const T4& v4) {
-  if (PredFunction4(v1, v2, v3, v4))
-    return testing::AssertionSuccess();
+testing::AssertionResult PredFormatFunction4(const char* e1, const char* e2,
+                                             const char* e3, const char* e4,
+                                             const T1& v1, const T2& v2,
+                                             const T3& v3, const T4& v4) {
+  if (PredFunction4(v1, v2, v3, v4)) return testing::AssertionSuccess();
 
   return testing::AssertionFailure()
-      << e1 << " + " << e2 << " + " << e3 << " + " << e4
-      << " is expected to be positive, but evaluates to "
-      << v1 + v2 + v3 + v4 << ".";
+         << e1 << " + " << e2 << " + " << e3 << " + " << e4
+         << " is expected to be positive, but evaluates to "
+         << v1 + v2 + v3 + v4 << ".";
 }
 
 // A 4-ary predicate-formatter functor.
 struct PredFormatFunctor4 {
   template <typename T1, typename T2, typename T3, typename T4>
-  testing::AssertionResult operator()(const char* e1,
-                                      const char* e2,
-                                      const char* e3,
-                                      const char* e4,
-                                      const T1& v1,
-                                      const T2& v2,
-                                      const T3& v3,
+  testing::AssertionResult operator()(const char* e1, const char* e2,
+                                      const char* e3, const char* e4,
+                                      const T1& v1, const T2& v2, const T3& v3,
                                       const T4& v4) const {
     return PredFormatFunction4(e1, e2, e3, e4, v1, v2, v3, v4);
   }
@@ -1429,22 +1287,18 @@ class Predicate4Test : public testing::Test {
   void TearDown() override {
     // Verifies that each of the predicate's arguments was evaluated
     // exactly once.
-    EXPECT_EQ(1, n1_) <<
-        "The predicate assertion didn't evaluate argument 2 "
-        "exactly once.";
-    EXPECT_EQ(1, n2_) <<
-        "The predicate assertion didn't evaluate argument 3 "
-        "exactly once.";
-    EXPECT_EQ(1, n3_) <<
-        "The predicate assertion didn't evaluate argument 4 "
-        "exactly once.";
-    EXPECT_EQ(1, n4_) <<
-        "The predicate assertion didn't evaluate argument 5 "
-        "exactly once.";
+    EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 "
+                         "exactly once.";
+    EXPECT_EQ(1, n2_) << "The predicate assertion didn't evaluate argument 3 "
+                         "exactly once.";
+    EXPECT_EQ(1, n3_) << "The predicate assertion didn't evaluate argument 4 "
+                         "exactly once.";
+    EXPECT_EQ(1, n4_) << "The predicate assertion didn't evaluate argument 5 "
+                         "exactly once.";
 
     // Verifies that the control flow in the test function is expected.
     if (expected_to_finish_ && !finished_) {
-      FAIL() << "The predicate assertion unexpactedly aborted the test.";
+      FAIL() << "The predicate assertion unexpectedly aborted the test.";
     } else if (!expected_to_finish_ && finished_) {
       FAIL() << "The failed predicate assertion didn't abort the test "
                 "as expected.";
@@ -1478,21 +1332,14 @@ typedef Predicate4Test ASSERT_PRED4Test;
 // Tests a successful EXPECT_PRED4 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED4Test, FunctionOnBuiltInTypeSuccess) {
-  EXPECT_PRED4(PredFunction4Int,
-               ++n1_,
-               ++n2_,
-               ++n3_,
-               ++n4_);
+  EXPECT_PRED4(PredFunction4Int, ++n1_, ++n2_, ++n3_, ++n4_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED4 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED4Test, FunctionOnUserTypeSuccess) {
-  EXPECT_PRED4(PredFunction4Bool,
-               Bool(++n1_),
-               Bool(++n2_),
-               Bool(++n3_),
+  EXPECT_PRED4(PredFunction4Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_),
                Bool(++n4_));
   finished_ = true;
 }
@@ -1500,21 +1347,14 @@ TEST_F(EXPECT_PRED4Test, FunctionOnUserTypeSuccess) {
 // Tests a successful EXPECT_PRED4 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED4Test, FunctorOnBuiltInTypeSuccess) {
-  EXPECT_PRED4(PredFunctor4(),
-               ++n1_,
-               ++n2_,
-               ++n3_,
-               ++n4_);
+  EXPECT_PRED4(PredFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED4 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED4Test, FunctorOnUserTypeSuccess) {
-  EXPECT_PRED4(PredFunctor4(),
-               Bool(++n1_),
-               Bool(++n2_),
-               Bool(++n3_),
+  EXPECT_PRED4(PredFunctor4(), Bool(++n1_), Bool(++n2_), Bool(++n3_),
                Bool(++n4_));
   finished_ = true;
 }
@@ -1522,73 +1362,60 @@ TEST_F(EXPECT_PRED4Test, FunctorOnUserTypeSuccess) {
 // Tests a failed EXPECT_PRED4 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED4Test, FunctionOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED4(PredFunction4Int,
-                 n1_++,
-                 n2_++,
-                 n3_++,
-                 n4_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED4(PredFunction4Int, n1_++, n2_++, n3_++, n4_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED4 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED4Test, FunctionOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED4(PredFunction4Bool,
-                 Bool(n1_++),
-                 Bool(n2_++),
-                 Bool(n3_++),
-                 Bool(n4_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED4(PredFunction4Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++),
+                     Bool(n4_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED4 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED4Test, FunctorOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED4(PredFunctor4(),
-                 n1_++,
-                 n2_++,
-                 n3_++,
-                 n4_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED4(PredFunctor4(), n1_++, n2_++, n3_++, n4_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED4 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED4Test, FunctorOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED4(PredFunctor4(),
-                 Bool(n1_++),
-                 Bool(n2_++),
-                 Bool(n3_++),
-                 Bool(n4_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED4(PredFunctor4(), Bool(n1_++), Bool(n2_++), Bool(n3_++),
+                     Bool(n4_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a successful ASSERT_PRED4 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED4Test, FunctionOnBuiltInTypeSuccess) {
-  ASSERT_PRED4(PredFunction4Int,
-               ++n1_,
-               ++n2_,
-               ++n3_,
-               ++n4_);
+  ASSERT_PRED4(PredFunction4Int, ++n1_, ++n2_, ++n3_, ++n4_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED4 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED4Test, FunctionOnUserTypeSuccess) {
-  ASSERT_PRED4(PredFunction4Bool,
-               Bool(++n1_),
-               Bool(++n2_),
-               Bool(++n3_),
+  ASSERT_PRED4(PredFunction4Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_),
                Bool(++n4_));
   finished_ = true;
 }
@@ -1596,21 +1423,14 @@ TEST_F(ASSERT_PRED4Test, FunctionOnUserTypeSuccess) {
 // Tests a successful ASSERT_PRED4 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED4Test, FunctorOnBuiltInTypeSuccess) {
-  ASSERT_PRED4(PredFunctor4(),
-               ++n1_,
-               ++n2_,
-               ++n3_,
-               ++n4_);
+  ASSERT_PRED4(PredFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED4 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED4Test, FunctorOnUserTypeSuccess) {
-  ASSERT_PRED4(PredFunctor4(),
-               Bool(++n1_),
-               Bool(++n2_),
-               Bool(++n3_),
+  ASSERT_PRED4(PredFunctor4(), Bool(++n1_), Bool(++n2_), Bool(++n3_),
                Bool(++n4_));
   finished_ = true;
 }
@@ -1619,195 +1439,155 @@ TEST_F(ASSERT_PRED4Test, FunctorOnUserTypeSuccess) {
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED4Test, FunctionOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED4(PredFunction4Int,
-                 n1_++,
-                 n2_++,
-                 n3_++,
-                 n4_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED4(PredFunction4Int, n1_++, n2_++, n3_++, n4_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED4 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED4Test, FunctionOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED4(PredFunction4Bool,
-                 Bool(n1_++),
-                 Bool(n2_++),
-                 Bool(n3_++),
-                 Bool(n4_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED4(PredFunction4Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++),
+                     Bool(n4_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED4 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED4Test, FunctorOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED4(PredFunctor4(),
-                 n1_++,
-                 n2_++,
-                 n3_++,
-                 n4_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED4(PredFunctor4(), n1_++, n2_++, n3_++, n4_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED4 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED4Test, FunctorOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED4(PredFunctor4(),
-                 Bool(n1_++),
-                 Bool(n2_++),
-                 Bool(n3_++),
-                 Bool(n4_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED4(PredFunctor4(), Bool(n1_++), Bool(n2_++), Bool(n3_++),
+                     Bool(n4_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a successful EXPECT_PRED_FORMAT4 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnBuiltInTypeSuccess) {
-  EXPECT_PRED_FORMAT4(PredFormatFunction4,
-                      ++n1_,
-                      ++n2_,
-                      ++n3_,
-                      ++n4_);
+  EXPECT_PRED_FORMAT4(PredFormatFunction4, ++n1_, ++n2_, ++n3_, ++n4_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED_FORMAT4 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnUserTypeSuccess) {
-  EXPECT_PRED_FORMAT4(PredFormatFunction4,
-                      Bool(++n1_),
-                      Bool(++n2_),
-                      Bool(++n3_),
-                      Bool(++n4_));
+  EXPECT_PRED_FORMAT4(PredFormatFunction4, Bool(++n1_), Bool(++n2_),
+                      Bool(++n3_), Bool(++n4_));
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED_FORMAT4 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnBuiltInTypeSuccess) {
-  EXPECT_PRED_FORMAT4(PredFormatFunctor4(),
-                      ++n1_,
-                      ++n2_,
-                      ++n3_,
-                      ++n4_);
+  EXPECT_PRED_FORMAT4(PredFormatFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED_FORMAT4 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnUserTypeSuccess) {
-  EXPECT_PRED_FORMAT4(PredFormatFunctor4(),
-                      Bool(++n1_),
-                      Bool(++n2_),
-                      Bool(++n3_),
-                      Bool(++n4_));
+  EXPECT_PRED_FORMAT4(PredFormatFunctor4(), Bool(++n1_), Bool(++n2_),
+                      Bool(++n3_), Bool(++n4_));
   finished_ = true;
 }
 
 // Tests a failed EXPECT_PRED_FORMAT4 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT4(PredFormatFunction4,
-                        n1_++,
-                        n2_++,
-                        n3_++,
-                        n4_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT4(PredFormatFunction4, n1_++, n2_++, n3_++, n4_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED_FORMAT4 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT4(PredFormatFunction4,
-                        Bool(n1_++),
-                        Bool(n2_++),
-                        Bool(n3_++),
-                        Bool(n4_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT4(PredFormatFunction4, Bool(n1_++), Bool(n2_++),
+                            Bool(n3_++), Bool(n4_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED_FORMAT4 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT4(PredFormatFunctor4(),
-                        n1_++,
-                        n2_++,
-                        n3_++,
-                        n4_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT4(PredFormatFunctor4(), n1_++, n2_++, n3_++, n4_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED_FORMAT4 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT4(PredFormatFunctor4(),
-                        Bool(n1_++),
-                        Bool(n2_++),
-                        Bool(n3_++),
-                        Bool(n4_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT4(PredFormatFunctor4(), Bool(n1_++), Bool(n2_++),
+                            Bool(n3_++), Bool(n4_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a successful ASSERT_PRED_FORMAT4 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnBuiltInTypeSuccess) {
-  ASSERT_PRED_FORMAT4(PredFormatFunction4,
-                      ++n1_,
-                      ++n2_,
-                      ++n3_,
-                      ++n4_);
+  ASSERT_PRED_FORMAT4(PredFormatFunction4, ++n1_, ++n2_, ++n3_, ++n4_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED_FORMAT4 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnUserTypeSuccess) {
-  ASSERT_PRED_FORMAT4(PredFormatFunction4,
-                      Bool(++n1_),
-                      Bool(++n2_),
-                      Bool(++n3_),
-                      Bool(++n4_));
+  ASSERT_PRED_FORMAT4(PredFormatFunction4, Bool(++n1_), Bool(++n2_),
+                      Bool(++n3_), Bool(++n4_));
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED_FORMAT4 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnBuiltInTypeSuccess) {
-  ASSERT_PRED_FORMAT4(PredFormatFunctor4(),
-                      ++n1_,
-                      ++n2_,
-                      ++n3_,
-                      ++n4_);
+  ASSERT_PRED_FORMAT4(PredFormatFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED_FORMAT4 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnUserTypeSuccess) {
-  ASSERT_PRED_FORMAT4(PredFormatFunctor4(),
-                      Bool(++n1_),
-                      Bool(++n2_),
-                      Bool(++n3_),
-                      Bool(++n4_));
+  ASSERT_PRED_FORMAT4(PredFormatFunctor4(), Bool(++n1_), Bool(++n2_),
+                      Bool(++n3_), Bool(++n4_));
   finished_ = true;
 }
 
@@ -1815,56 +1595,50 @@ TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnUserTypeSuccess) {
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT4(PredFormatFunction4,
-                        n1_++,
-                        n2_++,
-                        n3_++,
-                        n4_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT4(PredFormatFunction4, n1_++, n2_++, n3_++, n4_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED_FORMAT4 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT4(PredFormatFunction4,
-                        Bool(n1_++),
-                        Bool(n2_++),
-                        Bool(n3_++),
-                        Bool(n4_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT4(PredFormatFunction4, Bool(n1_++), Bool(n2_++),
+                            Bool(n3_++), Bool(n4_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED_FORMAT4 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT4(PredFormatFunctor4(),
-                        n1_++,
-                        n2_++,
-                        n3_++,
-                        n4_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT4(PredFormatFunctor4(), n1_++, n2_++, n3_++, n4_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED_FORMAT4 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT4(PredFormatFunctor4(),
-                        Bool(n1_++),
-                        Bool(n2_++),
-                        Bool(n3_++),
-                        Bool(n4_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT4(PredFormatFunctor4(), Bool(n1_++), Bool(n2_++),
+                            Bool(n3_++), Bool(n4_++));
+        finished_ = true;
+      },
+      "");
 }
 // Sample functions/functors for testing 5-ary predicate assertions.
 
@@ -1886,10 +1660,7 @@ bool PredFunction5Bool(Bool v1, Bool v2, Bool v3, Bool v4, Bool v5) {
 // A 5-ary predicate functor.
 struct PredFunctor5 {
   template <typename T1, typename T2, typename T3, typename T4, typename T5>
-  bool operator()(const T1& v1,
-                  const T2& v2,
-                  const T3& v3,
-                  const T4& v4,
+  bool operator()(const T1& v1, const T2& v2, const T3& v3, const T4& v4,
                   const T5& v5) {
     return v1 + v2 + v3 + v4 + v5 > 0;
   }
@@ -1897,37 +1668,26 @@ struct PredFunctor5 {
 
 // A 5-ary predicate-formatter function.
 template <typename T1, typename T2, typename T3, typename T4, typename T5>
-testing::AssertionResult PredFormatFunction5(const char* e1,
-                                             const char* e2,
-                                             const char* e3,
-                                             const char* e4,
-                                             const char* e5,
-                                             const T1& v1,
-                                             const T2& v2,
-                                             const T3& v3,
-                                             const T4& v4,
-                                             const T5& v5) {
-  if (PredFunction5(v1, v2, v3, v4, v5))
-    return testing::AssertionSuccess();
+testing::AssertionResult PredFormatFunction5(const char* e1, const char* e2,
+                                             const char* e3, const char* e4,
+                                             const char* e5, const T1& v1,
+                                             const T2& v2, const T3& v3,
+                                             const T4& v4, const T5& v5) {
+  if (PredFunction5(v1, v2, v3, v4, v5)) return testing::AssertionSuccess();
 
   return testing::AssertionFailure()
-      << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
-      << " is expected to be positive, but evaluates to "
-      << v1 + v2 + v3 + v4 + v5 << ".";
+         << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
+         << " is expected to be positive, but evaluates to "
+         << v1 + v2 + v3 + v4 + v5 << ".";
 }
 
 // A 5-ary predicate-formatter functor.
 struct PredFormatFunctor5 {
   template <typename T1, typename T2, typename T3, typename T4, typename T5>
-  testing::AssertionResult operator()(const char* e1,
-                                      const char* e2,
-                                      const char* e3,
-                                      const char* e4,
-                                      const char* e5,
-                                      const T1& v1,
-                                      const T2& v2,
-                                      const T3& v3,
-                                      const T4& v4,
+  testing::AssertionResult operator()(const char* e1, const char* e2,
+                                      const char* e3, const char* e4,
+                                      const char* e5, const T1& v1,
+                                      const T2& v2, const T3& v3, const T4& v4,
                                       const T5& v5) const {
     return PredFormatFunction5(e1, e2, e3, e4, e5, v1, v2, v3, v4, v5);
   }
@@ -1946,25 +1706,20 @@ class Predicate5Test : public testing::Test {
   void TearDown() override {
     // Verifies that each of the predicate's arguments was evaluated
     // exactly once.
-    EXPECT_EQ(1, n1_) <<
-        "The predicate assertion didn't evaluate argument 2 "
-        "exactly once.";
-    EXPECT_EQ(1, n2_) <<
-        "The predicate assertion didn't evaluate argument 3 "
-        "exactly once.";
-    EXPECT_EQ(1, n3_) <<
-        "The predicate assertion didn't evaluate argument 4 "
-        "exactly once.";
-    EXPECT_EQ(1, n4_) <<
-        "The predicate assertion didn't evaluate argument 5 "
-        "exactly once.";
-    EXPECT_EQ(1, n5_) <<
-        "The predicate assertion didn't evaluate argument 6 "
-        "exactly once.";
+    EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 "
+                         "exactly once.";
+    EXPECT_EQ(1, n2_) << "The predicate assertion didn't evaluate argument 3 "
+                         "exactly once.";
+    EXPECT_EQ(1, n3_) << "The predicate assertion didn't evaluate argument 4 "
+                         "exactly once.";
+    EXPECT_EQ(1, n4_) << "The predicate assertion didn't evaluate argument 5 "
+                         "exactly once.";
+    EXPECT_EQ(1, n5_) << "The predicate assertion didn't evaluate argument 6 "
+                         "exactly once.";
 
     // Verifies that the control flow in the test function is expected.
     if (expected_to_finish_ && !finished_) {
-      FAIL() << "The predicate assertion unexpactedly aborted the test.";
+      FAIL() << "The predicate assertion unexpectedly aborted the test.";
     } else if (!expected_to_finish_ && finished_) {
       FAIL() << "The failed predicate assertion didn't abort the test "
                 "as expected.";
@@ -2000,152 +1755,106 @@ typedef Predicate5Test ASSERT_PRED5Test;
 // Tests a successful EXPECT_PRED5 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED5Test, FunctionOnBuiltInTypeSuccess) {
-  EXPECT_PRED5(PredFunction5Int,
-               ++n1_,
-               ++n2_,
-               ++n3_,
-               ++n4_,
-               ++n5_);
+  EXPECT_PRED5(PredFunction5Int, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED5 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED5Test, FunctionOnUserTypeSuccess) {
-  EXPECT_PRED5(PredFunction5Bool,
-               Bool(++n1_),
-               Bool(++n2_),
-               Bool(++n3_),
-               Bool(++n4_),
-               Bool(++n5_));
+  EXPECT_PRED5(PredFunction5Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_),
+               Bool(++n4_), Bool(++n5_));
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED5 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED5Test, FunctorOnBuiltInTypeSuccess) {
-  EXPECT_PRED5(PredFunctor5(),
-               ++n1_,
-               ++n2_,
-               ++n3_,
-               ++n4_,
-               ++n5_);
+  EXPECT_PRED5(PredFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED5 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED5Test, FunctorOnUserTypeSuccess) {
-  EXPECT_PRED5(PredFunctor5(),
-               Bool(++n1_),
-               Bool(++n2_),
-               Bool(++n3_),
-               Bool(++n4_),
-               Bool(++n5_));
+  EXPECT_PRED5(PredFunctor5(), Bool(++n1_), Bool(++n2_), Bool(++n3_),
+               Bool(++n4_), Bool(++n5_));
   finished_ = true;
 }
 
 // Tests a failed EXPECT_PRED5 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED5Test, FunctionOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED5(PredFunction5Int,
-                 n1_++,
-                 n2_++,
-                 n3_++,
-                 n4_++,
-                 n5_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED5(PredFunction5Int, n1_++, n2_++, n3_++, n4_++, n5_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED5 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED5Test, FunctionOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED5(PredFunction5Bool,
-                 Bool(n1_++),
-                 Bool(n2_++),
-                 Bool(n3_++),
-                 Bool(n4_++),
-                 Bool(n5_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED5(PredFunction5Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++),
+                     Bool(n4_++), Bool(n5_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED5 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED5Test, FunctorOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED5(PredFunctor5(),
-                 n1_++,
-                 n2_++,
-                 n3_++,
-                 n4_++,
-                 n5_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED5(PredFunctor5(), n1_++, n2_++, n3_++, n4_++, n5_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED5 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED5Test, FunctorOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED5(PredFunctor5(),
-                 Bool(n1_++),
-                 Bool(n2_++),
-                 Bool(n3_++),
-                 Bool(n4_++),
-                 Bool(n5_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED5(PredFunctor5(), Bool(n1_++), Bool(n2_++), Bool(n3_++),
+                     Bool(n4_++), Bool(n5_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a successful ASSERT_PRED5 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED5Test, FunctionOnBuiltInTypeSuccess) {
-  ASSERT_PRED5(PredFunction5Int,
-               ++n1_,
-               ++n2_,
-               ++n3_,
-               ++n4_,
-               ++n5_);
+  ASSERT_PRED5(PredFunction5Int, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED5 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED5Test, FunctionOnUserTypeSuccess) {
-  ASSERT_PRED5(PredFunction5Bool,
-               Bool(++n1_),
-               Bool(++n2_),
-               Bool(++n3_),
-               Bool(++n4_),
-               Bool(++n5_));
+  ASSERT_PRED5(PredFunction5Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_),
+               Bool(++n4_), Bool(++n5_));
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED5 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED5Test, FunctorOnBuiltInTypeSuccess) {
-  ASSERT_PRED5(PredFunctor5(),
-               ++n1_,
-               ++n2_,
-               ++n3_,
-               ++n4_,
-               ++n5_);
+  ASSERT_PRED5(PredFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED5 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED5Test, FunctorOnUserTypeSuccess) {
-  ASSERT_PRED5(PredFunctor5(),
-               Bool(++n1_),
-               Bool(++n2_),
-               Bool(++n3_),
-               Bool(++n4_),
-               Bool(++n5_));
+  ASSERT_PRED5(PredFunctor5(), Bool(++n1_), Bool(++n2_), Bool(++n3_),
+               Bool(++n4_), Bool(++n5_));
   finished_ = true;
 }
 
@@ -2153,211 +1862,157 @@ TEST_F(ASSERT_PRED5Test, FunctorOnUserTypeSuccess) {
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED5Test, FunctionOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED5(PredFunction5Int,
-                 n1_++,
-                 n2_++,
-                 n3_++,
-                 n4_++,
-                 n5_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED5(PredFunction5Int, n1_++, n2_++, n3_++, n4_++, n5_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED5 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED5Test, FunctionOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED5(PredFunction5Bool,
-                 Bool(n1_++),
-                 Bool(n2_++),
-                 Bool(n3_++),
-                 Bool(n4_++),
-                 Bool(n5_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED5(PredFunction5Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++),
+                     Bool(n4_++), Bool(n5_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED5 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED5Test, FunctorOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED5(PredFunctor5(),
-                 n1_++,
-                 n2_++,
-                 n3_++,
-                 n4_++,
-                 n5_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED5(PredFunctor5(), n1_++, n2_++, n3_++, n4_++, n5_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED5 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED5Test, FunctorOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED5(PredFunctor5(),
-                 Bool(n1_++),
-                 Bool(n2_++),
-                 Bool(n3_++),
-                 Bool(n4_++),
-                 Bool(n5_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED5(PredFunctor5(), Bool(n1_++), Bool(n2_++), Bool(n3_++),
+                     Bool(n4_++), Bool(n5_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a successful EXPECT_PRED_FORMAT5 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnBuiltInTypeSuccess) {
-  EXPECT_PRED_FORMAT5(PredFormatFunction5,
-                      ++n1_,
-                      ++n2_,
-                      ++n3_,
-                      ++n4_,
-                      ++n5_);
+  EXPECT_PRED_FORMAT5(PredFormatFunction5, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED_FORMAT5 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnUserTypeSuccess) {
-  EXPECT_PRED_FORMAT5(PredFormatFunction5,
-                      Bool(++n1_),
-                      Bool(++n2_),
-                      Bool(++n3_),
-                      Bool(++n4_),
-                      Bool(++n5_));
+  EXPECT_PRED_FORMAT5(PredFormatFunction5, Bool(++n1_), Bool(++n2_),
+                      Bool(++n3_), Bool(++n4_), Bool(++n5_));
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED_FORMAT5 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnBuiltInTypeSuccess) {
-  EXPECT_PRED_FORMAT5(PredFormatFunctor5(),
-                      ++n1_,
-                      ++n2_,
-                      ++n3_,
-                      ++n4_,
-                      ++n5_);
+  EXPECT_PRED_FORMAT5(PredFormatFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_);
   finished_ = true;
 }
 
 // Tests a successful EXPECT_PRED_FORMAT5 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnUserTypeSuccess) {
-  EXPECT_PRED_FORMAT5(PredFormatFunctor5(),
-                      Bool(++n1_),
-                      Bool(++n2_),
-                      Bool(++n3_),
-                      Bool(++n4_),
-                      Bool(++n5_));
+  EXPECT_PRED_FORMAT5(PredFormatFunctor5(), Bool(++n1_), Bool(++n2_),
+                      Bool(++n3_), Bool(++n4_), Bool(++n5_));
   finished_ = true;
 }
 
 // Tests a failed EXPECT_PRED_FORMAT5 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT5(PredFormatFunction5,
-                        n1_++,
-                        n2_++,
-                        n3_++,
-                        n4_++,
-                        n5_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT5(PredFormatFunction5, n1_++, n2_++, n3_++, n4_++,
+                            n5_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED_FORMAT5 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT5(PredFormatFunction5,
-                        Bool(n1_++),
-                        Bool(n2_++),
-                        Bool(n3_++),
-                        Bool(n4_++),
-                        Bool(n5_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT5(PredFormatFunction5, Bool(n1_++), Bool(n2_++),
+                            Bool(n3_++), Bool(n4_++), Bool(n5_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED_FORMAT5 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnBuiltInTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT5(PredFormatFunctor5(),
-                        n1_++,
-                        n2_++,
-                        n3_++,
-                        n4_++,
-                        n5_++);
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT5(PredFormatFunctor5(), n1_++, n2_++, n3_++, n4_++,
+                            n5_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed EXPECT_PRED_FORMAT5 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnUserTypeFailure) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT5(PredFormatFunctor5(),
-                        Bool(n1_++),
-                        Bool(n2_++),
-                        Bool(n3_++),
-                        Bool(n4_++),
-                        Bool(n5_++));
-    finished_ = true;
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT5(PredFormatFunctor5(), Bool(n1_++), Bool(n2_++),
+                            Bool(n3_++), Bool(n4_++), Bool(n5_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a successful ASSERT_PRED_FORMAT5 where the
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnBuiltInTypeSuccess) {
-  ASSERT_PRED_FORMAT5(PredFormatFunction5,
-                      ++n1_,
-                      ++n2_,
-                      ++n3_,
-                      ++n4_,
-                      ++n5_);
+  ASSERT_PRED_FORMAT5(PredFormatFunction5, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED_FORMAT5 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnUserTypeSuccess) {
-  ASSERT_PRED_FORMAT5(PredFormatFunction5,
-                      Bool(++n1_),
-                      Bool(++n2_),
-                      Bool(++n3_),
-                      Bool(++n4_),
-                      Bool(++n5_));
+  ASSERT_PRED_FORMAT5(PredFormatFunction5, Bool(++n1_), Bool(++n2_),
+                      Bool(++n3_), Bool(++n4_), Bool(++n5_));
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED_FORMAT5 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnBuiltInTypeSuccess) {
-  ASSERT_PRED_FORMAT5(PredFormatFunctor5(),
-                      ++n1_,
-                      ++n2_,
-                      ++n3_,
-                      ++n4_,
-                      ++n5_);
+  ASSERT_PRED_FORMAT5(PredFormatFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_);
   finished_ = true;
 }
 
 // Tests a successful ASSERT_PRED_FORMAT5 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnUserTypeSuccess) {
-  ASSERT_PRED_FORMAT5(PredFormatFunctor5(),
-                      Bool(++n1_),
-                      Bool(++n2_),
-                      Bool(++n3_),
-                      Bool(++n4_),
-                      Bool(++n5_));
+  ASSERT_PRED_FORMAT5(PredFormatFunctor5(), Bool(++n1_), Bool(++n2_),
+                      Bool(++n3_), Bool(++n4_), Bool(++n5_));
   finished_ = true;
 }
 
@@ -2365,58 +2020,50 @@ TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnUserTypeSuccess) {
 // predicate-formatter is a function on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT5(PredFormatFunction5,
-                        n1_++,
-                        n2_++,
-                        n3_++,
-                        n4_++,
-                        n5_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT5(PredFormatFunction5, n1_++, n2_++, n3_++, n4_++,
+                            n5_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED_FORMAT5 where the
 // predicate-formatter is a function on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT5(PredFormatFunction5,
-                        Bool(n1_++),
-                        Bool(n2_++),
-                        Bool(n3_++),
-                        Bool(n4_++),
-                        Bool(n5_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT5(PredFormatFunction5, Bool(n1_++), Bool(n2_++),
+                            Bool(n3_++), Bool(n4_++), Bool(n5_++));
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED_FORMAT5 where the
 // predicate-formatter is a functor on a built-in type (int).
 TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnBuiltInTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT5(PredFormatFunctor5(),
-                        n1_++,
-                        n2_++,
-                        n3_++,
-                        n4_++,
-                        n5_++);
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT5(PredFormatFunctor5(), n1_++, n2_++, n3_++, n4_++,
+                            n5_++);
+        finished_ = true;
+      },
+      "");
 }
 
 // Tests a failed ASSERT_PRED_FORMAT5 where the
 // predicate-formatter is a functor on a user-defined type (Bool).
 TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnUserTypeFailure) {
   expected_to_finish_ = false;
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT5(PredFormatFunctor5(),
-                        Bool(n1_++),
-                        Bool(n2_++),
-                        Bool(n3_++),
-                        Bool(n4_++),
-                        Bool(n5_++));
-    finished_ = true;
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT5(PredFormatFunctor5(), Bool(n1_++), Bool(n2_++),
+                            Bool(n3_++), Bool(n4_++), Bool(n5_++));
+        finished_ = true;
+      },
+      "");
 }
index 1d1187eff006cc88750ef957829d580ac690350b..1a0c5ea4f0d31ae34f8149eae3e739f601347a8c 100644 (file)
@@ -81,15 +81,17 @@ TEST_F(PrematureExitDeathTest, FileExistsDuringExecutionOfDeathTest) {
     return;
   }
 
-  EXPECT_DEATH_IF_SUPPORTED({
-      // If the file exists, crash the process such that the main test
-      // process will catch the (expected) crash and report a success;
-      // otherwise don't crash, which will cause the main test process
-      // to report that the death test has failed.
-      if (PrematureExitFileExists()) {
-        exit(1);
-      }
-    }, "");
+  EXPECT_DEATH_IF_SUPPORTED(
+      {
+        // If the file exists, crash the process such that the main test
+        // process will catch the (expected) crash and report a success;
+        // otherwise don't crash, which will cause the main test process
+        // to report that the death test has failed.
+        if (PrematureExitFileExists()) {
+          exit(1);
+        }
+      },
+      "");
 }
 
 // Tests that the premature-exit file exists during the execution of a
@@ -106,7 +108,7 @@ TEST_F(PrematureExitTest, PrematureExitFileExistsDuringTestExecution) {
 
 }  // namespace
 
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
   InitGoogleTest(&argc, argv);
   const int exit_code = RUN_ALL_TESTS();
 
index 7da4a15ea141989f86426a572bac0a58b33f76ba..73fb8dc906a97ec505fbc27f3ea7111ed101c0ff 100644 (file)
 // (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 --gtest_repeat=number flag.
 
 #include <stdlib.h>
+
 #include <iostream>
+
 #include "gtest/gtest.h"
 #include "src/gtest-internal-inl.h"
 
-namespace testing {
-
-GTEST_DECLARE_string_(death_test_style);
-GTEST_DECLARE_string_(filter);
-GTEST_DECLARE_int32_(repeat);
-
-}  // namespace testing
-
-using testing::GTEST_FLAG(death_test_style);
-using testing::GTEST_FLAG(filter);
-using testing::GTEST_FLAG(repeat);
-
 namespace {
 
 // We need this when we are testing Google Test itself and therefore
 // cannot use Google Test assertions.
-#define GTEST_CHECK_INT_EQ_(expected, actual) \
-  do {\
-    const int expected_val = (expected);\
-    const int actual_val = (actual);\
-    if (::testing::internal::IsTrue(expected_val != actual_val)) {\
-      ::std::cout << "Value of: " #actual "\n"\
-                  << "  Actual: " << actual_val << "\n"\
-                  << "Expected: " #expected "\n"\
-                  << "Which is: " << expected_val << "\n";\
-      ::testing::internal::posix::Abort();\
-    }\
+#define GTEST_CHECK_INT_EQ_(expected, actual)                      \
+  do {                                                             \
+    const int expected_val = (expected);                           \
+    const int actual_val = (actual);                               \
+    if (::testing::internal::IsTrue(expected_val != actual_val)) { \
+      ::std::cout << "Value of: " #actual "\n"                     \
+                  << "  Actual: " << actual_val << "\n"            \
+                  << "Expected: " #expected "\n"                   \
+                  << "Which is: " << expected_val << "\n";         \
+      ::testing::internal::posix::Abort();                         \
+    }                                                              \
   } while (::testing::internal::AlwaysFalse())
 
-
 // Used for verifying that global environment set-up and tear-down are
 // inside the --gtest_repeat loop.
 
@@ -91,9 +79,7 @@ TEST(FooTest, ShouldFail) {
 
 int g_should_pass_count = 0;
 
-TEST(FooTest, ShouldPass) {
-  g_should_pass_count++;
-}
+TEST(FooTest, ShouldPass) { g_should_pass_count++; }
 
 // A test that contains a thread-safe death test and a fast death
 // test.  It should pass.
@@ -103,10 +89,10 @@ int g_death_test_count = 0;
 TEST(BarDeathTest, ThreadSafeAndFast) {
   g_death_test_count++;
 
-  GTEST_FLAG(death_test_style) = "threadsafe";
+  GTEST_FLAG_SET(death_test_style, "threadsafe");
   EXPECT_DEATH_IF_SUPPORTED(::testing::internal::posix::Abort(), "");
 
-  GTEST_FLAG(death_test_style) = "fast";
+  GTEST_FLAG_SET(death_test_style, "fast");
   EXPECT_DEATH_IF_SUPPORTED(::testing::internal::posix::Abort(), "");
 }
 
@@ -120,8 +106,7 @@ TEST_P(MyParamTest, ShouldPass) {
   GTEST_CHECK_INT_EQ_(g_param_test_count % kNumberOfParamTests, GetParam());
   g_param_test_count++;
 }
-INSTANTIATE_TEST_SUITE_P(MyParamSequence,
-                         MyParamTest,
+INSTANTIATE_TEST_SUITE_P(MyParamSequence, MyParamTest,
                          testing::Range(0, kNumberOfParamTests));
 
 // Resets the count for each test.
@@ -153,7 +138,8 @@ void TestRepeatUnspecified() {
 
 // Tests the behavior of Google Test when --gtest_repeat has the given value.
 void TestRepeat(int repeat) {
-  GTEST_FLAG(repeat) = repeat;
+  GTEST_FLAG_SET(repeat, repeat);
+  GTEST_FLAG_SET(recreate_environments_when_repeating, true);
 
   ResetCounts();
   GTEST_CHECK_INT_EQ_(repeat > 0 ? 1 : 0, RUN_ALL_TESTS());
@@ -163,8 +149,9 @@ void TestRepeat(int repeat) {
 // Tests using --gtest_repeat when --gtest_filter specifies an empty
 // set of tests.
 void TestRepeatWithEmptyFilter(int repeat) {
-  GTEST_FLAG(repeat) = repeat;
-  GTEST_FLAG(filter) = "None";
+  GTEST_FLAG_SET(repeat, repeat);
+  GTEST_FLAG_SET(recreate_environments_when_repeating, true);
+  GTEST_FLAG_SET(filter, "None");
 
   ResetCounts();
   GTEST_CHECK_INT_EQ_(0, RUN_ALL_TESTS());
@@ -174,8 +161,9 @@ void TestRepeatWithEmptyFilter(int repeat) {
 // Tests using --gtest_repeat when --gtest_filter specifies a set of
 // successful tests.
 void TestRepeatWithFilterForSuccessfulTests(int repeat) {
-  GTEST_FLAG(repeat) = repeat;
-  GTEST_FLAG(filter) = "*-*ShouldFail";
+  GTEST_FLAG_SET(repeat, repeat);
+  GTEST_FLAG_SET(recreate_environments_when_repeating, true);
+  GTEST_FLAG_SET(filter, "*-*ShouldFail");
 
   ResetCounts();
   GTEST_CHECK_INT_EQ_(0, RUN_ALL_TESTS());
@@ -190,8 +178,9 @@ void TestRepeatWithFilterForSuccessfulTests(int repeat) {
 // Tests using --gtest_repeat when --gtest_filter specifies a set of
 // failed tests.
 void TestRepeatWithFilterForFailedTests(int repeat) {
-  GTEST_FLAG(repeat) = repeat;
-  GTEST_FLAG(filter) = "*ShouldFail";
+  GTEST_FLAG_SET(repeat, repeat);
+  GTEST_FLAG_SET(recreate_environments_when_repeating, true);
+  GTEST_FLAG_SET(filter, "*ShouldFail");
 
   ResetCounts();
   GTEST_CHECK_INT_EQ_(1, RUN_ALL_TESTS());
index 14e63ab897d9628c671c9364b1f3391703268569..1c87b44f01578df083f5c846126f9d8e7472640d 100755 (executable)
@@ -35,7 +35,7 @@ output.
 
 import re
 
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 # Path to the gtest_skip_in_environment_setup_test binary
 EXE_PATH = gtest_test_utils.GetTestExecutablePath('gtest_skip_test')
index 6e791556aa71e5623a357af822713b4df2176403..6960b11a586650fff717687779ea3e85bd56f6b0 100755 (executable)
@@ -33,7 +33,7 @@ This script invokes gtest_skip_in_environment_setup_test_ and verifies its
 output.
 """
 
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 # Path to the gtest_skip_in_environment_setup_test binary
 EXE_PATH = gtest_test_utils.GetTestExecutablePath(
index 937231063816e047acdd2fb416da80e4986438be..5f21c27dcdbd67721439d66168608c89a6aecad4 100644 (file)
@@ -31,6 +31,7 @@
 // testcases being skipped.
 
 #include <iostream>
+
 #include "gtest/gtest.h"
 
 class SetupEnvironment : public testing::Environment {
index 4a23004cca36814ec3bf7e0c124444ad64770c58..e1b8d655adae34648bc4cfbcf1a2fa29bc161642 100644 (file)
@@ -46,10 +46,6 @@ class Fixture : public Test {
   }
 };
 
-TEST_F(Fixture, SkipsOneTest) {
-  EXPECT_EQ(5, 7);
-}
+TEST_F(Fixture, SkipsOneTest) { EXPECT_EQ(5, 7); }
 
-TEST_F(Fixture, SkipsAnotherTest) {
-  EXPECT_EQ(99, 100);
-}
+TEST_F(Fixture, SkipsAnotherTest) { EXPECT_EQ(99, 100); }
index 1d94ac6b3ad9f9f7dbadbfb2bf749b8271560dac..e8e22a83c58ca6f9bfcb1f1c84b4c00daabc4759 100644 (file)
@@ -35,9 +35,7 @@
 
 namespace {
 
-void Subroutine() {
-  EXPECT_EQ(42, 42);
-}
+void Subroutine() { EXPECT_EQ(42, 42); }
 
 TEST(NoFatalFailureTest, ExpectNoFatalFailure) {
   EXPECT_NO_FATAL_FAILURE(;);
index 843481910f03f6989773c586b8e11eddbd6034cb..24b173ffd884c4044ea10a180d8ba16104622215 100644 (file)
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-
 // Tests that SCOPED_TRACE() and various Google Test assertions can be
 // used in a large number of threads concurrently.
 
-#include "gtest/gtest.h"
-
 #include <vector>
 
+#include "gtest/gtest.h"
 #include "src/gtest-internal-inl.h"
 
 #if GTEST_IS_THREADSAFE
@@ -66,8 +64,7 @@ std::string IdToString(int id) {
 }
 
 void ExpectKeyAndValueWereRecordedForId(
-    const std::vector<TestProperty>& properties,
-    int id, const char* suffix) {
+    const std::vector<TestProperty>& properties, int id, const char* suffix) {
   TestPropertyKeyIs matches_key(IdToKey(id, suffix).c_str());
   const std::vector<TestProperty>::const_iterator property =
       std::find_if(properties.begin(), properties.end(), matches_key);
@@ -121,15 +118,13 @@ TEST(StressTest, CanUseScopedTraceAndAssertionsInManyThreads) {
     std::unique_ptr<ThreadWithParam<int> > threads[kThreadCount];
     Notification threads_can_start;
     for (int i = 0; i != kThreadCount; i++)
-      threads[i].reset(new ThreadWithParam<int>(&ManyAsserts,
-                                                i,
-                                                &threads_can_start));
+      threads[i].reset(
+          new ThreadWithParam<int>(&ManyAsserts, i, &threads_can_start));
 
     threads_can_start.Notify();
 
     // Blocks until all the threads are done.
-    for (int i = 0; i != kThreadCount; i++)
-      threads[i]->Join();
+    for (int i = 0; i != kThreadCount; i++) threads[i]->Join();
   }
 
   // Ensures that kThreadCount*kThreadCount failures have been reported.
@@ -149,7 +144,7 @@ TEST(StressTest, CanUseScopedTraceAndAssertionsInManyThreads) {
     ExpectKeyAndValueWereRecordedForId(properties, i, "string");
     ExpectKeyAndValueWereRecordedForId(properties, i, "int");
   }
-  CheckTestFailureCount(kThreadCount*kThreadCount);
+  CheckTestFailureCount(kThreadCount * kThreadCount);
 }
 
 void FailingThread(bool is_fatal) {
@@ -196,8 +191,8 @@ TEST(FatalFailureTest, ExpectFatalFailureIgnoresFailuresInOtherThreads) {
 TEST(FatalFailureOnAllThreadsTest, ExpectFatalFailureOnAllThreads) {
   // This statement should succeed, because failures in all threads are
   // considered.
-  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(
-      GenerateFatalFailureInAnotherThread(true), "expected");
+  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(GenerateFatalFailureInAnotherThread(true),
+                                      "expected");
   CheckTestFailureCount(0);
   // We need to add a failure, because main() checks that there are failures.
   // But when only this test is run, we shouldn't have any failures.
@@ -226,7 +221,7 @@ TEST(NonFatalFailureOnAllThreadsTest, ExpectNonFatalFailureOnAllThreads) {
 }  // namespace
 }  // namespace testing
 
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
   testing::InitGoogleTest(&argc, argv);
 
   const int result = RUN_ALL_TESTS();  // Expected to fail.
@@ -238,8 +233,7 @@ int main(int argc, char **argv) {
 
 #else
 TEST(StressTest,
-     DISABLED_ThreadSafetyTestsAreSkippedWhenGoogleTestIsNotThreadSafe) {
-}
+     DISABLED_ThreadSafetyTestsAreSkippedWhenGoogleTestIsNotThreadSafe) {}
 
 int main(int argc, char **argv) {
   testing::InitGoogleTest(&argc, argv);
index a48db05012cc30e0edf4a1354ff392c92d000bf0..45f368b3a5e3ced287beacfb1ba70e95a8f0f0b3 100644 (file)
 
 // 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, 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)
+  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)
+  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.
index d0c24466a4b7e3e623b5af495b8e26eaa8a9c864..eecc53346c277085ebae99e132dca3181b725296 100755 (executable)
@@ -32,6 +32,7 @@
 # pylint: disable-msg=C6204
 
 import os
+import subprocess
 import sys
 
 IS_WINDOWS = os.name == 'nt'
@@ -42,13 +43,6 @@ import atexit
 import shutil
 import tempfile
 import unittest as _test_module
-
-try:
-  import subprocess
-  _SUBPROCESS_MODULE_AVAILABLE = True
-except:
-  import popen2
-  _SUBPROCESS_MODULE_AVAILABLE = False
 # pylint: enable-msg=C6204
 
 GTEST_OUTPUT_VAR_NAME = 'GTEST_OUTPUT'
@@ -173,7 +167,7 @@ def GetTestExecutablePath(executable_name, build_dir=None):
         'Unable to find the test binary "%s". Please make sure to provide\n'
         'a path to the binary via the --build_dir flag or the BUILD_DIR\n'
         'environment variable.' % path)
-    print >> sys.stderr, message
+    print(message, file=sys.stderr)
     sys.exit(1)
 
   return path
@@ -224,69 +218,18 @@ class Subprocess:
                                combined in a string.
     """
 
-    # The subprocess module is the preferrable way of running programs
-    # since it is available and behaves consistently on all platforms,
-    # including Windows. But it is only available starting in python 2.4.
-    # In earlier python versions, we revert to the popen2 module, which is
-    # available in python 2.0 and later but doesn't provide required
-    # functionality (Popen4) under Windows. This allows us to support Mac
-    # OS X 10.4 Tiger, which has python 2.3 installed.
-    if _SUBPROCESS_MODULE_AVAILABLE:
-      if capture_stderr:
-        stderr = subprocess.STDOUT
-      else:
-        stderr = subprocess.PIPE
-
-      p = subprocess.Popen(command,
-                           stdout=subprocess.PIPE, stderr=stderr,
-                           cwd=working_dir, universal_newlines=True, env=env)
-      # communicate returns a tuple with the file object for the child's
-      # output.
-      self.output = p.communicate()[0]
-      self._return_code = p.returncode
+    if capture_stderr:
+      stderr = subprocess.STDOUT
     else:
-      old_dir = os.getcwd()
-
-      def _ReplaceEnvDict(dest, src):
-        # Changes made by os.environ.clear are not inheritable by child
-        # processes until Python 2.6. To produce inheritable changes we have
-        # to delete environment items with the del statement.
-        for key in dest.keys():
-          del dest[key]
-        dest.update(src)
-
-      # When 'env' is not None, backup the environment variables and replace
-      # them with the passed 'env'. When 'env' is None, we simply use the
-      # current 'os.environ' for compatibility with the subprocess.Popen
-      # semantics used above.
-      if env is not None:
-        old_environ = os.environ.copy()
-        _ReplaceEnvDict(os.environ, env)
-
-      try:
-        if working_dir is not None:
-          os.chdir(working_dir)
-        if capture_stderr:
-          p = popen2.Popen4(command)
-        else:
-          p = popen2.Popen3(command)
-        p.tochild.close()
-        self.output = p.fromchild.read()
-        ret_code = p.wait()
-      finally:
-        os.chdir(old_dir)
-
-        # Restore the old environment variables
-        # if they were replaced.
-        if env is not None:
-          _ReplaceEnvDict(os.environ, old_environ)
-
-      # Converts ret_code to match the semantics of
-      # subprocess.Popen.returncode.
-      if os.WIFSIGNALED(ret_code):
-        self._return_code = -os.WTERMSIG(ret_code)
-      else:  # os.WIFEXITED(ret_code) should return True here.
-        self._return_code = os.WEXITSTATUS(ret_code)
+      stderr = subprocess.PIPE
+
+    p = subprocess.Popen(command,
+                         stdout=subprocess.PIPE, stderr=stderr,
+                         cwd=working_dir, universal_newlines=True, env=env)
+    # communicate returns a tuple with the file object for the child's
+    # output.
+    self.output = p.communicate()[0]
+    self._return_code = p.returncode
 
     if bool(self._return_code & 0x80000000):
       self.terminated_by_signal = True
index 87ffad73d40065298f30500de824d808b6571d8d..1c2a303a8887a5c2904044807958c18cba675be4 100755 (executable)
@@ -31,7 +31,7 @@
 
 import os
 
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 binary_name = 'gtest_testbridge_test_'
 COMMAND = gtest_test_utils.GetTestExecutablePath(binary_name)
index 24617b209e10a9d1798368e26465aaa62715f0ee..c2c000dca50d07b065e3b24d2aa6738e6e9af98f 100644 (file)
@@ -27,7 +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.
 
-
 // This program is meant to be run by gtest_test_filter_test.py.  Do not run
 // it directly.
 
index 1d95adbf537ba9178163987c0d3e0c8aa03ab5ee..25d7c797ed4c249da9e471c940178234ddaa1dd5 100644 (file)
 // (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 throw-on-failure mode with exceptions enabled.
 
-#include "gtest/gtest.h"
-
-#include <stdlib.h>
 #include <stdio.h>
+#include <stdlib.h>
 #include <string.h>
+
 #include <stdexcept>
 
+#include "gtest/gtest.h"
+
 // 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
@@ -50,19 +50,19 @@ void Fail(const char* msg) {
 // Tests that an assertion failure throws a subclass of
 // std::runtime_error.
 void TestFailureThrowsRuntimeError() {
-  testing::GTEST_FLAG(throw_on_failure) = true;
+  GTEST_FLAG_SET(throw_on_failure, true);
 
   // A successful assertion shouldn't throw.
   try {
     EXPECT_EQ(3, 3);
-  } catch(...) {
+  } catch (...) {
     Fail("A successful assertion wrongfully threw.");
   }
 
   // A failed assertion should throw a subclass of std::runtime_error.
   try {
     EXPECT_EQ(2, 3) << "Expected failure";
-  } catch(const std::runtime_error& e) {
+  } catch (const std::runtime_error& e) {
     if (strstr(e.what(), "Expected failure") != nullptr) return;
 
     printf("%s",
@@ -70,7 +70,7 @@ void TestFailureThrowsRuntimeError() {
            "but the message is incorrect.  Instead of containing \"Expected "
            "failure\", it is:\n");
     Fail(e.what());
-  } catch(...) {
+  } catch (...) {
     Fail("A failed assertion threw the wrong type of exception.");
   }
   Fail("A failed assertion should've thrown but didn't.");
index 1730e8b8c9c9b742b5dcfd1f5055b2f232d483dd..cdfdc6c42f2be93257c55853949f6ac30ae7d545 100644 (file)
 // 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) ||
-               testing::GTEST_FLAG(catch_exceptions) ||
-               testing::GTEST_FLAG(color) != "unknown" ||
-               testing::GTEST_FLAG(fail_fast) ||
-               testing::GTEST_FLAG(filter) != "unknown" ||
-               testing::GTEST_FLAG(list_tests) ||
-               testing::GTEST_FLAG(output) != "unknown" ||
-               testing::GTEST_FLAG(brief) || testing::GTEST_FLAG(print_time) ||
-               testing::GTEST_FLAG(random_seed) ||
-               testing::GTEST_FLAG(repeat) > 0 ||
-               testing::GTEST_FLAG(show_internal_stack_frames) ||
-               testing::GTEST_FLAG(shuffle) ||
-               testing::GTEST_FLAG(stack_trace_depth) > 0 ||
-               testing::GTEST_FLAG(stream_result_to) != "unknown" ||
-               testing::GTEST_FLAG(throw_on_failure);
+  bool dummy =
+      GTEST_FLAG_GET(also_run_disabled_tests) ||
+      GTEST_FLAG_GET(break_on_failure) || GTEST_FLAG_GET(catch_exceptions) ||
+      GTEST_FLAG_GET(color) != "unknown" || GTEST_FLAG_GET(fail_fast) ||
+      GTEST_FLAG_GET(filter) != "unknown" || GTEST_FLAG_GET(list_tests) ||
+      GTEST_FLAG_GET(output) != "unknown" || GTEST_FLAG_GET(brief) ||
+      GTEST_FLAG_GET(print_time) || GTEST_FLAG_GET(random_seed) ||
+      GTEST_FLAG_GET(repeat) > 0 ||
+      GTEST_FLAG_GET(recreate_environments_when_repeating) ||
+      GTEST_FLAG_GET(show_internal_stack_frames) || GTEST_FLAG_GET(shuffle) ||
+      GTEST_FLAG_GET(stack_trace_depth) > 0 ||
+      GTEST_FLAG_GET(stream_result_to) != "unknown" ||
+      GTEST_FLAG_GET(throw_on_failure);
   EXPECT_TRUE(dummy || !dummy);  // Suppresses warning that dummy is unused.
 }
 
@@ -114,15 +111,15 @@ TEST_F(StreamingListenerTest, OnTestIterationEnd) {
   EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
 }
 
-TEST_F(StreamingListenerTest, OnTestCaseStart) {
+TEST_F(StreamingListenerTest, OnTestSuiteStart) {
   *output() = "";
-  streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", nullptr, nullptr));
+  streamer_.OnTestSuiteStart(TestSuite("FooTest", "Bar", nullptr, nullptr));
   EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
 }
 
-TEST_F(StreamingListenerTest, OnTestCaseEnd) {
+TEST_F(StreamingListenerTest, OnTestSuiteEnd) {
   *output() = "";
-  streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", nullptr, nullptr));
+  streamer_.OnTestSuiteEnd(TestSuite("FooTest", "Bar", nullptr, nullptr));
   EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
 }
 
@@ -140,8 +137,8 @@ TEST_F(StreamingListenerTest, OnTestEnd) {
 
 TEST_F(StreamingListenerTest, OnTestPartResult) {
   *output() = "";
-  streamer_.OnTestPartResult(TestPartResult(
-      TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%"));
+  streamer_.OnTestPartResult(TestPartResult(TestPartResult::kFatalFailure,
+                                            "foo.cc", 42, "failed=\n&%"));
 
   // Meta characters in the failure message should be properly escaped.
   EXPECT_EQ(
@@ -199,24 +196,6 @@ using testing::DoubleLE;
 using testing::EmptyTestEventListener;
 using testing::Environment;
 using testing::FloatLE;
-using testing::GTEST_FLAG(also_run_disabled_tests);
-using testing::GTEST_FLAG(break_on_failure);
-using testing::GTEST_FLAG(catch_exceptions);
-using testing::GTEST_FLAG(color);
-using testing::GTEST_FLAG(death_test_use_fork);
-using testing::GTEST_FLAG(fail_fast);
-using testing::GTEST_FLAG(filter);
-using testing::GTEST_FLAG(list_tests);
-using testing::GTEST_FLAG(output);
-using testing::GTEST_FLAG(brief);
-using testing::GTEST_FLAG(print_time);
-using testing::GTEST_FLAG(random_seed);
-using testing::GTEST_FLAG(repeat);
-using testing::GTEST_FLAG(show_internal_stack_frames);
-using testing::GTEST_FLAG(shuffle);
-using testing::GTEST_FLAG(stack_trace_depth);
-using testing::GTEST_FLAG(stream_result_to);
-using testing::GTEST_FLAG(throw_on_failure);
 using testing::IsNotSubstring;
 using testing::IsSubstring;
 using testing::kMaxStackTraceDepth;
@@ -265,7 +244,7 @@ using testing::internal::kTestTypeIdInGoogleTest;
 using testing::internal::NativeArray;
 using testing::internal::OsStackTraceGetter;
 using testing::internal::OsStackTraceGetterInterface;
-using testing::internal::ParseInt32Flag;
+using testing::internal::ParseFlag;
 using testing::internal::RelationToSourceCopy;
 using testing::internal::RelationToSourceReference;
 using testing::internal::ShouldRunTestOnShard;
@@ -293,11 +272,9 @@ using testing::internal::GetCapturedStdout;
 using testing::internal::ThreadWithParam;
 #endif
 
-class TestingVector : public std::vector<int> {
-};
+class TestingVector : public std::vector<int> {};
 
-::std::ostream& operator<<(::std::ostream& os,
-                           const TestingVector& vector) {
+::std::ostream& operator<<(::std::ostream& os, const TestingVector& vector) {
   os << "{ ";
   for (size_t i = 0; i < vector.size(); i++) {
     os << vector[i] << " ";
@@ -425,7 +402,7 @@ TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
 
 // Tests FormatEpochTimeInMillisAsIso8601().  The correctness of conversion
 // for particular dates below was verified in Python using
-// datetime.datetime.fromutctimestamp(<timetamp>/1000).
+// datetime.datetime.fromutctimestamp(<timestamp>/1000).
 
 // FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
 // have to set up a particular timezone to obtain predictable results.
@@ -441,8 +418,7 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test {
     saved_tz_ = nullptr;
 
     GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */)
-    if (getenv("TZ"))
-      saved_tz_ = strdup(getenv("TZ"));
+    if (getenv("TZ")) saved_tz_ = strdup(getenv("TZ"));
     GTEST_DISABLE_MSC_DEPRECATED_POP_()
 
     // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use.  We
@@ -471,6 +447,12 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test {
     tzset();
     GTEST_DISABLE_MSC_WARNINGS_POP_()
 #else
+#if GTEST_OS_LINUX_ANDROID && __ANDROID_API__ < 21
+    // Work around KitKat bug in tzset by setting "UTC" before setting "UTC+00".
+    // See https://github.com/android/ndk/issues/1604.
+    setenv("TZ", "UTC", 1);
+    tzset();
+#endif
     if (time_zone) {
       setenv(("TZ"), time_zone, 1);
     } else {
@@ -491,9 +473,8 @@ TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
 }
 
 TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) {
-  EXPECT_EQ(
-      "2011-10-31T18:52:42.234",
-      FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
+  EXPECT_EQ("2011-10-31T18:52:42.234",
+            FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
 }
 
 TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
@@ -510,10 +491,10 @@ TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
   EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0));
 }
 
-# ifdef __BORLANDC__
+#ifdef __BORLANDC__
 // Silences warnings: "Condition is always true", "Unreachable code"
-#  pragma option push -w-ccc -w-rch
-# endif
+#pragma option push -w-ccc -w-rch
+#endif
 
 // Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal
 // when the RHS is a pointer type.
@@ -587,10 +568,10 @@ TEST(NullLiteralTest, NoConversionNoWarning) {
 #pragma clang diagnostic pop
 #endif
 
-# ifdef __BORLANDC__
+#ifdef __BORLANDC__
 // Restores warnings after previous "#pragma option push" suppressed them.
-#  pragma option pop
-# endif
+#pragma option pop
+#endif
 
 //
 // Tests CodePointToUtf8().
@@ -618,20 +599,17 @@ TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
   // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
   // 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)));
+  EXPECT_EQ("\xD5\xB6", CodePointToUtf8(static_cast<wchar_t>(0x576)));
 }
 
 // Tests that Unicode code-points that have 12 to 16 bits are encoded
 // as 1110xxxx 10xxxxxx 10xxxxxx.
 TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
   // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
-  EXPECT_EQ("\xE0\xA3\x93",
-            CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
+  EXPECT_EQ("\xE0\xA3\x93", CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
 
   // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
-  EXPECT_EQ("\xEC\x9D\x8D",
-            CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
+  EXPECT_EQ("\xEC\x9D\x8D", CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
 }
 
 #if !GTEST_WIDE_STRING_USES_UTF16_
@@ -683,7 +661,7 @@ TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
   EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
 
   // 101 0111 0110 => 110-10101 10-110110
-  const wchar_t s[] = { 0x576, '\0' };
+  const wchar_t s[] = {0x576, '\0'};
   EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
   EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
 }
@@ -692,12 +670,12 @@ TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
 // as 1110xxxx 10xxxxxx 10xxxxxx.
 TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
   // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
-  const wchar_t s1[] = { 0x8D3, '\0' };
+  const wchar_t s1[] = {0x8D3, '\0'};
   EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
   EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
 
   // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
-  const wchar_t s2[] = { 0xC74D, '\0' };
+  const wchar_t s2[] = {0xC74D, '\0'};
   EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
   EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
 }
@@ -732,11 +710,11 @@ TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
   EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
                WideStringToUtf8(L"\xABCDFF", -1).c_str());
 }
-#else  // !GTEST_WIDE_STRING_USES_UTF16_
+#else   // !GTEST_WIDE_STRING_USES_UTF16_
 // Tests that surrogate pairs are encoded correctly on the systems using
 // UTF-16 encoding in the wide strings.
 TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
-  const wchar_t s[] = { 0xD801, 0xDC00, '\0' };
+  const wchar_t s[] = {0xD801, 0xDC00, '\0'};
   EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
 }
 
@@ -744,13 +722,13 @@ TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
 // generates the expected result.
 TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
   // Leading surrogate is at the end of the string.
-  const wchar_t s1[] = { 0xD800, '\0' };
+  const wchar_t s1[] = {0xD800, '\0'};
   EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
   // Leading surrogate is not followed by the trailing surrogate.
-  const wchar_t s2[] = { 0xD800, 'M', '\0' };
+  const wchar_t s2[] = {0xD800, 'M', '\0'};
   EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
   // Trailing surrogate appearas without a leading surrogate.
-  const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' };
+  const wchar_t s3[] = {0xDC00, 'P', 'Q', 'R', '\0'};
   EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
 }
 #endif  // !GTEST_WIDE_STRING_USES_UTF16_
@@ -758,21 +736,24 @@ TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
 // Tests that codepoint concatenation works correctly.
 #if !GTEST_WIDE_STRING_USES_UTF16_
 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
-  const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
+  const wchar_t s[] = {0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
   EXPECT_STREQ(
       "\xF4\x88\x98\xB4"
-          "\xEC\x9D\x8D"
-          "\n"
-          "\xD5\xB6"
-          "\xE0\xA3\x93"
-          "\xF4\x88\x98\xB4",
+      "\xEC\x9D\x8D"
+      "\n"
+      "\xD5\xB6"
+      "\xE0\xA3\x93"
+      "\xF4\x88\x98\xB4",
       WideStringToUtf8(s, -1).c_str());
 }
 #else
 TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
-  const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'};
+  const wchar_t s[] = {0xC74D, '\n', 0x576, 0x8D3, '\0'};
   EXPECT_STREQ(
-      "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
+      "\xEC\x9D\x8D"
+      "\n"
+      "\xD5\xB6"
+      "\xE0\xA3\x93",
       WideStringToUtf8(s, -1).c_str());
 }
 #endif  // !GTEST_WIDE_STRING_USES_UTF16_
@@ -781,9 +762,8 @@ TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
 
 TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
   testing::internal::Random random(42);
-  EXPECT_DEATH_IF_SUPPORTED(
-      random.Generate(0),
-      "Cannot generate a number in the range \\[0, 0\\)");
+  EXPECT_DEATH_IF_SUPPORTED(random.Generate(0),
+                            "Cannot generate a number in the range \\[0, 0\\)");
   EXPECT_DEATH_IF_SUPPORTED(
       random.Generate(testing::internal::Random::kMaxRange + 1),
       "Generation of a number in \\[0, 2147483649\\) was requested, "
@@ -912,7 +892,7 @@ class VectorShuffleTest : public Test {
       return true;
     }
 
-    bool found_in_vector[kVectorSize] = { false };
+    bool found_in_vector[kVectorSize] = {false};
     for (size_t i = 0; i < vector.size(); i++) {
       const int e = vector[i];
       if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) {
@@ -939,8 +919,8 @@ class VectorShuffleTest : public Test {
     return false;
   }
 
-  static bool RangeIsUnshuffled(
-      const TestingVector& vector, int begin, int end) {
+  static bool RangeIsUnshuffled(const TestingVector& vector, int begin,
+                                int end) {
     return !RangeIsShuffled(vector, begin, end);
   }
 
@@ -965,7 +945,7 @@ TEST_F(VectorShuffleTest, HandlesEmptyRange) {
   ASSERT_PRED1(VectorIsUnshuffled, vector_);
 
   // ...in the middle...
-  ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
+  ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2, &vector_);
   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
   ASSERT_PRED1(VectorIsUnshuffled, vector_);
 
@@ -987,7 +967,7 @@ TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
   ASSERT_PRED1(VectorIsUnshuffled, vector_);
 
   // ...in the middle...
-  ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
+  ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2 + 1, &vector_);
   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
   ASSERT_PRED1(VectorIsUnshuffled, vector_);
 
@@ -1012,7 +992,7 @@ TEST_F(VectorShuffleTest, ShufflesEntireVector) {
 }
 
 TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
-  const int kRangeSize = kVectorSize/2;
+  const int kRangeSize = kVectorSize / 2;
 
   ShuffleRange(&random_, 0, kRangeSize, &vector_);
 
@@ -1034,11 +1014,11 @@ TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
 
 TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
   const int kRangeSize = static_cast<int>(kVectorSize) / 3;
-  ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
+  ShuffleRange(&random_, kRangeSize, 2 * kRangeSize, &vector_);
 
   ASSERT_PRED1(VectorIsNotCorrupt, vector_);
   EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
-  EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
+  EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2 * kRangeSize);
   EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize,
                static_cast<int>(kVectorSize));
 }
@@ -1103,13 +1083,12 @@ TEST(StringTest, CaseInsensitiveWideCStringEquals) {
 
 // Tests String::ShowWideCString().
 TEST(StringTest, ShowWideCString) {
-  EXPECT_STREQ("(null)",
-               String::ShowWideCString(NULL).c_str());
+  EXPECT_STREQ("(null)", String::ShowWideCString(NULL).c_str());
   EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
   EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
 }
 
-# if GTEST_OS_WINDOWS_MOBILE
+#if GTEST_OS_WINDOWS_MOBILE
 TEST(StringTest, AnsiAndUtf16Null) {
   EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
   EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
@@ -1118,21 +1097,21 @@ TEST(StringTest, AnsiAndUtf16Null) {
 TEST(StringTest, AnsiAndUtf16ConvertBasic) {
   const char* ansi = String::Utf16ToAnsi(L"str");
   EXPECT_STREQ("str", ansi);
-  delete [] ansi;
+  delete[] ansi;
   const WCHAR* utf16 = String::AnsiToUtf16("str");
   EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
-  delete [] utf16;
+  delete[] utf16;
 }
 
 TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
   const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
   EXPECT_STREQ(".:\\ \"*?", ansi);
-  delete [] ansi;
+  delete[] ansi;
   const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
   EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
-  delete [] utf16;
+  delete[] utf16;
 }
-# endif  // GTEST_OS_WINDOWS_MOBILE
+#endif  // GTEST_OS_WINDOWS_MOBILE
 
 #endif  // GTEST_OS_WINDOWS
 
@@ -1154,9 +1133,7 @@ TEST(TestPropertyTest, ReplaceStringValue) {
 // AddFatalFailure() and AddNonfatalFailure() must be stand-alone
 // functions (i.e. their definitions cannot be inlined at the call
 // sites), or C++Builder won't compile the code.
-static void AddFatalFailure() {
-  FAIL() << "Expected fatal failure.";
-}
+static void AddFatalFailure() { FAIL() << "Expected fatal failure."; }
 
 static void AddNonfatalFailure() {
   ADD_FAILURE() << "Expected non-fatal failure.";
@@ -1164,10 +1141,7 @@ static void AddNonfatalFailure() {
 
 class ScopedFakeTestPartResultReporterTest : public Test {
  public:  // Must be public and not protected due to a bug in g++ 3.4.2.
-  enum FailureMode {
-    FATAL_FAILURE,
-    NONFATAL_FAILURE
-  };
+  enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE };
   static void AddFailure(FailureMode failure) {
     if (failure == FATAL_FAILURE) {
       AddFatalFailure();
@@ -1207,7 +1181,7 @@ TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
 #if GTEST_IS_THREADSAFE
 
 class ScopedFakeTestPartResultReporterWithThreadsTest
-  : public ScopedFakeTestPartResultReporterTest {
+    : public ScopedFakeTestPartResultReporterTest {
  protected:
   static void AddFailureInOtherThread(FailureMode failure) {
     ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
@@ -1260,7 +1234,7 @@ TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
 
 #ifdef __BORLANDC__
 // Silences warnings: "Condition is always true"
-# pragma option push -w-ccc
+#pragma option push -w-ccc
 #endif
 
 // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
@@ -1288,7 +1262,7 @@ void DoesNotAbortHelper(bool* aborted) {
 
 #ifdef __BORLANDC__
 // Restores warnings after previous "#pragma option push" suppressed them.
-# pragma option pop
+#pragma option pop
 #endif
 
 TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
@@ -1307,16 +1281,20 @@ static int global_var = 0;
 TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
 #ifndef __BORLANDC__
   // ICE's in C++Builder.
-  EXPECT_FATAL_FAILURE({
-    GTEST_USE_UNPROTECTED_COMMA_;
-    AddFatalFailure();
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {
+        GTEST_USE_UNPROTECTED_COMMA_;
+        AddFatalFailure();
+      },
+      "");
 #endif
 
-  EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
-    GTEST_USE_UNPROTECTED_COMMA_;
-    AddFatalFailure();
-  }, "");
+  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(
+      {
+        GTEST_USE_UNPROTECTED_COMMA_;
+        AddFatalFailure();
+      },
+      "");
 }
 
 // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
@@ -1324,8 +1302,7 @@ TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
 typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
 
 TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
-  EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
-                          "Expected non-fatal failure.");
+  EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), "Expected non-fatal failure.");
 }
 
 TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
@@ -1344,15 +1321,19 @@ TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
 // statement that contains a macro which expands to code containing an
 // unprotected comma.
 TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
-  EXPECT_NONFATAL_FAILURE({
-    GTEST_USE_UNPROTECTED_COMMA_;
-    AddNonfatalFailure();
-  }, "");
+  EXPECT_NONFATAL_FAILURE(
+      {
+        GTEST_USE_UNPROTECTED_COMMA_;
+        AddNonfatalFailure();
+      },
+      "");
 
-  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
-    GTEST_USE_UNPROTECTED_COMMA_;
-    AddNonfatalFailure();
-  }, "");
+  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
+      {
+        GTEST_USE_UNPROTECTED_COMMA_;
+        AddNonfatalFailure();
+      },
+      "");
 }
 
 #if GTEST_IS_THREADSAFE
@@ -1396,21 +1377,18 @@ class TestResultTest : public Test {
   typedef std::vector<TestPartResult> TPRVector;
 
   // We make use of 2 TestPartResult objects,
-  TestPartResult * pr1, * pr2;
+  TestPartResult *pr1, *pr2;
 
   // ... and 3 TestResult objects.
-  TestResult * r0, * r1, * r2;
+  TestResult *r0, *r1, *r2;
 
   void SetUp() override {
     // pr1 is for success.
-    pr1 = new TestPartResult(TestPartResult::kSuccess,
-                             "foo/bar.cc",
-                             10,
+    pr1 = new TestPartResult(TestPartResult::kSuccess, "foo/bar.cc", 10,
                              "Success!");
 
     // pr2 is for fatal failure.
-    pr2 = new TestPartResult(TestPartResult::kFatalFailure,
-                             "foo/bar.cc",
+    pr2 = new TestPartResult(TestPartResult::kFatalFailure, "foo/bar.cc",
                              -1,  // This line number means "unknown"
                              "Failure!");
 
@@ -1423,10 +1401,10 @@ class TestResultTest : public Test {
     // 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
-    TPRVector* results1 = const_cast<TPRVector*>(
-        &TestResultAccessor::test_part_results(*r1));
-    TPRVector* results2 = const_cast<TPRVector*>(
-        &TestResultAccessor::test_part_results(*r2));
+    TPRVector* results1 =
+        const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r1));
+    TPRVector* results2 =
+        const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r2));
 
     // r0 is an empty TestResult.
 
@@ -1597,23 +1575,24 @@ class GTestFlagSaverTest : public Test {
   static void SetUpTestSuite() {
     saver_ = new GTestFlagSaver;
 
-    GTEST_FLAG(also_run_disabled_tests) = false;
-    GTEST_FLAG(break_on_failure) = false;
-    GTEST_FLAG(catch_exceptions) = false;
-    GTEST_FLAG(death_test_use_fork) = false;
-    GTEST_FLAG(color) = "auto";
-    GTEST_FLAG(fail_fast) = false;
-    GTEST_FLAG(filter) = "";
-    GTEST_FLAG(list_tests) = false;
-    GTEST_FLAG(output) = "";
-    GTEST_FLAG(brief) = false;
-    GTEST_FLAG(print_time) = true;
-    GTEST_FLAG(random_seed) = 0;
-    GTEST_FLAG(repeat) = 1;
-    GTEST_FLAG(shuffle) = false;
-    GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
-    GTEST_FLAG(stream_result_to) = "";
-    GTEST_FLAG(throw_on_failure) = false;
+    GTEST_FLAG_SET(also_run_disabled_tests, false);
+    GTEST_FLAG_SET(break_on_failure, false);
+    GTEST_FLAG_SET(catch_exceptions, false);
+    GTEST_FLAG_SET(death_test_use_fork, false);
+    GTEST_FLAG_SET(color, "auto");
+    GTEST_FLAG_SET(fail_fast, false);
+    GTEST_FLAG_SET(filter, "");
+    GTEST_FLAG_SET(list_tests, false);
+    GTEST_FLAG_SET(output, "");
+    GTEST_FLAG_SET(brief, false);
+    GTEST_FLAG_SET(print_time, true);
+    GTEST_FLAG_SET(random_seed, 0);
+    GTEST_FLAG_SET(repeat, 1);
+    GTEST_FLAG_SET(recreate_environments_when_repeating, true);
+    GTEST_FLAG_SET(shuffle, false);
+    GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
+    GTEST_FLAG_SET(stream_result_to, "");
+    GTEST_FLAG_SET(throw_on_failure, false);
   }
 
   // Restores the Google Test flags that the tests have modified.  This will
@@ -1626,41 +1605,43 @@ class GTestFlagSaverTest : public Test {
   // Verifies that the Google Test flags have their default values, and then
   // modifies each of them.
   void VerifyAndModifyFlags() {
-    EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests));
-    EXPECT_FALSE(GTEST_FLAG(break_on_failure));
-    EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
-    EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
-    EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
-    EXPECT_FALSE(GTEST_FLAG(fail_fast));
-    EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
-    EXPECT_FALSE(GTEST_FLAG(list_tests));
-    EXPECT_STREQ("", GTEST_FLAG(output).c_str());
-    EXPECT_FALSE(GTEST_FLAG(brief));
-    EXPECT_TRUE(GTEST_FLAG(print_time));
-    EXPECT_EQ(0, GTEST_FLAG(random_seed));
-    EXPECT_EQ(1, GTEST_FLAG(repeat));
-    EXPECT_FALSE(GTEST_FLAG(shuffle));
-    EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth));
-    EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str());
-    EXPECT_FALSE(GTEST_FLAG(throw_on_failure));
-
-    GTEST_FLAG(also_run_disabled_tests) = true;
-    GTEST_FLAG(break_on_failure) = true;
-    GTEST_FLAG(catch_exceptions) = true;
-    GTEST_FLAG(color) = "no";
-    GTEST_FLAG(death_test_use_fork) = true;
-    GTEST_FLAG(fail_fast) = true;
-    GTEST_FLAG(filter) = "abc";
-    GTEST_FLAG(list_tests) = true;
-    GTEST_FLAG(output) = "xml:foo.xml";
-    GTEST_FLAG(brief) = true;
-    GTEST_FLAG(print_time) = false;
-    GTEST_FLAG(random_seed) = 1;
-    GTEST_FLAG(repeat) = 100;
-    GTEST_FLAG(shuffle) = true;
-    GTEST_FLAG(stack_trace_depth) = 1;
-    GTEST_FLAG(stream_result_to) = "localhost:1234";
-    GTEST_FLAG(throw_on_failure) = true;
+    EXPECT_FALSE(GTEST_FLAG_GET(also_run_disabled_tests));
+    EXPECT_FALSE(GTEST_FLAG_GET(break_on_failure));
+    EXPECT_FALSE(GTEST_FLAG_GET(catch_exceptions));
+    EXPECT_STREQ("auto", GTEST_FLAG_GET(color).c_str());
+    EXPECT_FALSE(GTEST_FLAG_GET(death_test_use_fork));
+    EXPECT_FALSE(GTEST_FLAG_GET(fail_fast));
+    EXPECT_STREQ("", GTEST_FLAG_GET(filter).c_str());
+    EXPECT_FALSE(GTEST_FLAG_GET(list_tests));
+    EXPECT_STREQ("", GTEST_FLAG_GET(output).c_str());
+    EXPECT_FALSE(GTEST_FLAG_GET(brief));
+    EXPECT_TRUE(GTEST_FLAG_GET(print_time));
+    EXPECT_EQ(0, GTEST_FLAG_GET(random_seed));
+    EXPECT_EQ(1, GTEST_FLAG_GET(repeat));
+    EXPECT_TRUE(GTEST_FLAG_GET(recreate_environments_when_repeating));
+    EXPECT_FALSE(GTEST_FLAG_GET(shuffle));
+    EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG_GET(stack_trace_depth));
+    EXPECT_STREQ("", GTEST_FLAG_GET(stream_result_to).c_str());
+    EXPECT_FALSE(GTEST_FLAG_GET(throw_on_failure));
+
+    GTEST_FLAG_SET(also_run_disabled_tests, true);
+    GTEST_FLAG_SET(break_on_failure, true);
+    GTEST_FLAG_SET(catch_exceptions, true);
+    GTEST_FLAG_SET(color, "no");
+    GTEST_FLAG_SET(death_test_use_fork, true);
+    GTEST_FLAG_SET(fail_fast, true);
+    GTEST_FLAG_SET(filter, "abc");
+    GTEST_FLAG_SET(list_tests, true);
+    GTEST_FLAG_SET(output, "xml:foo.xml");
+    GTEST_FLAG_SET(brief, true);
+    GTEST_FLAG_SET(print_time, false);
+    GTEST_FLAG_SET(random_seed, 1);
+    GTEST_FLAG_SET(repeat, 100);
+    GTEST_FLAG_SET(recreate_environments_when_repeating, false);
+    GTEST_FLAG_SET(shuffle, true);
+    GTEST_FLAG_SET(stack_trace_depth, 1);
+    GTEST_FLAG_SET(stream_result_to, "localhost:1234");
+    GTEST_FLAG_SET(throw_on_failure, true);
   }
 
  private:
@@ -1674,15 +1655,11 @@ GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr;
 // tests are designed to work regardless of their order.
 
 // Modifies the Google Test flags in the test body.
-TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
-  VerifyAndModifyFlags();
-}
+TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { VerifyAndModifyFlags(); }
 
 // Verifies that the Google Test flags in the body of the previous test were
 // restored to their original values.
-TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
-  VerifyAndModifyFlags();
-}
+TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { VerifyAndModifyFlags(); }
 
 // Sets an environment variable with the given name to the given
 // value.  If the value argument is "", unsets the environment
@@ -1699,12 +1676,12 @@ static void SetEnv(const char* name, const char* value) {
 
   // Because putenv stores a pointer to the string buffer, we can't delete the
   // previous string (if present) until after it's replaced.
-  std::string *prev_env = NULL;
+  std::stringprev_env = NULL;
   if (added_env.find(name) != added_env.end()) {
     prev_env = added_env[name];
   }
-  added_env[name] = new std::string(
-      (Message() << name << "=" << value).GetString());
+  added_env[name] =
+      new std::string((Message() << name << "=" << value).GetString());
 
   // The standard signature of putenv accepts a 'char*' argument. Other
   // implementations, like C++Builder's, accept a 'const char*'.
@@ -1736,7 +1713,7 @@ TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
   EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
 }
 
-# if !defined(GTEST_GET_INT32_FROM_ENV_)
+#if !defined(GTEST_GET_INT32_FROM_ENV_)
 
 // Tests that Int32FromGTestEnv() returns the default value when the
 // environment variable overflows as an Int32.
@@ -1762,7 +1739,7 @@ TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
   EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
 }
 
-# endif  // !defined(GTEST_GET_INT32_FROM_ENV_)
+#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
@@ -1776,29 +1753,29 @@ TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
 }
 #endif  // !GTEST_OS_WINDOWS_MOBILE
 
-// Tests ParseInt32Flag().
+// Tests ParseFlag().
 
 // Tests that ParseInt32Flag() returns false and doesn't change the
 // output value when the flag has wrong format
 TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
   int32_t value = 123;
-  EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value));
+  EXPECT_FALSE(ParseFlag("--a=100", "b", &value));
   EXPECT_EQ(123, value);
 
-  EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value));
+  EXPECT_FALSE(ParseFlag("a=100", "a", &value));
   EXPECT_EQ(123, value);
 }
 
-// Tests that ParseInt32Flag() returns false and doesn't change the
+// Tests that ParseFlag() returns false and doesn't change the
 // output value when the flag overflows as an Int32.
 TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
   printf("(expecting 2 warnings)\n");
 
   int32_t value = 123;
-  EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value));
+  EXPECT_FALSE(ParseFlag("--abc=12345678987654321", "abc", &value));
   EXPECT_EQ(123, value);
 
-  EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value));
+  EXPECT_FALSE(ParseFlag("--abc=-12345678987654321", "abc", &value));
   EXPECT_EQ(123, value);
 }
 
@@ -1809,10 +1786,10 @@ TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
   printf("(expecting 2 warnings)\n");
 
   int32_t value = 123;
-  EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value));
+  EXPECT_FALSE(ParseFlag("--abc=A1", "abc", &value));
   EXPECT_EQ(123, value);
 
-  EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value));
+  EXPECT_FALSE(ParseFlag("--abc=12X", "abc", &value));
   EXPECT_EQ(123, value);
 }
 
@@ -1821,11 +1798,10 @@ TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
 // the range of an Int32.
 TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
   int32_t value = 123;
-  EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
+  EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
   EXPECT_EQ(456, value);
 
-  EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789",
-                             "abc", &value));
+  EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=-789", "abc", &value));
   EXPECT_EQ(-789, value);
 }
 
@@ -1847,8 +1823,7 @@ TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
 TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
   EXPECT_DEATH_IF_SUPPORTED(
-      Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
-      ".*");
+      Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*");
 }
 
 // Tests that Int32FromEnvOrDie() aborts with an error message
@@ -1856,8 +1831,7 @@ TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
 TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
   SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
   EXPECT_DEATH_IF_SUPPORTED(
-      Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
-      ".*");
+      Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*");
 }
 
 // Tests that ShouldRunTestOnShard() selects all tests
@@ -1964,7 +1938,8 @@ TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
           prev_selected_shard_index = shard_index;
         } else {
           ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
-            << shard_index << " are both selected to run test " << test_id;
+                        << shard_index << " are both selected to run test "
+                        << test_id;
         }
       }
     }
@@ -1976,7 +1951,7 @@ TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
     int num_tests_on_shard = 0;
     for (int test_id = 0; test_id < num_tests; test_id++) {
       num_tests_on_shard +=
-        ShouldRunTestOnShard(num_shards, shard_index, test_id);
+          ShouldRunTestOnShard(num_shards, shard_index, test_id);
     }
     EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
   }
@@ -2008,8 +1983,8 @@ TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
 void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
     const TestResult& test_result, const char* key) {
   EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
-  ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key
-                                                  << "' recorded unexpectedly.";
+  ASSERT_EQ(0, test_result.test_property_count())
+      << "Property for key '" << key << "' recorded unexpectedly.";
 }
 
 void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
@@ -2036,10 +2011,10 @@ void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
 }
 
 // Tests that property recording functions in UnitTest outside of tests
-// functions correcly.  Creating a separate instance of UnitTest ensures it
+// functions correctly.  Creating a separate instance of UnitTest ensures it
 // is in a state similar to the UnitTest's singleton's between tests.
-class UnitTestRecordPropertyTest :
-    public testing::internal::UnitTestRecordPropertyTestHelper {
+class UnitTestRecordPropertyTest
+    public testing::internal::UnitTestRecordPropertyTestHelper {
  public:
   static void SetUpTestSuite() {
     ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
@@ -2078,8 +2053,7 @@ TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
 
   EXPECT_STREQ("key_1",
                unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
-  EXPECT_STREQ("1",
-               unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
+  EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
 }
 
 // Tests TestResult has multiple properties when added.
@@ -2120,16 +2094,13 @@ TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
 
 TEST_F(UnitTestRecordPropertyTest,
        AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) {
-  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
-      "name");
+  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("name");
   ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
       "value_param");
   ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
       "type_param");
-  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
-      "status");
-  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
-      "time");
+  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("status");
+  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("time");
   ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
       "classname");
 }
@@ -2177,9 +2148,7 @@ static Environment* record_property_env GTEST_ATTRIBUTE_UNUSED_ =
 // First, some predicates and predicate-formatters needed by the tests.
 
 // Returns true if and only if the argument is an even number.
-bool IsEven(int n) {
-  return (n % 2) == 0;
-}
+bool IsEven(int n) { return (n % 2) == 0; }
 
 // A functor that returns true if and only if the argument is an even number.
 struct IsEvenFunctor {
@@ -2226,41 +2195,37 @@ struct AssertIsEvenFunctor {
 };
 
 // Returns true if and only if the sum of the arguments is an even number.
-bool SumIsEven2(int n1, int n2) {
-  return IsEven(n1 + n2);
-}
+bool SumIsEven2(int n1, int n2) { return IsEven(n1 + n2); }
 
 // A functor that returns true if and only if the sum of the arguments is an
 // even number.
 struct SumIsEven3Functor {
-  bool operator()(int n1, int n2, int n3) {
-    return IsEven(n1 + n2 + n3);
-  }
+  bool operator()(int n1, int n2, int n3) { return IsEven(n1 + n2 + n3); }
 };
 
 // A predicate-formatter function that asserts the sum of the
 // arguments is an even number.
-AssertionResult AssertSumIsEven4(
-    const char* e1, const char* e2, const char* e3, const char* e4,
-    int n1, int n2, int n3, int n4) {
+AssertionResult AssertSumIsEven4(const char* e1, const char* e2, const char* e3,
+                                 const char* e4, int n1, int n2, int n3,
+                                 int n4) {
   const int sum = n1 + n2 + n3 + n4;
   if (IsEven(sum)) {
     return AssertionSuccess();
   }
 
   Message msg;
-  msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
-      << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
-      << ") evaluates to " << sum << ", which is not even.";
+  msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " (" << n1 << " + "
+      << n2 << " + " << n3 << " + " << n4 << ") evaluates to " << sum
+      << ", which is not even.";
   return AssertionFailure(msg);
 }
 
 // A predicate-formatter functor that asserts the sum of the arguments
 // is an even number.
 struct AssertSumIsEven5Functor {
-  AssertionResult operator()(
-      const char* e1, const char* e2, const char* e3, const char* e4,
-      const char* e5, int n1, int n2, int n3, int n4, int n5) {
+  AssertionResult operator()(const char* e1, const char* e2, const char* e3,
+                             const char* e4, const char* e5, int n1, int n2,
+                             int n3, int n4, int n5) {
     const int sum = n1 + n2 + n3 + n4 + n5;
     if (IsEven(sum)) {
       return AssertionSuccess();
@@ -2268,14 +2233,12 @@ struct AssertSumIsEven5Functor {
 
     Message msg;
     msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
-        << " ("
-        << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
-        << ") evaluates to " << sum << ", which is not even.";
+        << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + "
+        << n5 << ") evaluates to " << sum << ", which is not even.";
     return AssertionFailure(msg);
   }
 };
 
-
 // Tests unary predicate assertions.
 
 // Tests unary predicate assertions that don't use a custom formatter.
@@ -2285,11 +2248,12 @@ TEST(Pred1Test, WithoutFormat) {
   ASSERT_PRED1(IsEven, 4);
 
   // Failure cases.
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
-  }, "This failure is expected.");
-  EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
-                       "evaluates to false");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
+      },
+      "This failure is expected.");
+  EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5), "evaluates to false");
 }
 
 // Tests unary predicate assertions that use a custom formatter.
@@ -2297,15 +2261,17 @@ TEST(Pred1Test, WithFormat) {
   // Success cases.
   EXPECT_PRED_FORMAT1(AssertIsEven, 2);
   ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
-    << "This failure is UNEXPECTED!";
+      << "This failure is UNEXPECTED!";
 
   // Failure cases.
   const int n = 5;
   EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
                           "n evaluates to 5, which is not even.");
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
-  }, "This failure is expected.");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
+      },
+      "This failure is expected.");
 }
 
 // Tests that unary predicate assertions evaluates their arguments
@@ -2317,14 +2283,15 @@ TEST(Pred1Test, SingleEvaluationOnFailure) {
   EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
 
   // A failure case.
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
-        << "This failure is expected.";
-  }, "This failure is expected.");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
+            << "This failure is expected.";
+      },
+      "This failure is expected.");
   EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
 }
 
-
 // Tests predicate assertions whose arity is >= 2.
 
 // Tests predicate assertions that don't use a custom formatter.
@@ -2336,19 +2303,23 @@ TEST(PredTest, WithoutFormat) {
   // Failure cases.
   const int n1 = 1;
   const int n2 = 2;
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
-  }, "This failure is expected.");
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
-  }, "evaluates to false");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
+      },
+      "This failure is expected.");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
+      },
+      "evaluates to false");
 }
 
 // Tests predicate assertions that use a custom formatter.
 TEST(PredTest, WithFormat) {
   // Success cases.
-  ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
-    "This failure is UNEXPECTED!";
+  ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10)
+      << "This failure is UNEXPECTED!";
   EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
 
   // Failure cases.
@@ -2356,13 +2327,17 @@ TEST(PredTest, WithFormat) {
   const int n2 = 2;
   const int n3 = 4;
   const int n4 = 6;
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
-  }, "evaluates to 13, which is not even.");
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
-        << "This failure is expected.";
-  }, "This failure is expected.");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
+      },
+      "evaluates to 13, which is not even.");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
+            << "This failure is expected.";
+      },
+      "This failure is expected.");
 }
 
 // Tests that predicate assertions evaluates their arguments
@@ -2380,9 +2355,8 @@ TEST(PredTest, SingleEvaluationOnFailure) {
   int n3 = 0;
   int n4 = 0;
   int n5 = 0;
-  ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
-                      n1++, n2++, n3++, n4++, n5++)
-                        << "This failure is UNEXPECTED!";
+  ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), n1++, n2++, n3++, n4++, n5++)
+      << "This failure is UNEXPECTED!";
   EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
   EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
   EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
@@ -2391,19 +2365,23 @@ TEST(PredTest, SingleEvaluationOnFailure) {
 
   // A failure case.
   n1 = n2 = n3 = 0;
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
-        << "This failure is expected.";
-  }, "This failure is expected.");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
+            << "This failure is expected.";
+      },
+      "This failure is expected.");
   EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
   EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
   EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
 
   // Another failure case.
   n1 = n2 = n3 = n4 = 0;
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
-  }, "evaluates to 1, which is not even.");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
+      },
+      "evaluates to 1, which is not even.");
   EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
   EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
   EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
@@ -2414,7 +2392,7 @@ TEST(PredTest, SingleEvaluationOnFailure) {
 TEST(PredTest, ExpectPredEvalFailure) {
   std::set<int> set_a = {2, 1, 3, 4, 5};
   std::set<int> set_b = {0, 4, 8};
-  const auto compare_sets = [] (std::set<int>, std::set<int>) { return false; };
+  const auto compare_sets = [](std::set<int>, std::set<int>) { return false; };
   EXPECT_NONFATAL_FAILURE(
       EXPECT_PRED2(compare_sets, set_a, set_b),
       "compare_sets(set_a, set_b) evaluates to false, where\nset_a evaluates "
@@ -2424,9 +2402,7 @@ TEST(PredTest, ExpectPredEvalFailure) {
 // Some helper functions for testing using overloaded/template
 // functions with ASSERT_PREDn and EXPECT_PREDn.
 
-bool IsPositive(double x) {
-  return x > 0;
-}
+bool IsPositive(double x) { return x > 0; }
 
 template <typename T>
 bool IsNegative(T x) {
@@ -2442,7 +2418,7 @@ bool GreaterThan(T1 x1, T2 x2) {
 // their types are explicitly specified.
 TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
   // C++Builder requires C-style casts rather than static_cast.
-  EXPECT_PRED1((bool (*)(int))(IsPositive), 5);  // NOLINT
+  EXPECT_PRED1((bool (*)(int))(IsPositive), 5);       // NOLINT
   ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0);  // NOLINT
 }
 
@@ -2455,31 +2431,27 @@ TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
   ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
 }
 
-
 // Some helper functions for testing using overloaded/template
 // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
 
 AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
-  return n > 0 ? AssertionSuccess() :
-      AssertionFailure(Message() << "Failure");
+  return n > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure");
 }
 
 AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
-  return x > 0 ? AssertionSuccess() :
-      AssertionFailure(Message() << "Failure");
+  return x > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure");
 }
 
 template <typename T>
 AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
-  return x < 0 ? AssertionSuccess() :
-      AssertionFailure(Message() << "Failure");
+  return x < 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure");
 }
 
 template <typename T1, typename T2>
 AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
                              const T1& x1, const T2& x2) {
-  return x1 == x2 ? AssertionSuccess() :
-      AssertionFailure(Message() << "Failure");
+  return x1 == x2 ? AssertionSuccess()
+                  : AssertionFailure(Message() << "Failure");
 }
 
 // Tests that overloaded functions can be used in *_PRED_FORMAT*
@@ -2496,20 +2468,18 @@ TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
   ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
 }
 
-
 // Tests string assertions.
 
 // Tests ASSERT_STREQ with non-NULL arguments.
 TEST(StringAssertionTest, ASSERT_STREQ) {
-  const char * const p1 = "good";
+  const char* const p1 = "good";
   ASSERT_STREQ(p1, p1);
 
   // Let p2 have the same content as p1, but be at a different address.
   const char p2[] = "good";
   ASSERT_STREQ(p1, p2);
 
-  EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
-                       "  \"bad\"\n  \"good\"");
+  EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"), "  \"bad\"\n  \"good\"");
 }
 
 // Tests ASSERT_STREQ with NULL arguments.
@@ -2532,8 +2502,7 @@ TEST(StringAssertionTest, ASSERT_STRNE) {
   ASSERT_STRNE(nullptr, "");
   ASSERT_STRNE("", "Hi");
   ASSERT_STRNE("Hi", "");
-  EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
-                       "\"Hi\" vs \"Hi\"");
+  EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"), "\"Hi\" vs \"Hi\"");
 }
 
 // Tests ASSERT_STRCASEEQ.
@@ -2542,8 +2511,7 @@ TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
   ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr);
 
   ASSERT_STRCASEEQ("", "");
-  EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
-                       "Ignoring case");
+  EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"), "Ignoring case");
 }
 
 // Tests ASSERT_STRCASENE.
@@ -2555,8 +2523,7 @@ TEST(StringAssertionTest, ASSERT_STRCASENE) {
   ASSERT_STRCASENE(nullptr, "");
   ASSERT_STRCASENE("", "Hi");
   ASSERT_STRCASENE("Hi", "");
-  EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
-                       "(ignoring case)");
+  EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"), "(ignoring case)");
 }
 
 // Tests *_STREQ on wide strings.
@@ -2574,17 +2541,17 @@ TEST(StringAssertionTest, STREQ_Wide) {
   EXPECT_STREQ(L"Hi", L"Hi");
 
   // Unequal strings.
-  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
-                          "Abc");
+  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"), "Abc");
 
   // Strings containing wide characters.
-  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
-                          "abc");
+  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"), "abc");
 
   // The streaming variation.
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
-  }, "Expected failure");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
+      },
+      "Expected failure");
 }
 
 // Tests *_STRNE on wide strings.
@@ -2597,22 +2564,19 @@ TEST(StringAssertionTest, STRNE_Wide) {
       "");
 
   // Empty strings.
-  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
-                          "L\"\"");
+  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""), "L\"\"");
 
   // Non-null vs NULL.
   ASSERT_STRNE(L"non-null", nullptr);
 
   // Equal strings.
-  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
-                          "L\"Hi\"");
+  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"), "L\"Hi\"");
 
   // Unequal strings.
   EXPECT_STRNE(L"abc", L"Abc");
 
   // Strings containing wide characters.
-  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
-                          "abc");
+  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"), "abc");
 
   // The streaming variation.
   ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
@@ -2646,12 +2610,13 @@ TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
 // Tests that IsSubstring() generates the correct message when the input
 // argument type is const char*.
 TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
-  EXPECT_STREQ("Value of: needle_expr\n"
-               "  Actual: \"needle\"\n"
-               "Expected: a substring of haystack_expr\n"
-               "Which is: \"haystack\"",
-               IsSubstring("needle_expr", "haystack_expr",
-                           "needle", "haystack").failure_message());
+  EXPECT_STREQ(
+      "Value of: needle_expr\n"
+      "  Actual: \"needle\"\n"
+      "Expected: a substring of haystack_expr\n"
+      "Which is: \"haystack\"",
+      IsSubstring("needle_expr", "haystack_expr", "needle", "haystack")
+          .failure_message());
 }
 
 // Tests that IsSubstring returns the correct result when the input
@@ -2672,13 +2637,14 @@ TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
 // Tests that IsSubstring() generates the correct message when the input
 // argument type is ::std::wstring.
 TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
-  EXPECT_STREQ("Value of: needle_expr\n"
-               "  Actual: L\"needle\"\n"
-               "Expected: a substring of haystack_expr\n"
-               "Which is: L\"haystack\"",
-               IsSubstring(
-                   "needle_expr", "haystack_expr",
-                   ::std::wstring(L"needle"), L"haystack").failure_message());
+  EXPECT_STREQ(
+      "Value of: needle_expr\n"
+      "  Actual: L\"needle\"\n"
+      "Expected: a substring of haystack_expr\n"
+      "Which is: L\"haystack\"",
+      IsSubstring("needle_expr", "haystack_expr", ::std::wstring(L"needle"),
+                  L"haystack")
+          .failure_message());
 }
 
 #endif  // GTEST_HAS_STD_WSTRING
@@ -2702,13 +2668,13 @@ TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
 // Tests that IsNotSubstring() generates the correct message when the input
 // argument type is const wchar_t*.
 TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
-  EXPECT_STREQ("Value of: needle_expr\n"
-               "  Actual: L\"needle\"\n"
-               "Expected: not a substring of haystack_expr\n"
-               "Which is: L\"two needles\"",
-               IsNotSubstring(
-                   "needle_expr", "haystack_expr",
-                   L"needle", L"two needles").failure_message());
+  EXPECT_STREQ(
+      "Value of: needle_expr\n"
+      "  Actual: L\"needle\"\n"
+      "Expected: not a substring of haystack_expr\n"
+      "Which is: L\"two needles\"",
+      IsNotSubstring("needle_expr", "haystack_expr", L"needle", L"two needles")
+          .failure_message());
 }
 
 // Tests that IsNotSubstring returns the correct result when the input
@@ -2721,13 +2687,14 @@ TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
 // Tests that IsNotSubstring() generates the correct message when the input
 // argument type is ::std::string.
 TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
-  EXPECT_STREQ("Value of: needle_expr\n"
-               "  Actual: \"needle\"\n"
-               "Expected: not a substring of haystack_expr\n"
-               "Which is: \"two needles\"",
-               IsNotSubstring(
-                   "needle_expr", "haystack_expr",
-                   ::std::string("needle"), "two needles").failure_message());
+  EXPECT_STREQ(
+      "Value of: needle_expr\n"
+      "  Actual: \"needle\"\n"
+      "Expected: not a substring of haystack_expr\n"
+      "Which is: \"two needles\"",
+      IsNotSubstring("needle_expr", "haystack_expr", ::std::string("needle"),
+                     "two needles")
+          .failure_message());
 }
 
 #if GTEST_HAS_STD_WSTRING
@@ -2774,20 +2741,20 @@ class FloatingPointTest : public Test {
     const Bits zero_bits = Floating(0).bits();
 
     // Makes some numbers close to 0.0.
-    values_.close_to_positive_zero = Floating::ReinterpretBits(
-        zero_bits + max_ulps/2);
-    values_.close_to_negative_zero = -Floating::ReinterpretBits(
-        zero_bits + max_ulps - max_ulps/2);
-    values_.further_from_negative_zero = -Floating::ReinterpretBits(
-        zero_bits + max_ulps + 1 - max_ulps/2);
+    values_.close_to_positive_zero =
+        Floating::ReinterpretBits(zero_bits + max_ulps / 2);
+    values_.close_to_negative_zero =
+        -Floating::ReinterpretBits(zero_bits + max_ulps - max_ulps / 2);
+    values_.further_from_negative_zero =
+        -Floating::ReinterpretBits(zero_bits + max_ulps + 1 - max_ulps / 2);
 
     // The bits that represent 1.0.
     const Bits one_bits = Floating(1).bits();
 
     // Makes some numbers close to 1.0.
     values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
-    values_.further_from_one = Floating::ReinterpretBits(
-        one_bits + max_ulps + 1);
+    values_.further_from_one =
+        Floating::ReinterpretBits(one_bits + max_ulps + 1);
 
     // +infinity.
     values_.infinity = Floating::Infinity();
@@ -2796,23 +2763,23 @@ class FloatingPointTest : public Test {
     const Bits infinity_bits = Floating(values_.infinity).bits();
 
     // Makes some numbers close to infinity.
-    values_.close_to_infinity = Floating::ReinterpretBits(
-        infinity_bits - max_ulps);
-    values_.further_from_infinity = Floating::ReinterpretBits(
-        infinity_bits - max_ulps - 1);
+    values_.close_to_infinity =
+        Floating::ReinterpretBits(infinity_bits - max_ulps);
+    values_.further_from_infinity =
+        Floating::ReinterpretBits(infinity_bits - max_ulps - 1);
 
     // Makes some NAN's.  Sets the most significant bit of the fraction so that
     // our NaN's are quiet; trying to process a signaling NaN would raise an
     // exception if our environment enables floating point exceptions.
-    values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
-        | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
-    values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
-        | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
+    values_.nan1 = Floating::ReinterpretBits(
+        Floating::kExponentBitMask |
+        (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
+    values_.nan2 = Floating::ReinterpretBits(
+        Floating::kExponentBitMask |
+        (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
   }
 
-  void TestSize() {
-    EXPECT_EQ(sizeof(RawType), sizeof(Bits));
-  }
+  void TestSize() { EXPECT_EQ(sizeof(RawType), sizeof(Bits)); }
 
   static TestValues values_;
 };
@@ -2825,17 +2792,13 @@ typename FloatingPointTest<RawType>::TestValues
 typedef FloatingPointTest<float> FloatTest;
 
 // Tests that the size of Float::Bits matches the size of float.
-TEST_F(FloatTest, Size) {
-  TestSize();
-}
+TEST_F(FloatTest, Size) { TestSize(); }
 
 // Tests comparing with +0 and -0.
 TEST_F(FloatTest, Zeros) {
   EXPECT_FLOAT_EQ(0.0, -0.0);
-  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
-                          "1.0");
-  EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
-                       "1.5");
+  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0), "1.0");
+  EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5), "1.5");
 }
 
 // Tests comparing numbers close to 0.
@@ -2856,10 +2819,11 @@ TEST_F(FloatTest, AlmostZeros) {
   EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
   EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
 
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_FLOAT_EQ(v.close_to_positive_zero,
-                    v.further_from_negative_zero);
-  }, "v.further_from_negative_zero");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_FLOAT_EQ(v.close_to_positive_zero, v.further_from_negative_zero);
+      },
+      "v.further_from_negative_zero");
 }
 
 // Tests comparing numbers close to each other.
@@ -2871,8 +2835,7 @@ TEST_F(FloatTest, SmallDiff) {
 
 // Tests comparing numbers far apart.
 TEST_F(FloatTest, LargeDiff) {
-  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
-                          "3.0");
+  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0), "3.0");
 }
 
 // Tests comparing with infinity.
@@ -2901,15 +2864,11 @@ TEST_F(FloatTest, NaN) {
   // (parentheses).
   static const FloatTest::TestValues& v = this->values_;
 
-  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
-                          "v.nan1");
-  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
-                          "v.nan2");
-  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
-                          "v.nan1");
+  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1), "v.nan1");
+  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2), "v.nan2");
+  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1), "v.nan1");
 
-  EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
-                       "v.infinity");
+  EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), "v.infinity");
 }
 
 // Tests that *_FLOAT_EQ are reflexive.
@@ -2963,36 +2922,40 @@ TEST_F(FloatTest, FloatLEFails) {
                           "(2.0f) <= (1.0f)");
 
   // or by a small yet non-negligible margin,
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
-  }, "(values_.further_from_one) <= (1.0f)");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
+      },
+      "(values_.further_from_one) <= (1.0f)");
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
-  }, "(values_.nan1) <= (values_.infinity)");
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
-  }, "(-values_.infinity) <= (values_.nan1)");
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
-  }, "(values_.nan1) <= (values_.nan1)");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
+      },
+      "(values_.nan1) <= (values_.infinity)");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
+      },
+      "(-values_.infinity) <= (values_.nan1)");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
+      },
+      "(values_.nan1) <= (values_.nan1)");
 }
 
 // Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
 typedef FloatingPointTest<double> DoubleTest;
 
 // Tests that the size of Double::Bits matches the size of double.
-TEST_F(DoubleTest, Size) {
-  TestSize();
-}
+TEST_F(DoubleTest, Size) { TestSize(); }
 
 // Tests comparing with +0 and -0.
 TEST_F(DoubleTest, Zeros) {
   EXPECT_DOUBLE_EQ(0.0, -0.0);
-  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
-                          "1.0");
-  EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
-                       "1.0");
+  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0), "1.0");
+  EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0), "1.0");
 }
 
 // Tests comparing numbers close to 0.
@@ -3013,10 +2976,12 @@ TEST_F(DoubleTest, AlmostZeros) {
   EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
   EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
 
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
-                     v.further_from_negative_zero);
-  }, "v.further_from_negative_zero");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
+                         v.further_from_negative_zero);
+      },
+      "v.further_from_negative_zero");
 }
 
 // Tests comparing numbers close to each other.
@@ -3028,8 +2993,7 @@ TEST_F(DoubleTest, SmallDiff) {
 
 // Tests comparing numbers far apart.
 TEST_F(DoubleTest, LargeDiff) {
-  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
-                          "3.0");
+  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0), "3.0");
 }
 
 // Tests comparing with infinity.
@@ -3053,12 +3017,10 @@ TEST_F(DoubleTest, NaN) {
   static const DoubleTest::TestValues& v = this->values_;
 
   // Nokia's STLport crashes if we try to output infinity or NaN.
-  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
-                          "v.nan1");
+  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1), "v.nan1");
   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
   EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
-  EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
-                       "v.infinity");
+  EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), "v.infinity");
 }
 
 // Tests that *_DOUBLE_EQ are reflexive.
@@ -3119,22 +3081,29 @@ TEST_F(DoubleTest, DoubleLEFails) {
                           "(2.0) <= (1.0)");
 
   // or by a small yet non-negligible margin,
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
-  }, "(values_.further_from_one) <= (1.0)");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
+      },
+      "(values_.further_from_one) <= (1.0)");
 
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
-  }, "(values_.nan1) <= (values_.infinity)");
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
-  }, " (-values_.infinity) <= (values_.nan1)");
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
-  }, "(values_.nan1) <= (values_.nan1)");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
+      },
+      "(values_.nan1) <= (values_.infinity)");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
+      },
+      " (-values_.infinity) <= (values_.nan1)");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
+      },
+      "(values_.nan1) <= (values_.nan1)");
 }
 
-
 // Verifies that a test or test case whose name starts with DISABLED_ is
 // not run.
 
@@ -3146,9 +3115,7 @@ TEST(DisabledTest, DISABLED_TestShouldNotRun) {
 
 // A test whose name does not start with DISABLED_.
 // Should run.
-TEST(DisabledTest, NotDISABLED_TestShouldRun) {
-  EXPECT_EQ(1, 1);
-}
+TEST(DisabledTest, NotDISABLED_TestShouldRun) { EXPECT_EQ(1, 1); }
 
 // A test case whose name starts with DISABLED_.
 // Should not run.
@@ -3188,8 +3155,7 @@ TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
 // Tests that disabled typed tests aren't run.
 
 template <typename T>
-class TypedTest : public Test {
-};
+class TypedTest : public Test {};
 
 typedef testing::Types<int, double> NumericTypes;
 TYPED_TEST_SUITE(TypedTest, NumericTypes);
@@ -3199,8 +3165,7 @@ TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
 }
 
 template <typename T>
-class DISABLED_TypedTest : public Test {
-};
+class DISABLED_TypedTest : public Test {};
 
 TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes);
 
@@ -3211,8 +3176,7 @@ TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
 // Tests that disabled type-parameterized tests aren't run.
 
 template <typename T>
-class TypedTestP : public Test {
-};
+class TypedTestP : public Test {};
 
 TYPED_TEST_SUITE_P(TypedTestP);
 
@@ -3226,8 +3190,7 @@ REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun);
 INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes);
 
 template <typename T>
-class DISABLED_TypedTestP : public Test {
-};
+class DISABLED_TypedTestP : public Test {};
 
 TYPED_TEST_SUITE_P(DISABLED_TypedTestP);
 
@@ -3247,15 +3210,11 @@ class SingleEvaluationTest : public Test {
   // This helper function is needed by the FailedASSERT_STREQ test
   // below.  It's public to work around C++Builder's bug with scoping local
   // classes.
-  static void CompareAndIncrementCharPtrs() {
-    ASSERT_STREQ(p1_++, p2_++);
-  }
+  static void CompareAndIncrementCharPtrs() { ASSERT_STREQ(p1_++, p2_++); }
 
   // This helper function is needed by the FailedASSERT_NE test below.  It's
   // public to work around C++Builder's bug with scoping local classes.
-  static void CompareAndIncrementInts() {
-    ASSERT_NE(a_++, b_++);
-  }
+  static void CompareAndIncrementInts() { ASSERT_NE(a_++, b_++); }
 
  protected:
   SingleEvaluationTest() {
@@ -3298,8 +3257,7 @@ TEST_F(SingleEvaluationTest, ASSERT_STR) {
   EXPECT_EQ(s2_ + 1, p2_);
 
   // failed EXPECT_STRCASEEQ
-  EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
-                          "Ignoring case");
+  EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++), "Ignoring case");
   EXPECT_EQ(s1_ + 2, p1_);
   EXPECT_EQ(s2_ + 2, p2_);
 }
@@ -3359,34 +3317,39 @@ TEST_F(SingleEvaluationTest, OtherCases) {
 
 #endif  // GTEST_HAS_RTTI
 
-void ThrowAnInteger() {
-  throw 1;
-}
-void ThrowRuntimeError(const char* what) {
-  throw std::runtime_error(what);
-}
+void ThrowAnInteger() { throw 1; }
+void ThrowRuntimeError(const char* what) { throw std::runtime_error(what); }
 
 // Tests that assertion arguments are evaluated exactly once.
 TEST_F(SingleEvaluationTest, ExceptionTests) {
   // successful EXPECT_THROW
-  EXPECT_THROW({  // NOLINT
-    a_++;
-    ThrowAnInteger();
-  }, int);
+  EXPECT_THROW(
+      {  // NOLINT
+        a_++;
+        ThrowAnInteger();
+      },
+      int);
   EXPECT_EQ(1, a_);
 
   // failed EXPECT_THROW, throws different
-  EXPECT_NONFATAL_FAILURE(EXPECT_THROW({  // NOLINT
-    a_++;
-    ThrowAnInteger();
-  }, bool), "throws a different type");
+  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(
+                              {  // NOLINT
+                                a_++;
+                                ThrowAnInteger();
+                              },
+                              bool),
+                          "throws a different type");
   EXPECT_EQ(2, a_);
 
   // failed EXPECT_THROW, throws runtime error
-  EXPECT_NONFATAL_FAILURE(EXPECT_THROW({  // NOLINT
-    a_++;
-    ThrowRuntimeError("A description");
-  }, bool), "throws " ERROR_DESC " with description \"A description\"");
+  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(
+                              {  // NOLINT
+                                a_++;
+                                ThrowRuntimeError("A description");
+                              },
+                              bool),
+                          "throws " ERROR_DESC
+                          " with description \"A description\"");
   EXPECT_EQ(3, a_);
 
   // failed EXPECT_THROW, throws nothing
@@ -3399,9 +3362,10 @@ TEST_F(SingleEvaluationTest, ExceptionTests) {
 
   // failed EXPECT_NO_THROW
   EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({  // NOLINT
-    a_++;
-    ThrowAnInteger();
-  }), "it throws");
+                            a_++;
+                            ThrowAnInteger();
+                          }),
+                          "it throws");
   EXPECT_EQ(6, a_);
 
   // successful EXPECT_ANY_THROW
@@ -3422,12 +3386,8 @@ TEST_F(SingleEvaluationTest, ExceptionTests) {
 class NoFatalFailureTest : public Test {
  protected:
   void Succeeds() {}
-  void FailsNonFatal() {
-    ADD_FAILURE() << "some non-fatal failure";
-  }
-  void Fails() {
-    FAIL() << "some fatal failure";
-  }
+  void FailsNonFatal() { ADD_FAILURE() << "some non-fatal failure"; }
+  void Fails() { FAIL() << "some fatal failure"; }
 
   void DoAssertNoFatalFailureOnFails() {
     ASSERT_NO_FATAL_FAILURE(Fails());
@@ -3446,12 +3406,10 @@ TEST_F(NoFatalFailureTest, NoFailure) {
 }
 
 TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
-  EXPECT_NONFATAL_FAILURE(
-      EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
-      "some non-fatal failure");
-  EXPECT_NONFATAL_FAILURE(
-      ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
-      "some non-fatal failure");
+  EXPECT_NONFATAL_FAILURE(EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
+                          "some non-fatal failure");
+  EXPECT_NONFATAL_FAILURE(ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
+                          "some non-fatal failure");
 }
 
 TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
@@ -3574,8 +3532,9 @@ TEST(EditDistance, TestSuites) {
                 EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
                                                     CharsToIndices(c->right))))
         << "Left <" << c->left << "> Right <" << c->right << "> Edits <"
-        << EditsToString(CalculateOptimalEdits(
-               CharsToIndices(c->left), CharsToIndices(c->right))) << ">";
+        << EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
+                                               CharsToIndices(c->right)))
+        << ">";
     EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
                                                       CharsToLines(c->right)))
         << "Left <" << c->left << "> Right <" << c->right << "> Diff <"
@@ -3588,8 +3547,7 @@ TEST(EditDistance, TestSuites) {
 TEST(AssertionTest, EqFailure) {
   const std::string foo_val("5"), bar_val("6");
   const std::string msg1(
-      EqFailure("foo", "bar", foo_val, bar_val, false)
-      .failure_message());
+      EqFailure("foo", "bar", foo_val, bar_val, false).failure_message());
   EXPECT_STREQ(
       "Expected equality of these values:\n"
       "  foo\n"
@@ -3599,8 +3557,7 @@ TEST(AssertionTest, EqFailure) {
       msg1.c_str());
 
   const std::string msg2(
-      EqFailure("foo", "6", foo_val, bar_val, false)
-      .failure_message());
+      EqFailure("foo", "6", foo_val, bar_val, false).failure_message());
   EXPECT_STREQ(
       "Expected equality of these values:\n"
       "  foo\n"
@@ -3609,8 +3566,7 @@ TEST(AssertionTest, EqFailure) {
       msg2.c_str());
 
   const std::string msg3(
-      EqFailure("5", "bar", foo_val, bar_val, false)
-      .failure_message());
+      EqFailure("5", "bar", foo_val, bar_val, false).failure_message());
   EXPECT_STREQ(
       "Expected equality of these values:\n"
       "  5\n"
@@ -3627,9 +3583,8 @@ TEST(AssertionTest, EqFailure) {
       msg4.c_str());
 
   const std::string msg5(
-      EqFailure("foo", "bar",
-                std::string("\"x\""), std::string("\"y\""),
-                true).failure_message());
+      EqFailure("foo", "bar", std::string("\"x\""), std::string("\"y\""), true)
+          .failure_message());
   EXPECT_STREQ(
       "Expected equality of these values:\n"
       "  foo\n"
@@ -3664,24 +3619,21 @@ TEST(AssertionTest, AppendUserMessage) {
   const std::string foo("foo");
 
   Message msg;
-  EXPECT_STREQ("foo",
-               AppendUserMessage(foo, msg).c_str());
+  EXPECT_STREQ("foo", AppendUserMessage(foo, msg).c_str());
 
   msg << "bar";
-  EXPECT_STREQ("foo\nbar",
-               AppendUserMessage(foo, msg).c_str());
+  EXPECT_STREQ("foo\nbar", AppendUserMessage(foo, msg).c_str());
 }
 
 #ifdef __BORLANDC__
 // Silences warnings: "Condition is always true", "Unreachable code"
-# pragma option push -w-ccc -w-rch
+#pragma option push -w-ccc -w-rch
 #endif
 
 // Tests ASSERT_TRUE.
 TEST(AssertionTest, ASSERT_TRUE) {
   ASSERT_TRUE(2 > 1);  // NOLINT
-  EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
-                       "2 < 1");
+  EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1), "2 < 1");
 }
 
 // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
@@ -3729,7 +3681,7 @@ TEST(AssertionTest, AssertFalseWithAssertionResult) {
 
 #ifdef __BORLANDC__
 // Restores warnings after previous "#pragma option push" suppressed them
-# pragma option pop
+#pragma option pop
 #endif
 
 // Tests using ASSERT_EQ on double values.  The purpose is to make
@@ -3740,18 +3692,19 @@ TEST(ExpectTest, ASSERT_EQ_Double) {
   ASSERT_EQ(5.6, 5.6);
 
   // A failure.
-  EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
-                       "5.1");
+  EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), "5.1");
 }
 
 // Tests ASSERT_EQ.
 TEST(AssertionTest, ASSERT_EQ) {
   ASSERT_EQ(5, 2 + 3);
+  // clang-format off
   EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
                        "Expected equality of these values:\n"
                        "  5\n"
                        "  2*3\n"
                        "    Which is: 6");
+  // clang-format on
 }
 
 // Tests ASSERT_EQ(NULL, pointer).
@@ -3776,8 +3729,7 @@ TEST(ExpectTest, ASSERT_EQ_0) {
   ASSERT_EQ(0, n);
 
   // A failure.
-  EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
-                       "  0\n  5.6");
+  EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6), "  0\n  5.6");
 }
 
 // Tests ASSERT_NE.
@@ -3792,30 +3744,26 @@ TEST(AssertionTest, ASSERT_NE) {
 TEST(AssertionTest, ASSERT_LE) {
   ASSERT_LE(2, 3);
   ASSERT_LE(2, 2);
-  EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
-                       "Expected: (2) <= (0), actual: 2 vs 0");
+  EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0), "Expected: (2) <= (0), actual: 2 vs 0");
 }
 
 // Tests ASSERT_LT.
 TEST(AssertionTest, ASSERT_LT) {
   ASSERT_LT(2, 3);
-  EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
-                       "Expected: (2) < (2), actual: 2 vs 2");
+  EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2), "Expected: (2) < (2), actual: 2 vs 2");
 }
 
 // Tests ASSERT_GE.
 TEST(AssertionTest, ASSERT_GE) {
   ASSERT_GE(2, 1);
   ASSERT_GE(2, 2);
-  EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
-                       "Expected: (2) >= (3), actual: 2 vs 3");
+  EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3), "Expected: (2) >= (3), actual: 2 vs 3");
 }
 
 // Tests ASSERT_GT.
 TEST(AssertionTest, ASSERT_GT) {
   ASSERT_GT(2, 1);
-  EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
-                       "Expected: (2) > (2), actual: 2 vs 2");
+  EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2), "Expected: (2) > (2), actual: 2 vs 2");
 }
 
 #if GTEST_HAS_EXCEPTIONS
@@ -3826,7 +3774,7 @@ void ThrowNothing() {}
 TEST(AssertionTest, ASSERT_THROW) {
   ASSERT_THROW(ThrowAnInteger(), int);
 
-# ifndef __BORLANDC__
+#ifndef __BORLANDC__
 
   // ICE's in C++Builder 2007 and 2009.
   EXPECT_FATAL_FAILURE(
@@ -3837,9 +3785,10 @@ TEST(AssertionTest, ASSERT_THROW) {
       ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error),
       "Expected: ThrowRuntimeError(\"A description\") "
       "throws an exception of type std::logic_error.\n  "
-      "Actual: it throws " ERROR_DESC " "
+      "Actual: it throws " ERROR_DESC
+      " "
       "with description \"A description\".");
-# endif
+#endif
 
   EXPECT_FATAL_FAILURE(
       ASSERT_THROW(ThrowNothing(), bool),
@@ -3856,17 +3805,17 @@ TEST(AssertionTest, ASSERT_NO_THROW) {
   EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")),
                        "Expected: ThrowRuntimeError(\"A description\") "
                        "doesn't throw an exception.\n  "
-                       "Actual: it throws " ERROR_DESC " "
+                       "Actual: it throws " ERROR_DESC
+                       " "
                        "with description \"A description\".");
 }
 
 // Tests ASSERT_ANY_THROW.
 TEST(AssertionTest, ASSERT_ANY_THROW) {
   ASSERT_ANY_THROW(ThrowAnInteger());
-  EXPECT_FATAL_FAILURE(
-      ASSERT_ANY_THROW(ThrowNothing()),
-      "Expected: ThrowNothing() throws an exception.\n"
-      "  Actual: it doesn't.");
+  EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()),
+                       "Expected: ThrowNothing() throws an exception.\n"
+                       "  Actual: it doesn't.");
 }
 
 #endif  // GTEST_HAS_EXCEPTIONS
@@ -3880,14 +3829,11 @@ TEST(AssertionTest, AssertPrecedence) {
 }
 
 // A subroutine used by the following test.
-void TestEq1(int x) {
-  ASSERT_EQ(1, x);
-}
+void TestEq1(int x) { ASSERT_EQ(1, x); }
 
 // Tests calling a test subroutine that's not part of a fixture.
 TEST(AssertionTest, NonFixtureSubroutine) {
-  EXPECT_FATAL_FAILURE(TestEq1(2),
-                       "  x\n    Which is: 2");
+  EXPECT_FATAL_FAILURE(TestEq1(2), "  x\n    Which is: 2");
 }
 
 // An uncopyable class.
@@ -3899,6 +3845,7 @@ class Uncopyable {
   bool operator==(const Uncopyable& rhs) const {
     return value() == rhs.value();
   }
+
  private:
   // This constructor deliberately has no implementation, as we don't
   // want this class to be copyable.
@@ -3911,10 +3858,7 @@ class Uncopyable {
   return os << value.value();
 }
 
-
-bool IsPositiveUncopyable(const Uncopyable& x) {
-  return x.value() > 0;
-}
+bool IsPositiveUncopyable(const Uncopyable& x) { return x.value() > 0; }
 
 // A subroutine used by the following test.
 void TestAssertNonPositive() {
@@ -3933,8 +3877,9 @@ TEST(AssertionTest, AssertWorksWithUncopyableObject) {
   Uncopyable x(5);
   ASSERT_PRED1(IsPositiveUncopyable, x);
   ASSERT_EQ(x, x);
-  EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
-    "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
+  EXPECT_FATAL_FAILURE(
+      TestAssertNonPositive(),
+      "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
   EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
                        "Expected equality of these values:\n"
                        "  x\n    Which is: 5\n  y\n    Which is: -1");
@@ -3945,18 +3890,16 @@ TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
   Uncopyable x(5);
   EXPECT_PRED1(IsPositiveUncopyable, x);
   Uncopyable y(-1);
-  EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
-    "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
+  EXPECT_NONFATAL_FAILURE(
+      EXPECT_PRED1(IsPositiveUncopyable, y),
+      "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
   EXPECT_EQ(x, x);
   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
                           "Expected equality of these values:\n"
                           "  x\n    Which is: 5\n  y\n    Which is: -1");
 }
 
-enum NamedEnum {
-  kE1 = 0,
-  kE2 = 1
-};
+enum NamedEnum { kE1 = 0, kE2 = 1 };
 
 TEST(AssertionTest, NamedEnum) {
   EXPECT_EQ(kE1, kE1);
@@ -3972,7 +3915,7 @@ TEST(AssertionTest, NamedEnum) {
 enum {
   kCaseA = -1,
 
-# if GTEST_OS_LINUX
+#if GTEST_OS_LINUX
 
   // We want to test the case where the size of the anonymous enum is
   // larger than sizeof(int), to make sure our implementation of the
@@ -3985,21 +3928,21 @@ enum {
   // assertions.
   kCaseB = testing::internal::kMaxBiggestInt,
 
-# else
+#else
 
   kCaseB = INT_MAX,
 
-# endif  // GTEST_OS_LINUX
+#endif  // GTEST_OS_LINUX
 
   kCaseC = 42
 };
 
 TEST(AssertionTest, AnonymousEnum) {
-# if GTEST_OS_LINUX
+#if GTEST_OS_LINUX
 
   EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
 
-# endif  // GTEST_OS_LINUX
+#endif  // GTEST_OS_LINUX
 
   EXPECT_EQ(kCaseA, kCaseA);
   EXPECT_NE(kCaseA, kCaseB);
@@ -4007,10 +3950,8 @@ TEST(AssertionTest, AnonymousEnum) {
   EXPECT_LE(kCaseA, kCaseB);
   EXPECT_GT(kCaseB, kCaseA);
   EXPECT_GE(kCaseA, kCaseA);
-  EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
-                          "(kCaseA) >= (kCaseB)");
-  EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
-                          "-1 vs 42");
+  EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB), "(kCaseA) >= (kCaseB)");
+  EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC), "-1 vs 42");
 
   ASSERT_EQ(kCaseA, kCaseA);
   ASSERT_NE(kCaseA, kCaseB);
@@ -4019,34 +3960,25 @@ TEST(AssertionTest, AnonymousEnum) {
   ASSERT_GT(kCaseB, kCaseA);
   ASSERT_GE(kCaseA, kCaseA);
 
-# ifndef __BORLANDC__
+#ifndef __BORLANDC__
 
   // ICE's in C++Builder.
-  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
-                       "  kCaseB\n    Which is: ");
-  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
-                       "\n    Which is: 42");
-# endif
+  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), "  kCaseB\n    Which is: ");
+  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n    Which is: 42");
+#endif
 
-  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
-                       "\n    Which is: -1");
+  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n    Which is: -1");
 }
 
 #endif  // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
 
 #if GTEST_OS_WINDOWS
 
-static HRESULT UnexpectedHRESULTFailure() {
-  return E_UNEXPECTED;
-}
+static HRESULT UnexpectedHRESULTFailure() { return E_UNEXPECTED; }
 
-static HRESULT OkHRESULTSuccess() {
-  return S_OK;
-}
+static HRESULT OkHRESULTSuccess() { return S_OK; }
 
-static HRESULT FalseHRESULTSuccess() {
-  return S_FALSE;
-}
+static HRESULT FalseHRESULTSuccess() { return S_FALSE; }
 
 // HRESULT assertion tests test both zero and non-zero
 // success codes as well as failure message for each.
@@ -4057,8 +3989,8 @@ TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
   EXPECT_HRESULT_SUCCEEDED(S_FALSE);
 
   EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
-    "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
-    "  Actual: 0x8000FFFF");
+                          "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
+                          "  Actual: 0x8000FFFF");
 }
 
 TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
@@ -4066,35 +3998,35 @@ TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
   ASSERT_HRESULT_SUCCEEDED(S_FALSE);
 
   EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
-    "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
-    "  Actual: 0x8000FFFF");
+                       "Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
+                       "  Actual: 0x8000FFFF");
 }
 
 TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
   EXPECT_HRESULT_FAILED(E_UNEXPECTED);
 
   EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
-    "Expected: (OkHRESULTSuccess()) fails.\n"
-    "  Actual: 0x0");
+                          "Expected: (OkHRESULTSuccess()) fails.\n"
+                          "  Actual: 0x0");
   EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
-    "Expected: (FalseHRESULTSuccess()) fails.\n"
-    "  Actual: 0x1");
+                          "Expected: (FalseHRESULTSuccess()) fails.\n"
+                          "  Actual: 0x1");
 }
 
 TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
   ASSERT_HRESULT_FAILED(E_UNEXPECTED);
 
-# ifndef __BORLANDC__
+#ifndef __BORLANDC__
 
   // ICE's in C++Builder 2007 and 2009.
   EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
-    "Expected: (OkHRESULTSuccess()) fails.\n"
-    "  Actual: 0x0");
-# endif
+                       "Expected: (OkHRESULTSuccess()) fails.\n"
+                       "  Actual: 0x0");
+#endif
 
   EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
-    "Expected: (FalseHRESULTSuccess()) fails.\n"
-    "  Actual: 0x1");
+                       "Expected: (FalseHRESULTSuccess()) fails.\n"
+                       "  Actual: 0x1");
 }
 
 // Tests that streaming to the HRESULT macros works.
@@ -4104,25 +4036,23 @@ TEST(HRESULTAssertionTest, Streaming) {
   EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
   ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
 
-  EXPECT_NONFATAL_FAILURE(
-      EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
-      "expected failure");
+  EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED)
+                              << "expected failure",
+                          "expected failure");
 
-# ifndef __BORLANDC__
+#ifndef __BORLANDC__
 
   // ICE's in C++Builder 2007 and 2009.
-  EXPECT_FATAL_FAILURE(
-      ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
-      "expected failure");
-# endif
+  EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED)
+                           << "expected failure",
+                       "expected failure");
+#endif
 
-  EXPECT_NONFATAL_FAILURE(
-      EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
-      "expected failure");
+  EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
+                          "expected failure");
 
-  EXPECT_FATAL_FAILURE(
-      ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
-      "expected failure");
+  EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
+                       "expected failure");
 }
 
 #endif  // GTEST_OS_WINDOWS
@@ -4145,8 +4075,7 @@ TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
   else
     ;  // NOLINT
 
-  if (AlwaysFalse())
-    ASSERT_LT(1, 3);
+  if (AlwaysFalse()) ASSERT_LT(1, 3);
 
   if (AlwaysFalse())
     ;  // NOLINT
@@ -4184,24 +4113,21 @@ TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) {
 #pragma GCC diagnostic ignored "-Wpragmas"
 #endif
 TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
-  if (AlwaysFalse())
-    EXPECT_THROW(ThrowNothing(), bool);
+  if (AlwaysFalse()) EXPECT_THROW(ThrowNothing(), bool);
 
   if (AlwaysTrue())
     EXPECT_THROW(ThrowAnInteger(), int);
   else
     ;  // NOLINT
 
-  if (AlwaysFalse())
-    EXPECT_NO_THROW(ThrowAnInteger());
+  if (AlwaysFalse()) EXPECT_NO_THROW(ThrowAnInteger());
 
   if (AlwaysTrue())
     EXPECT_NO_THROW(ThrowNothing());
   else
     ;  // NOLINT
 
-  if (AlwaysFalse())
-    EXPECT_ANY_THROW(ThrowNothing());
+  if (AlwaysFalse()) EXPECT_ANY_THROW(ThrowNothing());
 
   if (AlwaysTrue())
     EXPECT_ANY_THROW(ThrowAnInteger());
@@ -4257,8 +4183,8 @@ TEST(AssertionSyntaxTest, WorksWithSwitch) {
   }
 
   switch (0)
-    case 0:
-      EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
+  case 0:
+    EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
 
   // Binary assertions are implemented using a different code path
   // than the Boolean assertions.  Hence we test them separately.
@@ -4269,22 +4195,20 @@ TEST(AssertionSyntaxTest, WorksWithSwitch) {
   }
 
   switch (0)
-    case 0:
-      EXPECT_NE(1, 2);
+  case 0:
+    EXPECT_NE(1, 2);
 }
 
 #if GTEST_HAS_EXCEPTIONS
 
-void ThrowAString() {
-    throw "std::string";
-}
+void ThrowAString() { throw "std::string"; }
 
 // Test that the exception assertion macros compile and work with const
 // type qualifier.
 TEST(AssertionSyntaxTest, WorksWithConst) {
-    ASSERT_THROW(ThrowAString(), const char*);
+  ASSERT_THROW(ThrowAString(), const char*);
 
-    EXPECT_THROW(ThrowAString(), const char*);
+  EXPECT_THROW(ThrowAString(), const char*);
 }
 
 #endif  // GTEST_HAS_EXCEPTIONS
@@ -4382,22 +4306,19 @@ TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
 // Tests using ASSERT_FALSE with a streamed message.
 TEST(AssertionWithMessageTest, ASSERT_FALSE) {
   ASSERT_FALSE(false) << "This shouldn't fail.";
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
-                       << " evaluates to " << true;
-  }, "Expected failure");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
+                           << " evaluates to " << true;
+      },
+      "Expected failure");
 }
 
 // Tests using FAIL with a streamed message.
-TEST(AssertionWithMessageTest, FAIL) {
-  EXPECT_FATAL_FAILURE(FAIL() << 0,
-                       "0");
-}
+TEST(AssertionWithMessageTest, FAIL) { EXPECT_FATAL_FAILURE(FAIL() << 0, "0"); }
 
 // Tests using SUCCEED with a streamed message.
-TEST(AssertionWithMessageTest, SUCCEED) {
-  SUCCEED() << "Success == " << 1;
-}
+TEST(AssertionWithMessageTest, SUCCEED) { SUCCEED() << "Success == " << 1; }
 
 // Tests using ASSERT_TRUE with a streamed message.
 TEST(AssertionWithMessageTest, ASSERT_TRUE) {
@@ -4414,13 +4335,16 @@ TEST(AssertionWithMessageTest, ASSERT_TRUE) {
 #if GTEST_OS_WINDOWS
 // Tests using wide strings in assertion messages.
 TEST(AssertionWithMessageTest, WideStringMessage) {
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_TRUE(false) << L"This failure is expected.\x8119";
-  }, "This failure is expected.");
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_EQ(1, 2) << "This failure is "
-                    << L"expected too.\x8120";
-  }, "This failure is expected too.");
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_TRUE(false) << L"This failure is expected.\x8119";
+      },
+      "This failure is expected.");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_EQ(1, 2) << "This failure is " << L"expected too.\x8120";
+      },
+      "This failure is expected too.");
 }
 #endif  // GTEST_OS_WINDOWS
 
@@ -4436,8 +4360,7 @@ TEST(ExpectTest, EXPECT_TRUE) {
                           "Value of: 2 < 1\n"
                           "  Actual: false\n"
                           "Expected: true");
-  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
-                          "2 > 3");
+  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3), "2 > 3");
 }
 
 // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
@@ -4466,8 +4389,7 @@ TEST(ExpectTest, EXPECT_FALSE) {
                           "Value of: 2 > 1\n"
                           "  Actual: true\n"
                           "Expected: false");
-  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
-                          "2 < 3");
+  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3), "2 < 3");
 }
 
 // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
@@ -4486,19 +4408,20 @@ TEST(ExpectTest, ExpectFalseWithAssertionResult) {
 
 #ifdef __BORLANDC__
 // Restores warnings after previous "#pragma option push" suppressed them
-# pragma option pop
+#pragma option pop
 #endif
 
 // Tests EXPECT_EQ.
 TEST(ExpectTest, EXPECT_EQ) {
   EXPECT_EQ(5, 2 + 3);
+  // clang-format off
   EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
                           "Expected equality of these values:\n"
                           "  5\n"
                           "  2*3\n"
                           "    Which is: 6");
-  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
-                          "2 - 3");
+  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3), "2 - 3");
+  // clang-format on
 }
 
 // Tests using EXPECT_EQ on double values.  The purpose is to make
@@ -4509,8 +4432,7 @@ TEST(ExpectTest, EXPECT_EQ_Double) {
   EXPECT_EQ(5.6, 5.6);
 
   // A failure.
-  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
-                          "5.1");
+  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), "5.1");
 }
 
 // Tests EXPECT_EQ(NULL, pointer).
@@ -4535,8 +4457,7 @@ TEST(ExpectTest, EXPECT_EQ_0) {
   EXPECT_EQ(0, n);
 
   // A failure.
-  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
-                          "  0\n  5.6");
+  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6), "  0\n  5.6");
 }
 
 // Tests EXPECT_NE.
@@ -4546,19 +4467,16 @@ TEST(ExpectTest, EXPECT_NE) {
   EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
                           "Expected: ('a') != ('a'), "
                           "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
-  EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
-                          "2");
+  EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2), "2");
   char* const p0 = nullptr;
-  EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
-                          "p0");
+  EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0), "p0");
   // Only way to get the Nokia compiler to compile the cast
   // is to have a separate void* variable first. Putting
   // the two casts on the same line doesn't work, neither does
   // a direct C-style to char*.
   void* pv1 = (void*)0x1234;  // NOLINT
   char* const p1 = reinterpret_cast<char*>(pv1);
-  EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
-                          "p1");
+  EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), "p1");
 }
 
 // Tests EXPECT_LE.
@@ -4567,8 +4485,7 @@ TEST(ExpectTest, EXPECT_LE) {
   EXPECT_LE(2, 2);
   EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
                           "Expected: (2) <= (0), actual: 2 vs 0");
-  EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
-                          "(1.1) <= (0.9)");
+  EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9), "(1.1) <= (0.9)");
 }
 
 // Tests EXPECT_LT.
@@ -4576,8 +4493,7 @@ TEST(ExpectTest, EXPECT_LT) {
   EXPECT_LT(2, 3);
   EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
                           "Expected: (2) < (2), actual: 2 vs 2");
-  EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
-                          "(2) < (1)");
+  EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1), "(2) < (1)");
 }
 
 // Tests EXPECT_GE.
@@ -4586,8 +4502,7 @@ TEST(ExpectTest, EXPECT_GE) {
   EXPECT_GE(2, 2);
   EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
                           "Expected: (2) >= (3), actual: 2 vs 3");
-  EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
-                          "(0.9) >= (1.1)");
+  EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1), "(0.9) >= (1.1)");
 }
 
 // Tests EXPECT_GT.
@@ -4595,8 +4510,7 @@ TEST(ExpectTest, EXPECT_GT) {
   EXPECT_GT(2, 1);
   EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
                           "Expected: (2) > (2), actual: 2 vs 2");
-  EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
-                          "(2) > (3)");
+  EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3), "(2) > (3)");
 }
 
 #if GTEST_HAS_EXCEPTIONS
@@ -4607,12 +4521,13 @@ TEST(ExpectTest, EXPECT_THROW) {
   EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
                           "Expected: ThrowAnInteger() throws an exception of "
                           "type bool.\n  Actual: it throws a different type.");
-  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowRuntimeError("A description"),
-                                       std::logic_error),
-                          "Expected: ThrowRuntimeError(\"A description\") "
-                          "throws an exception of type std::logic_error.\n  "
-                          "Actual: it throws " ERROR_DESC " "
-                          "with description \"A description\".");
+  EXPECT_NONFATAL_FAILURE(
+      EXPECT_THROW(ThrowRuntimeError("A description"), std::logic_error),
+      "Expected: ThrowRuntimeError(\"A description\") "
+      "throws an exception of type std::logic_error.\n  "
+      "Actual: it throws " ERROR_DESC
+      " "
+      "with description \"A description\".");
   EXPECT_NONFATAL_FAILURE(
       EXPECT_THROW(ThrowNothing(), bool),
       "Expected: ThrowNothing() throws an exception of type bool.\n"
@@ -4628,17 +4543,17 @@ TEST(ExpectTest, EXPECT_NO_THROW) {
   EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")),
                           "Expected: ThrowRuntimeError(\"A description\") "
                           "doesn't throw an exception.\n  "
-                          "Actual: it throws " ERROR_DESC " "
+                          "Actual: it throws " ERROR_DESC
+                          " "
                           "with description \"A description\".");
 }
 
 // Tests EXPECT_ANY_THROW.
 TEST(ExpectTest, EXPECT_ANY_THROW) {
   EXPECT_ANY_THROW(ThrowAnInteger());
-  EXPECT_NONFATAL_FAILURE(
-      EXPECT_ANY_THROW(ThrowNothing()),
-      "Expected: ThrowNothing() throws an exception.\n"
-      "  Actual: it doesn't.");
+  EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()),
+                          "Expected: ThrowNothing() throws an exception.\n"
+                          "  Actual: it doesn't.");
 }
 
 #endif  // GTEST_HAS_EXCEPTIONS
@@ -4650,7 +4565,6 @@ TEST(ExpectTest, ExpectPrecedence) {
                           "  true && false\n    Which is: false");
 }
 
-
 // Tests the StreamableToString() function.
 
 // Tests using StreamableToString() on a scalar.
@@ -4688,8 +4602,7 @@ TEST(StreamableToStringTest, NullCString) {
 TEST(StreamableTest, string) {
   static const std::string str(
       "This failure message is a std::string, and is expected.");
-  EXPECT_FATAL_FAILURE(FAIL() << str,
-                       str.c_str());
+  EXPECT_FATAL_FAILURE(FAIL() << str, str.c_str());
 }
 
 // Tests that we can output strings containing embedded NULs.
@@ -4697,25 +4610,24 @@ TEST(StreamableTest, string) {
 TEST(StreamableTest, stringWithEmbeddedNUL) {
   static const char char_array_with_nul[] =
       "Here's a NUL\0 and some more string";
-  static const std::string string_with_nul(char_array_with_nul,
-                                           sizeof(char_array_with_nul)
-                                           - 1);  // drops the trailing NUL
+  static const std::string string_with_nul(
+      char_array_with_nul,
+      sizeof(char_array_with_nul) - 1);  // drops the trailing NUL
   EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
                        "Here's a NUL\\0 and some more string");
 }
 
 // Tests that we can output a NUL char.
 TEST(StreamableTest, NULChar) {
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    FAIL() << "A NUL" << '\0' << " and some more string";
-  }, "A NUL\\0 and some more string");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        FAIL() << "A NUL" << '\0' << " and some more string";
+      },
+      "A NUL\\0 and some more string");
 }
 
 // Tests using int as an assertion message.
-TEST(StreamableTest, int) {
-  EXPECT_FATAL_FAILURE(FAIL() << 900913,
-                       "900913");
-}
+TEST(StreamableTest, int) { EXPECT_FATAL_FAILURE(FAIL() << 900913, "900913"); }
 
 // Tests using NULL char pointer as an assertion message.
 //
@@ -4729,10 +4641,12 @@ TEST(StreamableTest, NullCharPtr) {
 // Tests that basic IO manipulators (endl, ends, and flush) can be
 // streamed to testing::Message.
 TEST(StreamableTest, BasicIoManip) {
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    FAIL() << "Line 1." << std::endl
-           << "A NUL char " << std::ends << std::flush << " in line 2.";
-  }, "Line 1.\nA NUL char \\0 in line 2.");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        FAIL() << "Line 1." << std::endl
+               << "A NUL char " << std::ends << std::flush << " in line 2.";
+      },
+      "Line 1.\nA NUL char \\0 in line 2.");
 }
 
 // Tests the macros that haven't been covered so far.
@@ -4746,8 +4660,7 @@ void AddFailureHelper(bool* aborted) {
 // Tests ADD_FAILURE.
 TEST(MacroTest, ADD_FAILURE) {
   bool aborted = true;
-  EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
-                          "Intentional failure.");
+  EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted), "Intentional failure.");
   EXPECT_FALSE(aborted);
 }
 
@@ -4768,8 +4681,7 @@ TEST(MacroTest, ADD_FAILURE_AT) {
 
 // Tests FAIL.
 TEST(MacroTest, FAIL) {
-  EXPECT_FATAL_FAILURE(FAIL(),
-                       "Failed");
+  EXPECT_FATAL_FAILURE(FAIL(), "Failed");
   EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
                        "Intentional failure.");
 }
@@ -4802,37 +4714,34 @@ TEST(MacroTest, SUCCEED) {
 
 // Tests using bool values in {EXPECT|ASSERT}_EQ.
 TEST(EqAssertionTest, Bool) {
-  EXPECT_EQ(true,  true);
-  EXPECT_FATAL_FAILURE({
-      bool false_value = false;
-      ASSERT_EQ(false_value, true);
-    }, "  false_value\n    Which is: false\n  true");
+  EXPECT_EQ(true, true);
+  EXPECT_FATAL_FAILURE(
+      {
+        bool false_value = false;
+        ASSERT_EQ(false_value, 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),
-                          "  32\n  33");
+  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33), "  32\n  33");
 }
 
 // Tests using time_t values in {EXPECT|ASSERT}_EQ.
 TEST(EqAssertionTest, Time_T) {
-  EXPECT_EQ(static_cast<time_t>(0),
-            static_cast<time_t>(0));
-  EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
-                                 static_cast<time_t>(1234)),
-                       "1234");
+  EXPECT_EQ(static_cast<time_t>(0), static_cast<time_t>(0));
+  EXPECT_FATAL_FAILURE(
+      ASSERT_EQ(static_cast<time_t>(0), static_cast<time_t>(1234)), "1234");
 }
 
 // Tests using char values in {EXPECT|ASSERT}_EQ.
 TEST(EqAssertionTest, Char) {
   ASSERT_EQ('z', 'z');
   const char ch = 'b';
-  EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
-                          "  ch\n    Which is: 'b'");
-  EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
-                          "  ch\n    Which is: 'b'");
+  EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch), "  ch\n    Which is: 'b'");
+  EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch), "  ch\n    Which is: 'b'");
 }
 
 // Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
@@ -4848,8 +4757,7 @@ TEST(EqAssertionTest, WideChar) {
 
   static wchar_t wchar;
   wchar = L'b';
-  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
-                          "wchar");
+  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar), "wchar");
   wchar = 0x8119;
   EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
                        "  wchar\n    Which is: L'");
@@ -4868,13 +4776,11 @@ TEST(EqAssertionTest, StdString) {
 
   // Compares a const char* to an std::string that has different
   // content
-  EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
-                          "\"test\"");
+  EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")), "\"test\"");
 
   // Compares an std::string to a char* that has different content.
   char* const p1 = const_cast<char*>("foo");
-  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
-                          "p1");
+  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1), "p1");
 
   // Compares two std::strings that have different contents, one of
   // which having a NUL character in the middle.  This should fail.
@@ -4895,28 +4801,31 @@ TEST(EqAssertionTest, StdWideString) {
 
   // Compares an std::wstring to a const wchar_t* that has identical
   // content.
-  const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
+  const wchar_t kTestX8119[] = {'T', 'e', 's', 't', 0x8119, '\0'};
   EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
 
   // Compares an std::wstring to a const wchar_t* that has different
   // content.
-  const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
-  EXPECT_NONFATAL_FAILURE({  // NOLINT
-    EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
-  }, "kTestX8120");
+  const wchar_t kTestX8120[] = {'T', 'e', 's', 't', 0x8120, '\0'};
+  EXPECT_NONFATAL_FAILURE(
+      {  // NOLINT
+        EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
+      },
+      "kTestX8120");
 
   // Compares two std::wstrings that have different contents, one of
   // which having a NUL character in the middle.
   ::std::wstring wstr3(wstr1);
   wstr3.at(2) = L'\0';
-  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
-                          "wstr3");
+  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3), "wstr3");
 
   // Compares a wchar_t* to an std::wstring that has different
   // content.
-  EXPECT_FATAL_FAILURE({  // NOLINT
-    ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
-  }, "");
+  EXPECT_FATAL_FAILURE(
+      {  // NOLINT
+        ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
+      },
+      "");
 }
 
 #endif  // GTEST_HAS_STD_WSTRING
@@ -4934,10 +4843,8 @@ TEST(EqAssertionTest, CharPointer) {
   char* const p2 = reinterpret_cast<char*>(pv2);
   ASSERT_EQ(p1, p1);
 
-  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
-                          "  p2\n    Which is:");
-  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
-                          "  p2\n    Which is:");
+  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), "  p2\n    Which is:");
+  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), "  p2\n    Which is:");
   EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
                                  reinterpret_cast<char*>(0xABC0)),
                        "ABC0");
@@ -4956,16 +4863,13 @@ TEST(EqAssertionTest, WideCharPointer) {
   wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
   EXPECT_EQ(p0, p0);
 
-  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
-                          "  p2\n    Which is:");
-  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
-                          "  p2\n    Which is:");
+  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), "  p2\n    Which is:");
+  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, 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);
   const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
-  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
-                          "p4");
+  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4), "p4");
 }
 
 // Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
@@ -4987,15 +4891,11 @@ class UnprintableChar {
   bool operator!=(const UnprintableChar& rhs) const {
     return char_ != rhs.char_;
   }
-  bool operator<(const UnprintableChar& rhs) const {
-    return char_ < rhs.char_;
-  }
+  bool operator<(const UnprintableChar& rhs) const { return char_ < rhs.char_; }
   bool operator<=(const UnprintableChar& rhs) const {
     return char_ <= rhs.char_;
   }
-  bool operator>(const UnprintableChar& rhs) const {
-    return char_ > rhs.char_;
-  }
+  bool operator>(const UnprintableChar& rhs) const { return char_ > rhs.char_; }
   bool operator>=(const UnprintableChar& rhs) const {
     return char_ >= rhs.char_;
   }
@@ -5057,9 +4957,7 @@ class Foo {
 
 // Tests that the FRIEND_TEST declaration allows a TEST to access a
 // class's private members.  This should compile.
-TEST(FRIEND_TEST_Test, TEST) {
-  ASSERT_EQ(1, Foo().Bar());
-}
+TEST(FRIEND_TEST_Test, TEST) { ASSERT_EQ(1, Foo().Bar()); }
 
 // The fixture needed to test using FRIEND_TEST with TEST_F.
 class FRIEND_TEST_Test2 : public Test {
@@ -5069,9 +4967,7 @@ class FRIEND_TEST_Test2 : public Test {
 
 // Tests that the FRIEND_TEST declaration allows a TEST_F to access a
 // class's private members.  This should compile.
-TEST_F(FRIEND_TEST_Test2, TEST_F) {
-  ASSERT_EQ(1, foo.Bar());
-}
+TEST_F(FRIEND_TEST_Test2, TEST_F) { ASSERT_EQ(1, foo.Bar()); }
 
 // Tests the life cycle of Test objects.
 
@@ -5206,15 +5102,14 @@ class Base {
  public:
   explicit Base(int an_x) : x_(an_x) {}
   int x() const { return x_; }
+
  private:
   int x_;
 };
-std::ostream& operator<<(std::ostream& os,
-                         const Base& val) {
+std::ostream& operator<<(std::ostream& os, const Base& val) {
   return os << val.x();
 }
-std::ostream& operator<<(std::ostream& os,
-                         const Base* pointer) {
+std::ostream& operator<<(std::ostream& os, const Base* pointer) {
   return os << "(" << pointer->x() << ")";
 }
 
@@ -5231,7 +5126,7 @@ TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
 namespace {
 class MyTypeInUnnamedNameSpace : public Base {
  public:
-  explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
+  explicit MyTypeInUnnamedNameSpace(int an_x) : Base(an_x) {}
 };
 std::ostream& operator<<(std::ostream& os,
                          const MyTypeInUnnamedNameSpace& val) {
@@ -5256,14 +5151,12 @@ TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
 namespace namespace1 {
 class MyTypeInNameSpace1 : public Base {
  public:
-  explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
+  explicit MyTypeInNameSpace1(int an_x) : Base(an_x) {}
 };
-std::ostream& operator<<(std::ostream& os,
-                         const MyTypeInNameSpace1& val) {
+std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1& val) {
   return os << val.x();
 }
-std::ostream& operator<<(std::ostream& os,
-                         const MyTypeInNameSpace1* pointer) {
+std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1* pointer) {
   return os << "(" << pointer->x() << ")";
 }
 }  // namespace namespace1
@@ -5281,7 +5174,7 @@ TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
 namespace namespace2 {
 class MyTypeInNameSpace2 : public ::Base {
  public:
-  explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
+  explicit MyTypeInNameSpace2(int an_x) : Base(an_x) {}
 };
 }  // namespace namespace2
 std::ostream& operator<<(std::ostream& os,
@@ -5312,21 +5205,18 @@ TEST(MessageTest, NullPointers) {
   Message* p6 = nullptr;
 
   msg << p1 << p2 << p3 << p4 << p5 << p6;
-  ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
-               msg.GetString().c_str());
+  ASSERT_STREQ("(null)(null)(null)(null)(null)(null)", msg.GetString().c_str());
 }
 
 // Tests streaming wide strings to testing::Message.
 TEST(MessageTest, WideStrings) {
   // Streams a NULL of type const wchar_t*.
   const wchar_t* const_wstr = nullptr;
-  EXPECT_STREQ("(null)",
-               (Message() << const_wstr).GetString().c_str());
+  EXPECT_STREQ("(null)", (Message() << const_wstr).GetString().c_str());
 
   // Streams a NULL of type wchar_t*.
   wchar_t* wstr = nullptr;
-  EXPECT_STREQ("(null)",
-               (Message() << wstr).GetString().c_str());
+  EXPECT_STREQ("(null)", (Message() << wstr).GetString().c_str());
 
   // Streams a non-NULL of type const wchar_t*.
   const_wstr = L"abc\x8119";
@@ -5335,11 +5225,9 @@ TEST(MessageTest, WideStrings) {
 
   // Streams a non-NULL of type wchar_t*.
   wstr = const_cast<wchar_t*>(const_wstr);
-  EXPECT_STREQ("abc\xe8\x84\x99",
-               (Message() << wstr).GetString().c_str());
+  EXPECT_STREQ("abc\xe8\x84\x99", (Message() << wstr).GetString().c_str());
 }
 
-
 // This line tests that we can define tests in the testing namespace.
 namespace testing {
 
@@ -5353,14 +5241,12 @@ class TestInfoTest : public Test {
 
     for (int i = 0; i < test_suite->total_test_count(); ++i) {
       const TestInfo* const test_info = test_suite->GetTestInfo(i);
-      if (strcmp(test_name, test_info->name()) == 0)
-        return test_info;
+      if (strcmp(test_name, test_info->name()) == 0) return test_info;
     }
     return nullptr;
   }
 
-  static const TestResult* GetTestResult(
-      const TestInfo* test_info) {
+  static const TestResult* GetTestResult(const TestInfo* test_info) {
     return test_info->result();
   }
 };
@@ -5384,26 +5270,25 @@ TEST_F(TestInfoTest, result) {
   ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
 }
 
-#define VERIFY_CODE_LOCATION \
-  const int expected_line = __LINE__ - 1; \
+#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()); \
+  ASSERT_TRUE(test_info);                                                   \
+  EXPECT_STREQ(__FILE__, test_info->file());                                \
   EXPECT_EQ(expected_line, test_info->line())
 
+// clang-format off
 TEST(CodeLocationForTEST, Verify) {
   VERIFY_CODE_LOCATION;
 }
 
-class CodeLocationForTESTF : public Test {
-};
+class CodeLocationForTESTF : public Test {};
 
 TEST_F(CodeLocationForTESTF, Verify) {
   VERIFY_CODE_LOCATION;
 }
 
-class CodeLocationForTESTP : public TestWithParam<int> {
-};
+class CodeLocationForTESTP : public TestWithParam<int> {};
 
 TEST_P(CodeLocationForTESTP, Verify) {
   VERIFY_CODE_LOCATION;
@@ -5412,8 +5297,7 @@ TEST_P(CodeLocationForTESTP, Verify) {
 INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0));
 
 template <typename T>
-class CodeLocationForTYPEDTEST : public Test {
-};
+class CodeLocationForTYPEDTEST : public Test {};
 
 TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int);
 
@@ -5422,8 +5306,7 @@ TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
 }
 
 template <typename T>
-class CodeLocationForTYPEDTESTP : public Test {
-};
+class CodeLocationForTYPEDTESTP : public Test {};
 
 TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP);
 
@@ -5436,6 +5319,7 @@ REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify);
 INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int);
 
 #undef VERIFY_CODE_LOCATION
+// clang-format on
 
 // Tests setting up and tearing down a test case.
 // Legacy API is deprecated but still available
@@ -5495,9 +5379,7 @@ const char* SetUpTestCaseTest::shared_resource_ = nullptr;
 TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); }
 
 // Another test that uses the shared resource.
-TEST_F(SetUpTestCaseTest, Test2) {
-  EXPECT_STREQ("123", shared_resource_);
-}
+TEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ("123", shared_resource_); }
 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
 
 // Tests SetupTestSuite/TearDown TestSuite
@@ -5580,6 +5462,7 @@ struct Flags {
         print_time(true),
         random_seed(0),
         repeat(1),
+        recreate_environments_when_repeating(true),
         shuffle(false),
         stack_trace_depth(kMaxStackTraceDepth),
         stream_result_to(""),
@@ -5683,6 +5566,16 @@ struct Flags {
     return flags;
   }
 
+  // Creates a Flags struct where the gtest_recreate_environments_when_repeating
+  // flag has the given value.
+  static Flags RecreateEnvironmentsWhenRepeating(
+      bool recreate_environments_when_repeating) {
+    Flags flags;
+    flags.recreate_environments_when_repeating =
+        recreate_environments_when_repeating;
+    return flags;
+  }
+
   // Creates a Flags struct where the gtest_shuffle flag has the given
   // value.
   static Flags Shuffle(bool shuffle) {
@@ -5728,6 +5621,7 @@ struct Flags {
   bool print_time;
   int32_t random_seed;
   int32_t repeat;
+  bool recreate_environments_when_repeating;
   bool shuffle;
   int32_t stack_trace_depth;
   const char* stream_result_to;
@@ -5739,22 +5633,23 @@ class ParseFlagsTest : public Test {
  protected:
   // Clears the flags before each test.
   void SetUp() override {
-    GTEST_FLAG(also_run_disabled_tests) = false;
-    GTEST_FLAG(break_on_failure) = false;
-    GTEST_FLAG(catch_exceptions) = false;
-    GTEST_FLAG(death_test_use_fork) = false;
-    GTEST_FLAG(fail_fast) = false;
-    GTEST_FLAG(filter) = "";
-    GTEST_FLAG(list_tests) = false;
-    GTEST_FLAG(output) = "";
-    GTEST_FLAG(brief) = false;
-    GTEST_FLAG(print_time) = true;
-    GTEST_FLAG(random_seed) = 0;
-    GTEST_FLAG(repeat) = 1;
-    GTEST_FLAG(shuffle) = false;
-    GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth;
-    GTEST_FLAG(stream_result_to) = "";
-    GTEST_FLAG(throw_on_failure) = false;
+    GTEST_FLAG_SET(also_run_disabled_tests, false);
+    GTEST_FLAG_SET(break_on_failure, false);
+    GTEST_FLAG_SET(catch_exceptions, false);
+    GTEST_FLAG_SET(death_test_use_fork, false);
+    GTEST_FLAG_SET(fail_fast, false);
+    GTEST_FLAG_SET(filter, "");
+    GTEST_FLAG_SET(list_tests, false);
+    GTEST_FLAG_SET(output, "");
+    GTEST_FLAG_SET(brief, false);
+    GTEST_FLAG_SET(print_time, true);
+    GTEST_FLAG_SET(random_seed, 0);
+    GTEST_FLAG_SET(repeat, 1);
+    GTEST_FLAG_SET(recreate_environments_when_repeating, true);
+    GTEST_FLAG_SET(shuffle, false);
+    GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
+    GTEST_FLAG_SET(stream_result_to, "");
+    GTEST_FLAG_SET(throw_on_failure, false);
   }
 
   // Asserts that two narrow or wide string arrays are equal.
@@ -5771,45 +5666,48 @@ class ParseFlagsTest : public Test {
   // Verifies that the flag values match the expected values.
   static void CheckFlags(const Flags& expected) {
     EXPECT_EQ(expected.also_run_disabled_tests,
-              GTEST_FLAG(also_run_disabled_tests));
-    EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
-    EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
-    EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
-    EXPECT_EQ(expected.fail_fast, GTEST_FLAG(fail_fast));
-    EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
-    EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
-    EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
-    EXPECT_EQ(expected.brief, GTEST_FLAG(brief));
-    EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
-    EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
-    EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
-    EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle));
-    EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth));
+              GTEST_FLAG_GET(also_run_disabled_tests));
+    EXPECT_EQ(expected.break_on_failure, GTEST_FLAG_GET(break_on_failure));
+    EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG_GET(catch_exceptions));
+    EXPECT_EQ(expected.death_test_use_fork,
+              GTEST_FLAG_GET(death_test_use_fork));
+    EXPECT_EQ(expected.fail_fast, GTEST_FLAG_GET(fail_fast));
+    EXPECT_STREQ(expected.filter, GTEST_FLAG_GET(filter).c_str());
+    EXPECT_EQ(expected.list_tests, GTEST_FLAG_GET(list_tests));
+    EXPECT_STREQ(expected.output, GTEST_FLAG_GET(output).c_str());
+    EXPECT_EQ(expected.brief, GTEST_FLAG_GET(brief));
+    EXPECT_EQ(expected.print_time, GTEST_FLAG_GET(print_time));
+    EXPECT_EQ(expected.random_seed, GTEST_FLAG_GET(random_seed));
+    EXPECT_EQ(expected.repeat, GTEST_FLAG_GET(repeat));
+    EXPECT_EQ(expected.recreate_environments_when_repeating,
+              GTEST_FLAG_GET(recreate_environments_when_repeating));
+    EXPECT_EQ(expected.shuffle, GTEST_FLAG_GET(shuffle));
+    EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG_GET(stack_trace_depth));
     EXPECT_STREQ(expected.stream_result_to,
-                 GTEST_FLAG(stream_result_to).c_str());
-    EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure));
+                 GTEST_FLAG_GET(stream_result_to).c_str());
+    EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG_GET(throw_on_failure));
   }
 
   // Parses a command line (specified by argc1 and argv1), then
   // verifies that the flag values are expected and that the
   // recognized flags are removed from the command line.
   template <typename CharType>
-  static void TestParsingFlags(int argc1, const CharType** argv1,
-                               int argc2, const CharType** argv2,
-                               const Flags& expected, bool should_print_help) {
+  static void TestParsingFlags(int argc1, const CharType** argv1, int argc2,
+                               const CharType** argv2, const Flags& expected,
+                               bool should_print_help) {
     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);
@@ -5822,16 +5720,16 @@ class ParseFlagsTest : 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) {
       EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
     } else {
-      EXPECT_PRED_FORMAT2(IsNotSubstring,
-                          expected_help_fragment, captured_stdout);
+      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;
   }
@@ -5839,10 +5737,10 @@ class ParseFlagsTest : 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) \
-  TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
-                   sizeof(argv2)/sizeof(*argv2) - 1, 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.
@@ -5872,15 +5770,6 @@ TEST_F(ParseFlagsTest, FailFast) {
   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false);
 }
 
-// Tests parsing a bad --gtest_filter flag.
-TEST_F(ParseFlagsTest, FilterBad) {
-  const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
-
-  const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr};
-
-  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
-}
-
 // Tests parsing an empty --gtest_filter flag.
 TEST_F(ParseFlagsTest, FilterEmpty) {
   const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr};
@@ -6033,15 +5922,6 @@ TEST_F(ParseFlagsTest, ListTestsFalse_F) {
   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
 }
 
-// Tests parsing --gtest_output (invalid).
-TEST_F(ParseFlagsTest, OutputEmpty) {
-  const char* argv[] = {"foo.exe", "--gtest_output", nullptr};
-
-  const char* argv2[] = {"foo.exe", "--gtest_output", nullptr};
-
-  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
-}
-
 // Tests parsing --gtest_output=xml
 TEST_F(ParseFlagsTest, OutputXml) {
   const char* argv[] = {"foo.exe", "--gtest_output=xml", nullptr};
@@ -6067,8 +5947,8 @@ TEST_F(ParseFlagsTest, OutputXmlDirectory) {
 
   const char* argv2[] = {"foo.exe", nullptr};
 
-  GTEST_TEST_PARSING_FLAGS_(argv, argv2,
-                            Flags::Output("xml:directory/path/"), false);
+  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/"),
+                            false);
 }
 
 // Tests having a --gtest_brief flag
@@ -6161,6 +6041,20 @@ TEST_F(ParseFlagsTest, Repeat) {
   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
 }
 
+// Tests parsing --gtest_recreate_environments_when_repeating
+TEST_F(ParseFlagsTest, RecreateEnvironmentsWhenRepeating) {
+  const char* argv[] = {
+      "foo.exe",
+      "--gtest_recreate_environments_when_repeating=0",
+      nullptr,
+  };
+
+  const char* argv2[] = {"foo.exe", nullptr};
+
+  GTEST_TEST_PARSING_FLAGS_(
+      argv, argv2, Flags::RecreateEnvironmentsWhenRepeating(false), false);
+}
+
 // Tests having a --gtest_also_run_disabled_tests flag
 TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) {
   const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr};
@@ -6235,8 +6129,8 @@ TEST_F(ParseFlagsTest, StreamResultTo) {
 
   const char* argv2[] = {"foo.exe", nullptr};
 
-  GTEST_TEST_PARSING_FLAGS_(
-      argv, argv2, Flags::StreamResultTo("localhost:1234"), false);
+  GTEST_TEST_PARSING_FLAGS_(argv, argv2,
+                            Flags::StreamResultTo("localhost:1234"), false);
 }
 
 // Tests parsing --gtest_throw_on_failure.
@@ -6267,23 +6161,69 @@ TEST_F(ParseFlagsTest, ThrowOnFailureTrue) {
   GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
 }
 
-# if GTEST_OS_WINDOWS
+// Tests parsing a bad --gtest_filter flag.
+TEST_F(ParseFlagsTest, FilterBad) {
+  const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
+
+  const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr};
+
+#if GTEST_HAS_ABSL && GTEST_HAS_DEATH_TEST
+  // Invalid flag arguments are a fatal error when using the Abseil Flags.
+  EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true),
+              testing::ExitedWithCode(1),
+              "ERROR: Missing the value for the flag 'gtest_filter'");
+#elif !GTEST_HAS_ABSL
+  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
+#else
+  static_cast<void>(argv);
+  static_cast<void>(argv2);
+#endif
+}
+
+// Tests parsing --gtest_output (invalid).
+TEST_F(ParseFlagsTest, OutputEmpty) {
+  const char* argv[] = {"foo.exe", "--gtest_output", nullptr};
+
+  const char* argv2[] = {"foo.exe", "--gtest_output", nullptr};
+
+#if GTEST_HAS_ABSL && GTEST_HAS_DEATH_TEST
+  // Invalid flag arguments are a fatal error when using the Abseil Flags.
+  EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true),
+              testing::ExitedWithCode(1),
+              "ERROR: Missing the value for the flag 'gtest_output'");
+#elif !GTEST_HAS_ABSL
+  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
+#else
+  static_cast<void>(argv);
+  static_cast<void>(argv2);
+#endif
+}
+
+#if GTEST_HAS_ABSL
+TEST_F(ParseFlagsTest, AbseilPositionalFlags) {
+  const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", "--",
+                        "--other_flag", nullptr};
+
+  // When using Abseil flags, it should be possible to pass flags not recognized
+  // using "--" to delimit positional arguments. These flags should be returned
+  // though argv.
+  const char* argv2[] = {"foo.exe", "--other_flag", nullptr};
+
+  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
+}
+#endif
+
+#if GTEST_OS_WINDOWS
 // Tests parsing wide strings.
 TEST_F(ParseFlagsTest, WideStrings) {
-  const wchar_t* argv[] = {
-    L"foo.exe",
-    L"--gtest_filter=Foo*",
-    L"--gtest_list_tests=1",
-    L"--gtest_break_on_failure",
-    L"--non_gtest_flag",
-    NULL
-  };
+  const wchar_t* argv[] = {L"foo.exe",
+                           L"--gtest_filter=Foo*",
+                           L"--gtest_list_tests=1",
+                           L"--gtest_break_on_failure",
+                           L"--non_gtest_flag",
+                           NULL};
 
-  const wchar_t* argv2[] = {
-    L"foo.exe",
-    L"--non_gtest_flag",
-    NULL
-  };
+  const wchar_t* argv2[] = {L"foo.exe", L"--non_gtest_flag", NULL};
 
   Flags expected_flags;
   expected_flags.break_on_failure = true;
@@ -6292,7 +6232,7 @@ TEST_F(ParseFlagsTest, 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 {
@@ -6340,8 +6280,8 @@ TEST_F(FlagfileTest, Empty) {
 
 // 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"));
+  internal::FilePath flagfile_path(
+      CreateFlagfile("--" GTEST_FLAG_PREFIX_ "filter=abc"));
   std::string flagfile_flag =
       std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
 
@@ -6354,10 +6294,10 @@ TEST_F(FlagfileTest, FilterNonEmpty) {
 
 // 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"));
+  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();
 
@@ -6381,8 +6321,7 @@ class CurrentTestInfoTest : public Test {
   // the test case is run.
   static void SetUpTestSuite() {
     // There should be no tests running at this point.
-    const TestInfo* test_info =
-      UnitTest::GetInstance()->current_test_info();
+    const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
     EXPECT_TRUE(test_info == nullptr)
         << "There should be no tests running at this point.";
   }
@@ -6390,8 +6329,7 @@ class CurrentTestInfoTest : public Test {
   // Tests that current_test_info() returns NULL after the last test in
   // the test case has run.
   static void TearDownTestSuite() {
-    const TestInfo* test_info =
-      UnitTest::GetInstance()->current_test_info();
+    const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
     EXPECT_TRUE(test_info == nullptr)
         << "There should be no tests running at this point.";
   }
@@ -6400,8 +6338,7 @@ class CurrentTestInfoTest : public Test {
 // Tests that current_test_info() returns TestInfo for currently running
 // test by checking the expected test name against the actual one.
 TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) {
-  const TestInfo* test_info =
-    UnitTest::GetInstance()->current_test_info();
+  const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
   ASSERT_TRUE(nullptr != test_info)
       << "There is a test running so we should have a valid TestInfo.";
   EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
@@ -6415,8 +6352,7 @@ TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) {
 // use this test to see that the TestInfo object actually changed from
 // the previous invocation.
 TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) {
-  const TestInfo* test_info =
-    UnitTest::GetInstance()->current_test_info();
+  const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
   ASSERT_TRUE(nullptr != test_info)
       << "There is a test running so we should have a valid TestInfo.";
   EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
@@ -6427,7 +6363,6 @@ TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) {
 
 }  // 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 {
@@ -6476,13 +6411,12 @@ TEST(StreamingAssertionsTest, Unconditional) {
   SUCCEED() << "expected success";
   EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
                           "expected failure");
-  EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
-                       "expected failure");
+  EXPECT_FATAL_FAILURE(FAIL() << "expected failure", "expected failure");
 }
 
 #ifdef __BORLANDC__
 // Silences warnings: "Condition is always true", "Unreachable code"
-# pragma option push -w-ccc -w-rch
+#pragma option push -w-ccc -w-rch
 #endif
 
 TEST(StreamingAssertionsTest, Truth) {
@@ -6505,7 +6439,7 @@ TEST(StreamingAssertionsTest, Truth2) {
 
 #ifdef __BORLANDC__
 // Restores warnings after previous "#pragma option push" suppressed them
-# pragma option pop
+#pragma option pop
 #endif
 
 TEST(StreamingAssertionsTest, IntegerEquals) {
@@ -6576,28 +6510,32 @@ TEST(StreamingAssertionsTest, FloatingPointEquals) {
 TEST(StreamingAssertionsTest, Throw) {
   EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
   ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
-  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
-                          "expected failure", "expected failure");
-  EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
-                       "expected failure", "expected failure");
+  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool)
+                              << "expected failure",
+                          "expected failure");
+  EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool)
+                           << "expected failure",
+                       "expected failure");
 }
 
 TEST(StreamingAssertionsTest, NoThrow) {
   EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
   ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
-  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
-                          "expected failure", "expected failure");
-  EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
-                       "expected failure", "expected failure");
+  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger())
+                              << "expected failure",
+                          "expected failure");
+  EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) << "expected failure",
+                       "expected failure");
 }
 
 TEST(StreamingAssertionsTest, AnyThrow) {
   EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
   ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
-  EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
-                          "expected failure", "expected failure");
-  EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
-                       "expected failure", "expected failure");
+  EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing())
+                              << "expected failure",
+                          "expected failure");
+  EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) << "expected failure",
+                       "expected failure");
 }
 
 #endif  // GTEST_HAS_EXCEPTIONS
@@ -6605,65 +6543,65 @@ TEST(StreamingAssertionsTest, AnyThrow) {
 // Tests that Google Test correctly decides whether to use colors in the output.
 
 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
-  GTEST_FLAG(color) = "yes";
+  GTEST_FLAG_SET(color, "yes");
 
-  SetEnv("TERM", "xterm");  // TERM supports colors.
-  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
+  SetEnv("TERM", "xterm");             // TERM supports colors.
+  EXPECT_TRUE(ShouldUseColor(true));   // Stdout is a TTY.
   EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
 
-  SetEnv("TERM", "dumb");  // TERM doesn't support colors.
-  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
+  SetEnv("TERM", "dumb");              // TERM doesn't support colors.
+  EXPECT_TRUE(ShouldUseColor(true));   // Stdout is a TTY.
   EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
 }
 
 TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
   SetEnv("TERM", "dumb");  // TERM doesn't support colors.
 
-  GTEST_FLAG(color) = "True";
+  GTEST_FLAG_SET(color, "True");
   EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
 
-  GTEST_FLAG(color) = "t";
+  GTEST_FLAG_SET(color, "t");
   EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
 
-  GTEST_FLAG(color) = "1";
+  GTEST_FLAG_SET(color, "1");
   EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.
 }
 
 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
-  GTEST_FLAG(color) = "no";
+  GTEST_FLAG_SET(color, "no");
 
-  SetEnv("TERM", "xterm");  // TERM supports colors.
-  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
+  SetEnv("TERM", "xterm");              // TERM supports colors.
+  EXPECT_FALSE(ShouldUseColor(true));   // Stdout is a TTY.
   EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.
 
-  SetEnv("TERM", "dumb");  // TERM doesn't support colors.
-  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
+  SetEnv("TERM", "dumb");               // TERM doesn't support colors.
+  EXPECT_FALSE(ShouldUseColor(true));   // Stdout is a TTY.
   EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.
 }
 
 TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
   SetEnv("TERM", "xterm");  // TERM supports colors.
 
-  GTEST_FLAG(color) = "F";
+  GTEST_FLAG_SET(color, "F");
   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
 
-  GTEST_FLAG(color) = "0";
+  GTEST_FLAG_SET(color, "0");
   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
 
-  GTEST_FLAG(color) = "unknown";
+  GTEST_FLAG_SET(color, "unknown");
   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
 }
 
 TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
-  GTEST_FLAG(color) = "auto";
+  GTEST_FLAG_SET(color, "auto");
 
-  SetEnv("TERM", "xterm");  // TERM supports colors.
+  SetEnv("TERM", "xterm");              // TERM supports colors.
   EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.
   EXPECT_TRUE(ShouldUseColor(true));    // Stdout is a TTY.
 }
 
 TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
-  GTEST_FLAG(color) = "auto";
+  GTEST_FLAG_SET(color, "auto");
 
 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
   // On Windows, we ignore the TERM variable as it's usually not set.
@@ -6680,49 +6618,49 @@ TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
   // On non-Windows platforms, we rely on TERM to determine if the
   // terminal supports colors.
 
-  SetEnv("TERM", "dumb");  // TERM doesn't support colors.
+  SetEnv("TERM", "dumb");              // TERM doesn't support colors.
   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
 
-  SetEnv("TERM", "emacs");  // TERM doesn't support colors.
+  SetEnv("TERM", "emacs");             // TERM doesn't support colors.
   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
 
-  SetEnv("TERM", "vt100");  // TERM doesn't support colors.
+  SetEnv("TERM", "vt100");             // TERM doesn't support colors.
   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
 
-  SetEnv("TERM", "xterm-mono");  // TERM doesn't support colors.
+  SetEnv("TERM", "xterm-mono");        // TERM doesn't support colors.
   EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.
 
-  SetEnv("TERM", "xterm");  // TERM supports colors.
+  SetEnv("TERM", "xterm");            // TERM supports colors.
   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
 
-  SetEnv("TERM", "xterm-color");  // TERM supports colors.
+  SetEnv("TERM", "xterm-color");      // TERM supports colors.
   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
 
-  SetEnv("TERM", "xterm-256color");  // TERM supports colors.
+  SetEnv("TERM", "xterm-256color");   // TERM supports colors.
   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
 
-  SetEnv("TERM", "screen");  // TERM supports colors.
+  SetEnv("TERM", "screen");           // TERM supports colors.
   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
 
   SetEnv("TERM", "screen-256color");  // TERM supports colors.
   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
 
-  SetEnv("TERM", "tmux");  // TERM supports colors.
+  SetEnv("TERM", "tmux");             // TERM supports colors.
   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
 
-  SetEnv("TERM", "tmux-256color");  // TERM supports colors.
+  SetEnv("TERM", "tmux-256color");    // TERM supports colors.
   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
 
-  SetEnv("TERM", "rxvt-unicode");  // TERM supports colors.
+  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.
+  EXPECT_TRUE(ShouldUseColor(true));        // Stdout is a TTY.
 
-  SetEnv("TERM", "linux");  // TERM supports colors.
+  SetEnv("TERM", "linux");            // TERM supports colors.
   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
 
-  SetEnv("TERM", "cygwin");  // TERM supports colors.
+  SetEnv("TERM", "cygwin");           // TERM supports colors.
   EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.
 #endif  // GTEST_OS_WINDOWS
 }
@@ -6842,12 +6780,10 @@ class TestListener : public EmptyTestEventListener {
  public:
   TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {}
   TestListener(int* on_start_counter, bool* is_destroyed)
-      : on_start_counter_(on_start_counter),
-        is_destroyed_(is_destroyed) {}
+      : on_start_counter_(on_start_counter), is_destroyed_(is_destroyed) {}
 
   ~TestListener() override {
-    if (is_destroyed_)
-      *is_destroyed_ = true;
+    if (is_destroyed_) *is_destroyed_ = true;
   }
 
  protected:
@@ -6904,8 +6840,8 @@ TEST(TestEventListenersTest, Append) {
   {
     TestEventListeners listeners;
     listeners.Append(listener);
-    TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
-        *UnitTest::GetInstance());
+    TestEventListenersAccessor::GetRepeater(&listeners)
+        ->OnTestProgramStart(*UnitTest::GetInstance());
     EXPECT_EQ(1, on_start_counter);
   }
   EXPECT_TRUE(is_destroyed);
@@ -6948,7 +6884,8 @@ class SequenceTestingListener : public EmptyTestEventListener {
   std::vector<std::string>* vector_;
   const char* const id_;
 
-  GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
+  SequenceTestingListener(const SequenceTestingListener&) = delete;
+  SequenceTestingListener& operator=(const SequenceTestingListener&) = delete;
 };
 
 TEST(EventListenerTest, AppendKeepsOrder) {
@@ -6958,32 +6895,32 @@ TEST(EventListenerTest, AppendKeepsOrder) {
   listeners.Append(new SequenceTestingListener(&vec, "2nd"));
   listeners.Append(new SequenceTestingListener(&vec, "3rd"));
 
-  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
-      *UnitTest::GetInstance());
+  TestEventListenersAccessor::GetRepeater(&listeners)
+      ->OnTestProgramStart(*UnitTest::GetInstance());
   ASSERT_EQ(3U, vec.size());
   EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
   EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
   EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
 
   vec.clear();
-  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
-      *UnitTest::GetInstance());
+  TestEventListenersAccessor::GetRepeater(&listeners)
+      ->OnTestProgramEnd(*UnitTest::GetInstance());
   ASSERT_EQ(3U, vec.size());
   EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
   EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
   EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
 
   vec.clear();
-  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
-      *UnitTest::GetInstance(), 0);
+  TestEventListenersAccessor::GetRepeater(&listeners)
+      ->OnTestIterationStart(*UnitTest::GetInstance(), 0);
   ASSERT_EQ(3U, vec.size());
   EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
   EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
   EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
 
   vec.clear();
-  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
-      *UnitTest::GetInstance(), 0);
+  TestEventListenersAccessor::GetRepeater(&listeners)
+      ->OnTestIterationEnd(*UnitTest::GetInstance(), 0);
   ASSERT_EQ(3U, vec.size());
   EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
   EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
@@ -7003,8 +6940,8 @@ TEST(TestEventListenersTest, Release) {
     TestEventListeners listeners;
     listeners.Append(listener);
     EXPECT_EQ(listener, listeners.Release(listener));
-    TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
-        *UnitTest::GetInstance());
+    TestEventListenersAccessor::GetRepeater(&listeners)
+        ->OnTestProgramStart(*UnitTest::GetInstance());
     EXPECT_TRUE(listeners.Release(listener) == nullptr);
   }
   EXPECT_EQ(0, on_start_counter);
@@ -7022,17 +6959,20 @@ TEST(EventListenerTest, SuppressEventForwarding) {
   ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
   TestEventListenersAccessor::SuppressEventForwarding(&listeners);
   ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
-  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
-      *UnitTest::GetInstance());
+  TestEventListenersAccessor::GetRepeater(&listeners)
+      ->OnTestProgramStart(*UnitTest::GetInstance());
   EXPECT_EQ(0, on_start_counter);
 }
 
 // Tests that events generated by Google Test are not forwarded in
 // death test subprocesses.
 TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
-  EXPECT_DEATH_IF_SUPPORTED({
-      GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
-          *GetUnitTestImpl()->listeners())) << "expected failure";},
+  EXPECT_DEATH_IF_SUPPORTED(
+      {
+        GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
+            *GetUnitTestImpl()->listeners()))
+            << "expected failure";
+      },
       "expected failure");
 }
 
@@ -7049,8 +6989,8 @@ TEST(EventListenerTest, default_result_printer) {
 
   EXPECT_EQ(listener, listeners.default_result_printer());
 
-  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
-      *UnitTest::GetInstance());
+  TestEventListenersAccessor::GetRepeater(&listeners)
+      ->OnTestProgramStart(*UnitTest::GetInstance());
 
   EXPECT_EQ(1, on_start_counter);
 
@@ -7063,8 +7003,8 @@ TEST(EventListenerTest, default_result_printer) {
 
   // After broadcasting an event the counter is still the same, indicating
   // the listener is not in the list anymore.
-  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
-      *UnitTest::GetInstance());
+  TestEventListenersAccessor::GetRepeater(&listeners)
+      ->OnTestProgramStart(*UnitTest::GetInstance());
   EXPECT_EQ(1, on_start_counter);
 }
 
@@ -7086,8 +7026,8 @@ TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
     EXPECT_FALSE(is_destroyed);
 
     // Broadcasting events now should not affect default_result_printer.
-    TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
-        *UnitTest::GetInstance());
+    TestEventListenersAccessor::GetRepeater(&listeners)
+        ->OnTestProgramStart(*UnitTest::GetInstance());
     EXPECT_EQ(0, on_start_counter);
   }
   // Destroying the list should not affect the listener now, too.
@@ -7108,8 +7048,8 @@ TEST(EventListenerTest, default_xml_generator) {
 
   EXPECT_EQ(listener, listeners.default_xml_generator());
 
-  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
-      *UnitTest::GetInstance());
+  TestEventListenersAccessor::GetRepeater(&listeners)
+      ->OnTestProgramStart(*UnitTest::GetInstance());
 
   EXPECT_EQ(1, on_start_counter);
 
@@ -7122,8 +7062,8 @@ TEST(EventListenerTest, default_xml_generator) {
 
   // After broadcasting an event the counter is still the same, indicating
   // the listener is not in the list anymore.
-  TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
-      *UnitTest::GetInstance());
+  TestEventListenersAccessor::GetRepeater(&listeners)
+      ->OnTestProgramStart(*UnitTest::GetInstance());
   EXPECT_EQ(1, on_start_counter);
 }
 
@@ -7145,8 +7085,8 @@ TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
     EXPECT_FALSE(is_destroyed);
 
     // Broadcasting events now should not affect default_xml_generator.
-    TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
-        *UnitTest::GetInstance());
+    TestEventListenersAccessor::GetRepeater(&listeners)
+        ->OnTestProgramStart(*UnitTest::GetInstance());
     EXPECT_EQ(0, on_start_counter);
   }
   // Destroying the list should not affect the listener now, too.
@@ -7154,7 +7094,7 @@ TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
   delete listener;
 }
 
-// Sanity tests to ensure that the alternative, verbose spellings of
+// Tests to ensure that the alternative, verbose spellings of
 // some of the macros work.  We don't test them thoroughly as that
 // would be quite involved.  Since their implementations are
 // straightforward, and they are rarely used, we'll just rely on the
@@ -7234,28 +7174,26 @@ struct IncompleteType;
 // Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time
 // constant.
 TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) {
-  GTEST_COMPILE_ASSERT_(
-      HasDebugStringAndShortDebugString<HasDebugStringMethods>::value,
-      const_true);
-  GTEST_COMPILE_ASSERT_(
+  static_assert(HasDebugStringAndShortDebugString<HasDebugStringMethods>::value,
+                "const_true");
+  static_assert(
       HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value,
-      const_true);
-  GTEST_COMPILE_ASSERT_(HasDebugStringAndShortDebugString<
-                            const InheritsDebugStringMethods>::value,
-                        const_true);
-  GTEST_COMPILE_ASSERT_(
+      "const_true");
+  static_assert(HasDebugStringAndShortDebugString<
+                    const InheritsDebugStringMethods>::value,
+                "const_true");
+  static_assert(
       !HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value,
-      const_false);
-  GTEST_COMPILE_ASSERT_(
+      "const_false");
+  static_assert(
       !HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value,
-      const_false);
-  GTEST_COMPILE_ASSERT_(
+      "const_false");
+  static_assert(
       !HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value,
-      const_false);
-  GTEST_COMPILE_ASSERT_(
-      !HasDebugStringAndShortDebugString<IncompleteType>::value, const_false);
-  GTEST_COMPILE_ASSERT_(!HasDebugStringAndShortDebugString<int>::value,
-                        const_false);
+      "const_false");
+  static_assert(!HasDebugStringAndShortDebugString<IncompleteType>::value,
+                "const_false");
+  static_assert(!HasDebugStringAndShortDebugString<int>::value, "const_false");
 }
 
 // Tests that HasDebugStringAndShortDebugString<T>::value is true when T has
@@ -7306,7 +7244,6 @@ TEST(GTestReferenceToConstTest, Works) {
   TestGTestReferenceToConst<const std::string&, const std::string&>();
 }
 
-
 // Tests IsContainerTest.
 
 class NonContainer {};
@@ -7318,10 +7255,9 @@ TEST(IsContainerTestTest, WorksForNonContainer) {
 }
 
 TEST(IsContainerTestTest, WorksForContainer) {
+  EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<std::vector<bool>>(0)));
   EXPECT_EQ(sizeof(IsContainer),
-            sizeof(IsContainerTest<std::vector<bool> >(0)));
-  EXPECT_EQ(sizeof(IsContainer),
-            sizeof(IsContainerTest<std::map<int, double> >(0)));
+            sizeof(IsContainerTest<std::map<int, double>>(0)));
 }
 
 struct ConstOnlyContainerWithPointerIterator {
@@ -7370,8 +7306,8 @@ TEST(ArrayEqTest, WorksForDegeneratedArrays) {
 
 TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
   // Note that a and b are distinct but compatible types.
-  const int a[] = { 0, 1 };
-  long b[] = { 0, 1 };
+  const int a[] = {0, 1};
+  long b[] = {0, 1};
   EXPECT_TRUE(ArrayEq(a, b));
   EXPECT_TRUE(ArrayEq(a, 2, b));
 
@@ -7381,9 +7317,9 @@ TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
 }
 
 TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
-  const char a[][3] = { "hi", "lo" };
-  const char b[][3] = { "hi", "lo" };
-  const char c[][3] = { "hi", "li" };
+  const char a[][3] = {"hi", "lo"};
+  const char b[][3] = {"hi", "lo"};
+  const char c[][3] = {"hi", "li"};
 
   EXPECT_TRUE(ArrayEq(a, b));
   EXPECT_TRUE(ArrayEq(a, 2, b));
@@ -7401,11 +7337,11 @@ TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
 }
 
 TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
-  int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
-  const int b[2] = { 2, 3 };
+  int a[][2] = {{0, 1}, {2, 3}, {4, 5}};
+  const int b[2] = {2, 3};
   EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
 
-  const int c[2] = { 6, 7 };
+  const int c[2] = {6, 7};
   EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
 }
 
@@ -7431,7 +7367,7 @@ TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
 }
 
 TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
-  const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
+  const int a[2][3] = {{0, 1, 2}, {3, 4, 5}};
   int b[2][3];
 #ifndef __BORLANDC__  // C++Builder cannot compile some array size deductions.
   CopyArray(a, &b);
@@ -7446,7 +7382,7 @@ TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
 // Tests NativeArray.
 
 TEST(NativeArrayTest, ConstructorFromArrayWorks) {
-  const int a[3] = { 0, 1, 2 };
+  const int a[3] = {0, 1, 2};
   NativeArray<int> na(a, 3, RelationToSourceReference());
   EXPECT_EQ(3U, na.size());
   EXPECT_EQ(a, na.begin());
@@ -7476,7 +7412,7 @@ TEST(NativeArrayTest, TypeMembersAreCorrect) {
 }
 
 TEST(NativeArrayTest, MethodsWork) {
-  const int a[3] = { 0, 1, 2 };
+  const int a[3] = {0, 1, 2};
   NativeArray<int> na(a, 3, RelationToSourceCopy());
   ASSERT_EQ(3U, na.size());
   EXPECT_EQ(3, na.end() - na.begin());
@@ -7495,14 +7431,14 @@ TEST(NativeArrayTest, MethodsWork) {
   NativeArray<int> na2(a, 3, RelationToSourceReference());
   EXPECT_TRUE(na == na2);
 
-  const int b1[3] = { 0, 1, 1 };
-  const int b2[4] = { 0, 1, 2, 3 };
+  const int b1[3] = {0, 1, 1};
+  const int b2[4] = {0, 1, 2, 3};
   EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));
   EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));
 }
 
 TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
-  const char a[2][3] = { "hi", "lo" };
+  const char a[2][3] = {"hi", "lo"};
   NativeArray<char[3]> na(a, 2, RelationToSourceReference());
   ASSERT_EQ(2U, na.size());
   EXPECT_EQ(a, na.begin());
@@ -7782,3 +7718,35 @@ TEST(RegisterTest, WasRegistered) {
 
   FAIL() << "Didn't find the test!";
 }
+
+// Test that the pattern globbing algorithm is linear. If not, this test should
+// time out.
+TEST(PatternGlobbingTest, MatchesFilterLinearRuntime) {
+  std::string name(100, 'a');  // Construct the string (a^100)b
+  name.push_back('b');
+
+  std::string pattern;  // Construct the string ((a*)^100)b
+  for (int i = 0; i < 100; ++i) {
+    pattern.append("a*");
+  }
+  pattern.push_back('b');
+
+  EXPECT_TRUE(
+      testing::internal::UnitTestOptions::MatchesFilter(name, pattern.c_str()));
+}
+
+TEST(PatternGlobbingTest, MatchesFilterWithMultiplePatterns) {
+  const std::string name = "aaaa";
+  EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "a*"));
+  EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "a*:"));
+  EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab"));
+  EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab:"));
+  EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab:a*"));
+}
+
+TEST(PatternGlobbingTest, MatchesFilterEdgeCases) {
+  EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter("", "*a"));
+  EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter("", "*"));
+  EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter("a", ""));
+  EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter("", ""));
+}
index ac66feb66719e62cfa16c79a17f63de990f277c1..c129e64b90515ffa404a9ac505e0366bd109e013 100755 (executable)
@@ -33,8 +33,8 @@
 
 import os
 from xml.dom import minidom, Node
-import gtest_test_utils
-import gtest_xml_test_utils
+from googletest.test import gtest_test_utils
+from googletest.test import gtest_xml_test_utils
 
 GTEST_OUTPUT_SUBDIR = "xml_outfiles"
 GTEST_OUTPUT_1_TEST = "gtest_xml_outfile1_test_"
@@ -43,7 +43,7 @@ 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" skipped="0" disabled="0" errors="0" time="*" timestamp="*">
-    <testcase name="TestSomeProperties" status="run" result="completed" time="*" timestamp="*" classname="PropertyOne">
+    <testcase name="TestSomeProperties" file="gtest_xml_outfile1_test_.cc" line="41" status="run" result="completed" time="*" timestamp="*" classname="PropertyOne">
       <properties>
         <property name="SetUpProp" value="1"/>
         <property name="TestSomeProperty" value="1"/>
@@ -57,7 +57,7 @@ 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" skipped="0" disabled="0" errors="0" time="*" timestamp="*">
-    <testcase name="TestSomeProperties" status="run" result="completed" time="*" timestamp="*" classname="PropertyTwo">
+    <testcase name="TestSomeProperties" file="gtest_xml_outfile2_test_.cc" line="41" status="run" result="completed" time="*" timestamp="*" classname="PropertyTwo">
       <properties>
         <property name="SetUpProp" value="2"/>
         <property name="TestSomeProperty" value="2"/>
index eade7aac88f59e6bb6f5ba341828bae46fcd006f..e1b7f1fc83d44501ba3b5f2d4ac5993422464a9d 100755 (executable)
@@ -38,8 +38,8 @@ import re
 import sys
 from xml.dom import minidom, Node
 
-import gtest_test_utils
-import gtest_xml_test_utils
+from googletest.test import gtest_test_utils
+from googletest.test import gtest_xml_test_utils
 
 GTEST_FILTER_FLAG = '--gtest_filter'
 GTEST_LIST_TESTS_FLAG = '--gtest_list_tests'
@@ -67,10 +67,10 @@ else:
 EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
 <testsuites tests="26" failures="5" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42">
   <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
-    <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
+    <testcase name="Succeeds" file="gtest_xml_output_unittest_.cc" line="51" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
   </testsuite>
   <testsuite name="FailedTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
-    <testcase name="Fails" status="run" result="completed" time="*" timestamp="*" classname="FailedTest">
+    <testcase name="Fails" file="gtest_xml_output_unittest_.cc" line="59" status="run" result="completed" time="*" timestamp="*" classname="FailedTest">
       <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A;  1&#x0A;  2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
 Expected equality of these values:
   1
@@ -78,8 +78,8 @@ Expected equality of these values:
     </testcase>
   </testsuite>
   <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" skipped="0" errors="0" time="*" timestamp="*">
-    <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest"/>
-    <testcase name="Fails" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest">
+    <testcase name="Succeeds" file="gtest_xml_output_unittest_.cc" line="86" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest"/>
+    <testcase name="Fails" file="gtest_xml_output_unittest_.cc" line="91" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest">
       <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A;  1&#x0A;  2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
 Expected equality of these values:
   1
@@ -89,35 +89,35 @@ Expected equality of these values:
   2
   3%(stack)s]]></failure>
     </testcase>
-    <testcase name="DISABLED_test" status="notrun" result="suppressed" time="*" timestamp="*" classname="MixedResultTest"/>
+    <testcase name="DISABLED_test" file="gtest_xml_output_unittest_.cc" line="96" status="notrun" result="suppressed" time="*" timestamp="*" classname="MixedResultTest"/>
   </testsuite>
   <testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
-    <testcase name="OutputsCData" status="run" result="completed" time="*" timestamp="*" classname="XmlQuotingTest">
+    <testcase name="OutputsCData" file="gtest_xml_output_unittest_.cc" line="100" status="run" result="completed" time="*" timestamp="*" classname="XmlQuotingTest">
       <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;XML output: &lt;?xml encoding=&quot;utf-8&quot;&gt;&lt;top&gt;&lt;![CDATA[cdata text]]&gt;&lt;/top&gt;" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
 Failed
 XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]&gt;<![CDATA[</top>%(stack)s]]></failure>
     </testcase>
   </testsuite>
   <testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
-    <testcase name="InvalidCharactersInMessage" status="run" result="completed" time="*" timestamp="*" classname="InvalidCharactersTest">
+    <testcase name="InvalidCharactersInMessage" file="gtest_xml_output_unittest_.cc" line="107" status="run" result="completed" time="*" timestamp="*" classname="InvalidCharactersTest">
       <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
 Failed
 Invalid characters in brackets []%(stack)s]]></failure>
     </testcase>
   </testsuite>
   <testsuite name="DisabledTest" tests="1" failures="0" disabled="1" skipped="0" errors="0" time="*" timestamp="*">
-    <testcase name="DISABLED_test_not_run" status="notrun" result="suppressed" time="*" timestamp="*" classname="DisabledTest"/>
+    <testcase name="DISABLED_test_not_run" file="gtest_xml_output_unittest_.cc" line="66" status="notrun" result="suppressed" time="*" timestamp="*" classname="DisabledTest"/>
   </testsuite>
   <testsuite name="SkippedTest" tests="3" failures="1" disabled="0" skipped="2" errors="0" time="*" timestamp="*">
-    <testcase name="Skipped" status="run" result="skipped" time="*" timestamp="*" classname="SkippedTest">
+    <testcase name="Skipped" status="run" file="gtest_xml_output_unittest_.cc" line="73" result="skipped" time="*" timestamp="*" classname="SkippedTest">
       <skipped message="gtest_xml_output_unittest_.cc:*&#x0A;"><![CDATA[gtest_xml_output_unittest_.cc:*
 %(stack)s]]></skipped>
     </testcase>
-    <testcase name="SkippedWithMessage" status="run" result="skipped" time="*" timestamp="*" classname="SkippedTest">
+    <testcase name="SkippedWithMessage" file="gtest_xml_output_unittest_.cc" line="77" status="run" result="skipped" time="*" timestamp="*" classname="SkippedTest">
       <skipped message="gtest_xml_output_unittest_.cc:*&#x0A;It is good practice to tell why you skip a test."><![CDATA[gtest_xml_output_unittest_.cc:*
 It is good practice to tell why you skip a test.%(stack)s]]></skipped>
     </testcase>
-    <testcase name="SkippedAfterFailure" status="run" result="completed" time="*" timestamp="*" classname="SkippedTest">
+    <testcase name="SkippedAfterFailure" file="gtest_xml_output_unittest_.cc" line="81" status="run" result="completed" time="*" timestamp="*" classname="SkippedTest">
       <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A;  1&#x0A;  2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
 Expected equality of these values:
   1
@@ -128,63 +128,63 @@ It is good practice to tell why you skip a test.%(stack)s]]></skipped>
 
   </testsuite>
   <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
-    <testcase name="OneProperty" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
+    <testcase name="OneProperty" file="gtest_xml_output_unittest_.cc" line="119" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
       <properties>
         <property name="key_1" value="1"/>
       </properties>
     </testcase>
-    <testcase name="IntValuedProperty" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
+    <testcase name="IntValuedProperty" file="gtest_xml_output_unittest_.cc" line="123" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
       <properties>
         <property name="key_int" value="1"/>
       </properties>
     </testcase>
-    <testcase name="ThreeProperties" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
+    <testcase name="ThreeProperties" file="gtest_xml_output_unittest_.cc" line="127" status="run" result="completed" time="*" timestamp="*" 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" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
+    <testcase name="TwoValuesForOneKeyUsesLastValue" file="gtest_xml_output_unittest_.cc" line="133" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
       <properties>
         <property name="key_1" value="2"/>
       </properties>
     </testcase>
   </testsuite>
   <testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
-     <testcase name="RecordProperty" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
+     <testcase name="RecordProperty" file="gtest_xml_output_unittest_.cc" line="138" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
        <properties>
          <property name="key" value="1"/>
        </properties>
      </testcase>
-     <testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
+     <testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" file="gtest_xml_output_unittest_.cc" line="151" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
        <properties>
          <property name="key_for_utility_int" value="1"/>
        </properties>
      </testcase>
-     <testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
+     <testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" file="gtest_xml_output_unittest_.cc" line="155" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
        <properties>
          <property name="key_for_utility_string" value="1"/>
        </properties>
      </testcase>
   </testsuite>
   <testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
-    <testcase name="HasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
-    <testcase name="HasValueParamAttribute/1" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
-    <testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
-    <testcase name="AnotherTestThatHasValueParamAttribute/1" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
+    <testcase name="HasValueParamAttribute/0" file="gtest_xml_output_unittest_.cc" line="162" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
+    <testcase name="HasValueParamAttribute/1" file="gtest_xml_output_unittest_.cc" line="162" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
+    <testcase name="AnotherTestThatHasValueParamAttribute/0" file="gtest_xml_output_unittest_.cc" line="163" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
+    <testcase name="AnotherTestThatHasValueParamAttribute/1" file="gtest_xml_output_unittest_.cc" line="163" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
   </testsuite>
   <testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
-    <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/0" />
+    <testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="171" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/0" />
   </testsuite>
   <testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
-    <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/1" />
+    <testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="171" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/1" />
   </testsuite>
   <testsuite name="Single/TypeParameterizedTestSuite/0" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
-    <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/0" />
+    <testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="178" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/0" />
   </testsuite>
   <testsuite name="Single/TypeParameterizedTestSuite/1" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
-    <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/1" />
+    <testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="178" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/1" />
   </testsuite>
 </testsuites>""" % {
     'stack': STACK_TRACE_TEMPLATE
@@ -195,24 +195,24 @@ EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
             timestamp="*" name="AllTests" ad_hoc_property="42">
   <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" skipped="0"
              errors="0" time="*" timestamp="*">
-    <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
+    <testcase name="Succeeds" file="gtest_xml_output_unittest_.cc" line="51" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
   </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" skipped="0" errors="0" time="*" timestamp="*">
-    <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
+    <testcase name="Succeeds" file="gtest_xml_output_unittest_.cc" line="51" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
   </testsuite>
   <testsuite name="PropertyRecordingTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
-    <testcase name="IntValuedProperty" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
+    <testcase name="IntValuedProperty" file="gtest_xml_output_unittest_.cc" line="123" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
       <properties>
         <property name="key_int" value="1"/>
       </properties>
     </testcase>
   </testsuite>
   <testsuite name="Single/ValueParamTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
-    <testcase name="HasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
+    <testcase name="HasValueParamAttribute/0" file="gtest_xml_output_unittest_.cc" line="162" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
   </testsuite>
 </testsuites>"""
 
index c0036aaef9df27654ae6a6ce1ded07642ca2d391..4bdb0c7e8acc71abfb8efd06f4dd7ff1b74d9c14 100644 (file)
 //
 // This program will be invoked from a Python unit test.  Don't run it
 // directly.
+// clang-format off
 
 #include "gtest/gtest.h"
 
 using ::testing::InitGoogleTest;
+using ::testing::Test;
 using ::testing::TestEventListeners;
 using ::testing::TestWithParam;
 using ::testing::UnitTest;
-using ::testing::Test;
 using ::testing::Values;
 
-class SuccessfulTest : public Test {
-};
+class SuccessfulTest : public Test {};
 
 TEST_F(SuccessfulTest, Succeeds) {
   SUCCEED() << "This is a success.";
@@ -191,3 +191,5 @@ int main(int argc, char** argv) {
   testing::Test::RecordProperty("ad_hoc_property", "42");
   return RUN_ALL_TESTS();
 }
+
+// clang-format on
index ec42c62c3b0593b3df0c0ac42880dcb3a6b8faf8..c6fb9f4438cc2979260be28b23e15bd37485d22c 100755 (executable)
@@ -31,7 +31,7 @@
 
 import re
 from xml.dom import minidom, Node
-import gtest_test_utils
+from googletest.test import gtest_test_utils
 
 GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.xml'
 
@@ -170,6 +170,10 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
     *  The stack traces are removed.
     """
 
+    if element.tagName == 'testcase':
+      source_file = element.getAttributeNode('file')
+      if source_file:
+        source_file.value = re.sub(r'^.*[/\\](.*)', '\\1', source_file.value)
     if element.tagName in ('testsuites', 'testsuite', 'testcase'):
       timestamp = element.getAttributeNode('timestamp')
       timestamp.value = re.sub(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d\d\d$',
index 41a547225423d8331a649da95f28e1fd3c5ae774..4dec8d46e247490d6b1666d870c11144d3085048 100644 (file)
@@ -46,6 +46,7 @@ class PrivateCode {
   PrivateCode();
 
   int x() const { return x_; }
+
  private:
   void set_x(int an_x) { x_ = an_x; }
   int x_;
diff --git a/library.json b/library.json
deleted file mode 100644 (file)
index f61bf00..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-{
-  "name": "googletest",
-  "keywords": "unittest, unit, test, gtest, gmock",
-  "description": "googletest is a testing framework developed by the Testing Technology team with Google's specific requirements and constraints in mind. No matter whether you work on Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it supports any kind of tests, not just unit tests.",
-   "license": "BSD-3-Clause",
-  "homepage": "https://github.com/google/googletest/blob/master/README.md",
-  "repository": {
-    "type": "git",
-    "url": "https://github.com/google/googletest.git"
-  },
-  "version": "1.10.0",
-  "frameworks": "arduino",
-  "platforms": [
-        "espressif32",
-        "espressif8266"
-  ],
-  "export": {
-        "include": [
-            "googlemock/include/*",
-            "googlemock/src/*",
-            "googletest/include/*",
-            "googletest/src/*"
-        ],
-        "exclude": [
-            "ci",
-            "googlemock/cmake",
-            "googlemock/scripts",
-            "googlemock/test",
-            "googlemock/CMakeLists.txt",
-            "googletest/cmake",
-            "googletest/scripts",
-            "googletest/test",
-            "googletest/CMakeLists.txt"
-          ]
-  },
-  "build": {
-        "flags": [
-            "-Igooglemock/include",
-            "-Igooglemock",
-            "-Igoogletest/include",
-            "-Igoogletest"
-        ],
-        "srcFilter": [
-          "+<*>",
-          "-<.git/>",
-          "-<googlemock>",
-          "-<googlemock/test/>",
-          "-<googlemock/src>",
-          "+<googlemock/src/gmock-all.cc>",
-          "+<googletest/src/gtest-all.cc>",
-          "+<googlemock/src/gmock_main.cc>",
-          "-<googletest>",
-          "-<googletest/codegear/>",
-          "-<googletest/samples>",
-          "-<googletest/test/>",
-          "-<googletest/xcode>",
-          "-<googletest/src>",
-          "+<googletest/src/gtest-all.cc>",
-          "+<googletest/src/gtest_main.cc>"
-        ]
-  }
-}